Compare commits

...

202 commits

Author SHA1 Message Date
717d446a3b fix: charge Tinkeroids two QIC for Gaia habitability
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
Viewer - Test / test_and_build (push) Waiting to run
2026-11-23 10:14:59 +00:00
405d5b6e7b fix: warn before wasting spaceship exploration power 2026-11-22 13:57:41 +00:00
dc59294a89 test: avoid duplicate chart and legacy UI fixture runs 2026-11-15 22:33:54 +00:00
622e54ea73 fix(viewer): restore all-player Over Time statistics 2026-11-15 21:57:19 +00:00
809f79bfbb docs(release): record Lost Fleet rematch release 4.17.11 2026-11-14 18:10:35 +00:00
5a7fdec4a0 fix(engine): allow valid Lost Fleet custom-map rematches 2026-11-14 18:09:24 +00:00
de287bb96e Record reconciled Gaia artwork release 4.17.10 2026-11-14 13:06:06 +00:00
a96681aa61 Add original artwork for fourteen Gaia achievements 2026-11-14 12:17:54 +00:00
8861fe0121 Record production release of four-formation achievements 4.17.9 2026-11-14 01:08:57 +00:00
58ff3f1cd5 Require four formations for both federation achievements 2026-11-14 01:06:00 +00:00
cdf0578950 Record verified production activation of Gaia achievements 4.17.8 2026-11-14 00:28:33 +00:00
d0bd5825a4 Adopt published protocol types and verify achievement release assets 2026-11-14 00:24:48 +00:00
d60485024f docs(release): record 4.17.8 asset-access blocker 2026-11-13 22:53:22 +00:00
ef589687d8 chore(engine): prepare 4.17.8 achievement pilot release 2026-11-13 22:52:01 +00:00
0f37489aa3 chore: normalize font attribution whitespace 2026-11-13 23:45:30 +01:00
1bb584e926 feat(engine): add Gaia score badge artwork in manifest revision 3 2026-11-13 23:45:30 +01:00
5499837e23 feat(engine): add achievement icons and reproducible portraits 2026-11-13 23:45:30 +01:00
a5dc982cd3 fix(engine): use BGS-compatible achievement IDs 2026-11-13 23:45:30 +01:00
a36a4aca77 feat(engine): add per-game achievement hooks and catalog 2026-11-13 23:45:30 +01:00
c39629c1b1 fix(viewer): label faction ban buttons compactly 2026-11-13 20:41:36 +00:00
c1acabcf58 fix(viewer): outline white planets in matching type highlights 2026-11-13 11:18:30 +00:00
6c139f7c4d fix(viewer): restore concurrent charge controls from legacy caches 2026-11-11 13:46:24 +00:00
cf14cb4fcd fix(analysis): enable manual saved-analysis decisions across seats 2026-11-10 08:29:02 +00:00
94db0ae68f fix(stats): replay Lost Fleet resource income and bowl selections 2026-11-09 16:20:26 +00:00
8b07831dfe fix(stats): complete Lost Fleet actions and acquisition breakdowns 2026-11-09 16:12:16 +00:00
988b145e67 fix(charges): make waits final until earlier decisions resolve 2026-11-09 12:17:42 +00:00
a196050723 fix(premoves): guard power changes and review stopped plans directly 2026-11-07 14:27:44 +00:00
facf787d03 fix(viewer): keep custom federation selection editable in planning 2026-11-07 11:40:12 +00:00
3c4b4d3173 fix(viewer): separate Deep Space sectors and polish player counters 2026-11-05 19:46:09 +00:00
8558786fc8 feat(viewer): ship Lost Fleet insignia and compact player counters 2026-11-05 19:03:08 +00:00
b2286fa32e fix: preserve planning booster reservations and map tile geometry 2026-11-05 13:34:00 +00:00
98017d2d8d feat(viewer): keep plans visible while inspecting steps 2026-11-03 23:07:19 +00:00
75590a4af8 fix(viewer): mark Lantids shared mines without hiding income 2026-11-03 22:22:41 +00:00
296a8a0a38 feat(viewer): program planned moves up to a chosen step 2026-11-03 21:42:29 +00:00
a8ace70a2e fix(viewer): silence routine plan updates and trim stale metadata 2026-11-03 13:09:53 +00:00
1b6f1f3566 test(viewer): align browser smoke with current chat controls 2026-11-02 20:04:52 +00:00
5299cc30f3 fix(viewer): reconcile completed federation plans 2026-11-02 19:56:52 +00:00
d8f540d2f9 fix(lantids): correct shared-mine rewards and scoring 2026-11-01 10:44:57 +01:00
b766f3b7a6 fix(viewer): keep desktop chat beside the players 2026-10-31 18:37:49 +01:00
f4ee221289 fix(viewer): place spectator chat beside the turn order 2026-10-31 18:34:35 +01:00
eef9f93cb4 fix(old-ui): show explorers on Lost Fleet map ships 2026-10-31 18:23:02 +01:00
5b9bc73391 fix(viewer): replace embedded chat with integrated chat control 2026-10-31 01:44:57 +01:00
3eb863b78c fix(viewer): remove redundant setup status banner 2026-10-30 23:02:35 +01:00
2480697b96 fix: clear concurrent turn actor before next round income 2026-10-30 22:13:04 +01:00
c8f319c689 fix(viewer): improve resource amount contrast 2026-10-30 09:23:46 +01:00
8dcf0caca8 fix(viewer): compact the mobile planning header 2026-10-29 21:31:37 +01:00
8b648fcce1 fix: exclude shared Lantids mines from protoplanet bonus 2026-10-29 21:15:05 +01:00
2027044fed fix: keep passed-player plans in the next round after charging 2026-10-29 15:03:31 +01:00
889184e834 fix(viewer): remove Automa symbol background panels 2026-10-27 22:48:29 +01:00
217bbc8456 fix(viewer): clarify Automa passing and show earned VP 2026-10-27 22:43:03 +01:00
41032f9274 fix(viewer): simplify Automa help and expand card details 2026-10-27 22:26:27 +01:00
0a64e1b75b fix(viewer): group Automa cards and restore last-turn results 2026-10-27 22:22:59 +01:00
702c55708b fix(viewer): clarify Automa cards and contextual help 2026-10-27 22:13:49 +01:00
8199f68ec3 Show the Automa support card on its faction board 2026-10-27 21:52:20 +01:00
a53a5a0d35 Show Automa actions and deck as board icons 2026-10-27 21:37:16 +01:00
26bd5ed488 Align Automa boards and show faction actions with game icons 2026-10-27 21:16:57 +01:00
954398848d Show Automa on the faction board with visible card details 2026-10-27 20:58:10 +01:00
7c18cc9c0e Use real exploration slots for Automa shuttles 2026-10-27 20:28:07 +01:00
cfeb270d5c Add official solo Automa with Lost Fleet support 2026-10-27 20:22:44 +01:00
9d5bbf14e9 fix: keep opponents' live boards visible during simulation 2026-10-27 18:13:39 +01:00
1b648dbcd7 fix: reconcile resolved planning income and offer empty variations 2026-10-27 17:48:44 +01:00
94d125ba2d fix: make concurrent charging opt-in and show pending charge turns 2026-10-27 17:38:53 +01:00
9f2a6d0dfe feat: allow independent charge decisions and optional waiting 2026-10-27 14:22:05 +01:00
2c4bbf2bb2 fix: keep faction help aligned with auction assignments 2026-10-26 12:12:31 +01:00
3449a057c7 fix: remove pass-the-device auction message 2026-10-26 09:54:48 +01:00
16db668c77 fix: keep premove history behind a discreet action-bar control 2026-10-25 20:59:18 +01:00
597bdc0c05 feat: retain premove history and show interrupted plans 2026-10-25 20:39:52 +01:00
a6166b0714 fix: resolve tinkering tile choices for dropped players 2026-10-25 09:32:38 +01:00
ddc17d71b6 fix: require terraforming for Mars credit action 2026-10-24 16:51:38 +02:00
80b0eea144 fix: separate Economy income from Gaia VP statistics 2026-10-23 10:13:07 +02:00
028aa0e21c fix: score Lantids first colonized planet type correctly 2026-10-22 16:38:59 +02:00
ac9318d711 Keep setup planning limited to the player's own choices 2026-10-22 16:14:25 +02:00
c4ae9cb506 Apply mine bonuses and planet counters to artifacts 2026-10-22 00:30:54 +02:00
2477b9673f Test hosted localization bundles from the production origin 2026-10-20 14:36:11 +02:00
e7092d1a94 fix: use the localized score heading in classic viewer 2026-10-20 14:32:37 +02:00
798acfa775 feat: add Simplified Chinese to both Gaia viewers 2026-10-20 14:31:14 +02:00
fb8d08ec02 Count planet artifacts toward final structure scoring 2026-10-19 20:56:22 +02:00
9667978a86 Award building round VP before advanced technology selection 2026-10-19 16:27:52 +02:00
7ec74b5328 fix(old-ui): preserve wrapped action codes during translation 2026-10-15 20:35:45 +02:00
bb1b5e98a2 fix(old-ui): wrap long special-action labels 2026-10-15 20:33:43 +02:00
f4f0860ea6 ui: show tech and booster actions on both player boards 2026-10-15 20:29:20 +02:00
ca5e0318ea fix(engine): forget faction boards when replaying into the faction selection
Engine.replayedTo carries each player's final faction variant over so the
replayed faction selection loads the boards the game was played with. When
the replay stops before the selection ends, the variant was left on the
player and the end of the selection loaded it on whatever faction was
picked next: undoing back into the faction selection and picking another
faction gave it the previous faction's board.

Reset the variant of players whose board isn't loaded at that point.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:35:40 +02:00
c97ea03ee0 fix(engine): keep player settings when replaying a game
Engine.replayedTo rebuilds the game from the move history and only
carried each player's name, dropped flag and variant over, so
wrapper.replay reset players' auto-charge/income/brainstone settings to
the defaults, and automove ran with those defaults. BGS saves the
result of replay when a player undoes a move against bots and for admin
replays, so the settings were silently lost for good.

Carry the settings over with the other per-player data. Saved analyses
still start every player with default settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:35:40 +02:00
7062118dce feat: offer "Undo my move" against bots in both viewers
BGS lets the only human of a game against bots take back their last saved
move (protocol 0.10.0). Both viewers show an "Undo my move" control with the
turn tools (an icon in the mobile action tray's title bar) while BGS reports
it available on that player's live board: never to spectators, nor in
replays, planning, BGS analysis or tutorials, nor while a queued plan awaits
the server. It asks BGS to undo; when the earlier state arrives, selections
made on the later board are dropped with the turn being composed. Back still
steps through the turn being composed, locally.

- @boardgamers/protocol 0.8.1 -> 0.10.0 (added to minimumReleaseAgeExclude)
- "Undo my move" in all 16 locales
- unit tests, a browser smoke test of both bundles, and BGS-like undo in the
  local premove preview
- viewer 5.20.58, old-ui 1.0.21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:35:40 +02:00
c93e1a8713 feat(viewer): cross out Tinkering tiles Tinkeroids already took
The Tinkeroids faction sheet (faction name -> Rules) listed all six
Tinkering tiles even mid-game. With Tinkeroids in the game, the tiles
used in earlier rounds and the one chosen this round are now crossed out
like used actions, with a tooltip saying which; none of them can be
chosen again.

New dev scenario: lost-fleet-tinkeroids-tinkering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:24:38 +02:00
9488fccc2a feat(viewer): offer Instant Gaiaforming from the Gaia Former menu
Players holding the instant Gaiaforming booster (or T F Mars's Power
action) tend to start a normal Gaia Project first and expect the action
to finish it. The action places the Gaia Former itself, needs no power
tokens in the Gaia area, and can no longer target a planet that already
has a Gaia Former.

- The Place a Gaia Former menu now lists Instant Gaiaforming first for
  each available source (booster: g, T F Mars: i), as the same move the
  special/ship action menus make. Opening the menu no longer asks for
  confirmation when every hex warns, since the instant choices don't.
- Booster, special action and T F Mars tooltips explain that the planet
  becomes Gaia right away and no power tokens move to the Gaia area
  (AI challenge manifest regenerated for the new ship-board text).
- New dev scenario: lost-fleet-instant-gaiaforming-booster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:24:38 +02:00
f578e70739 fix: use readable canonical Interspace map labels 2026-10-06 20:26:03 +02:00
cb81610a67 fix: log Gaiaformer resource spending and simulation costs 2026-10-06 19:42:34 +02:00
effc719a0a fix(viewer): scale statistics icon through a Safari-compatible SVG group 2026-10-06 13:21:26 +02:00
b4003f82fc fix(viewer): color statistics icon directly for Safari dark mode 2026-10-06 10:31:12 +02:00
3b927d64f6 fix(viewer): stop idle charge animation and clear stale notices 2026-10-05 16:48:52 +02:00
moon-coder
00c9a57c42 fix(old-ui): render federations with path-based lines
adb2413c replaced the shared federation <defs> (FederationGradients.vue,
#federation-arc/line/big-line per planet) with self-contained
{ path, color } lines drawn directly in SpaceHex.vue. old-ui's SpaceHex
keeps its own template while extending the current viewer's component, so
it still emitted <use xlink:href="#federation-…"> references to defs that
no longer exist — federations stopped rendering on the old-ui board.

Port the path-based markup (outline + colored stroke) to old-ui's
SpaceHex template and cover it with a Beta-2 fixture assertion in
game.spec.ts.
2026-10-05 09:35:59 +00:00
e3f162b1b2 fix: replace pending sealed bids in replay history 2026-10-05 02:05:40 +02:00
cac09a9c41 feat: allow revising simultaneous setup bids 2026-10-05 01:36:05 +02:00
92cd74a37a ui: show resource changes for each simulated move 2026-10-04 19:35:55 +02:00
2440f57842 ui: compact simulation controls for mobile 2026-10-04 17:39:54 +02:00
21230294cf fix: exit simulation from planning controls 2026-10-04 17:30:31 +02:00
1a0308dcae docs: remove the obsolete queue-capacity explanation 2026-10-04 12:01:09 +02:00
236e65e8c8 fix: remove the three-move premove submission limit 2026-10-04 11:59:52 +02:00
805298a241 Integrate current master and keep manual-income premove coverage 2026-10-04 11:38:32 +02:00
479da2ac00 fix(viewer): show federation token artwork in choices 2026-10-03 18:11:13 +02:00
3050d7ecc5 fix(engine): automate income orders without trade-offs 2026-10-03 18:11:02 +02:00
6d23b4bfda fix(viewer): share artifact track scoring descriptions 2026-10-02 20:28:38 +02:00
adb2413cd8 fix(viewer): draw crisp, aligned federation paths 2026-10-02 10:34:51 +02:00
5e2ef89e69
feat: show BGS Supporter badges in both viewers (#342)
* fix: use protocol 0.6.2 and remove chat scroll backports

* docs: rename demo sections to play online at

* fix: hand floating chat reminders over to the BGS rail

* feat: show BGS Supporter badges in both viewers
2026-10-02 00:01:38 +02:00
fa7a6a1217 feat: show BGS Supporter badges in both viewers 2026-10-01 23:59:25 +02:00
b30dd01963 Merge remote-tracking branch 'origin/master' into fix/mobile-out-of-turn-tools
# Conflicts:
#	viewer/package.json
2026-10-01 23:29:42 +02:00
2229fd7665 fix: reuse special action icons for Tinkeroids tile choices 2026-10-01 18:27:41 +02:00
966d80bc00 chore: bump viewer version to 5.20.42 2026-09-30 14:36:52 +02:00
e5e0894277 fix: hand floating chat reminders over to the BGS rail 2026-09-30 14:28:04 +02:00
97a3fa3bae fix: hand floating chat reminders over to the BGS rail 2026-09-30 14:25:57 +02:00
cab56d11d6 perf: split viewer languages and artwork into separate assets 2026-09-30 00:29:46 +02:00
7b2da7c39c Keep raw move log commands untranslated in every locale 2026-09-29 00:57:10 +02:00
f75b76daa7 Fix French translation of the setup log command 2026-09-29 00:52:21 +02:00
a3c3af5c22 Support host board setup with the Lost Fleet expansion 2026-09-29 00:22:48 +02:00
ed4753cd10 fix: use protocol 0.6.2 and remove chat scroll backports 2026-09-29 00:19:56 +02:00
69a6d940fd 📝 docs: add Boardgamers play link 2026-09-28 22:47:16 +02:00
39680d3c41 docs: rename demo sections to play online at 2026-09-28 22:41:11 +02:00
c2f22a450b docs: rename demo sections to play online at 2026-09-28 22:41:05 +02:00
4f9f7e694c fix: use protocol 0.6.2 and remove chat scroll backports 2026-09-28 19:50:40 +02:00
cee085b40f Fix Protoplanet bonus scoring and history checkbox labels 2026-09-28 14:49:58 +02:00
d10cff922c Add Lost Fleet rulebook link to the rules menu 2026-09-27 19:08:21 +02:00
e768b73a4c
fix(viewer): expose planning and charge in the idle mobile drawer (#340) 2026-09-27 18:57:58 +02:00
c54d602d4d
Fix chat scrolling in both Gaia Project viewers (#339) 2026-09-27 10:11:57 +02:00
26e73d54bd
fix(viewer): compact action controls and unify game icons (#338) 2026-09-27 09:34:44 +02:00
397c657b26
Add Persian viewer and tutorial translations (#337)
* Add Persian viewer and tutorial translations

* Handle missing shortcut markup without non-null assertions
2026-09-27 00:59:36 +02:00
42830754c7 fix(viewer): restore saved unread chat counts 2026-09-26 12:10:18 +02:00
4b2ba06cab Fix Korean topic particles in burning tutorial 2026-09-25 22:07:55 +02:00
fdc340665f Review viewer translations in game context and preserve shortcut labels 2026-09-25 22:03:55 +02:00
7370ce31d1 feat(viewer): localize interface and tutorials in 15 languages 2026-09-25 16:30:19 +02:00
b7908c20c6 Fix Back getting stuck in custom federation selection 2026-09-25 10:40:26 +02:00
dc97d50b11 Add optional 4-QIC tech action for two-player Lost Fleet 2026-09-24 21:42:38 +02:00
cd62fae9bf Anchor player hover cards to visible names 2026-09-24 11:49:47 +02:00
bd31210d11 Add player hover cards and board thumbnails 2026-09-24 11:44:13 +02:00
07ba1c6963 Share color-blind preference across BGS games 2026-09-23 19:45:17 +02:00
fac3634cd2 Allow editing, inserting and deleting simulated moves 2026-09-23 18:22:48 +02:00
01bb119750 Align charge and planning controls in the action toolbar 2026-09-23 12:51:36 +02:00
566e5ff487 Reduce desktop map bottom margin 2026-09-22 23:23:23 +02:00
f72abc5d8e Fit the desktop Lost Fleet map within the viewport 2026-09-22 22:58:56 +02:00
e564724728 feat(viewer): support editing chat messages 2026-09-21 22:40:08 +02:00
af9402952f fix(viewer): make chat translation controls compact 2026-09-21 21:53:09 +02:00
f047ffb15d Support analysis permissions and translated chat in both viewers 2026-09-21 20:32:47 +02:00
43b3df9055
Support saved BGS analyses (#336)
* Support saved BGS analyses with manual control of every player

* Hide live charge settings and chat in platform analyses
2026-09-21 16:18:07 +02:00
6b95308045 Let mobile scrolling continue beyond the chat message list 2026-09-21 15:20:41 +02:00
37edff66bb Reuse log resource rendering in planning and premoves 2026-09-20 17:59:17 +02:00
5054ffdd64 Show expected premove gains and unify planning resource icons 2026-09-20 17:56:39 +02:00
44d751fe27 Enlarge premove resource costs for readability 2026-09-20 17:51:26 +02:00
0430c38c5b Show premove resource spending as negative amounts 2026-09-20 17:50:04 +02:00
1a28d45847 Compact premove confirmation and queue with resource costs 2026-09-20 17:42:16 +02:00
e25370dbb6
Accept any reachable asteroid in the tutorial with one QIC (#335) 2026-09-20 16:38:17 +02:00
85a516040f
Keep auto-charge and planning in Gaia’s action bar (#334)
* Improve premoves and fix random auctions and Ivits exploration

* Fix blocked legacy random-faction sealed auctions

* Allow premoves for initial building and booster choices

* Compact setup actions and show ship explorers

* Restore auto-charge controls in Gaia game UI

* Use published player-settings protocol 0.3.4

* Allow verified protocol 0.3.4 during release-age quarantine

* Keep planning and auto-charge in the action bar outside your turn

* Bump viewer to 5.20.6 for action bar release
2026-09-19 12:02:37 +02:00
cfed58ed68
Teach range boosts and passing through native tutorial controls (#333) 2026-09-17 16:49:47 +02:00
8c50089ccd
Use native game controls throughout tutorials (#332) 2026-09-17 16:14:06 +02:00
28ff1fb405 Add playable Gaia Project tutorial course 2026-09-16 19:17:53 +02:00
2fb542b2fb Hide chat shortcut until there are unread messages 2026-09-15 11:51:31 +02:00
e3a8e0a664
Use shared BGS viewer and chat protocol (#331)
* Use shared BGS viewer and chat protocol

* Use shared chat panel with faction portraits and mobile viewport

* Update shared chat visibility and show date separators

* Keep typing after completing a chat mention
2026-09-13 22:54:32 +02:00
8967afe112 Fix chat history unread state and remove decorative tray handle 2026-09-11 20:43:58 +02:00
e299b0fd3e fix(viewer): keep mobile chat accessible beside turn controls 2026-09-11 16:42:16 +02:00
3644919458 feat(viewer): restore old UI with Lost Fleet support 2026-09-11 15:33:28 +02:00
a01f3a793c fix(viewer): mark engine options as a type-only import 2026-09-10 23:39:23 +02:00
de42325cc6
feat(viewer): add faction portraits, chat and action sounds (#330) 2026-09-10 23:37:58 +02:00
2e21d6d2d3 fix(viewer): top-align scoring tiles with tight spacing (undo fill-the-height spread)
Base (ScoringBoard) and Lost Fleet (ResearchBoard 7th column) both restyled the scoring column to
spread tiles evenly down the full board height (base) / pin finals to the action-row bottom (LF),
which read as 'spaced out'. Back to a tight top-aligned stack: base gap 4 units; Lost Fleet keeps
R6 anchored at the top, round tiles step a uniform tile+2, and the finals now sit directly below
R1's bottom edge (they previously overlapped R1 - positioned from its top, hiding it). Icons
unchanged. utils.ts researchBoardHeight/BOTTOM_SCORING_TILE_Y kept in sync (448 for LF).

viewer 5.16.2
2026-09-08 23:43:17 +02:00
7b144b807a chore(viewer): 5.16.1 - rebuild against engine 4.12.2 (federation fromData fix)
The viewer bundle embeds its own copy of the engine, so the browser-side fromData also crashed on
the object-shaped federation hexes (blank board). Rebuild picks up the fixed engine.
2026-09-08 18:31:24 +02:00
439f05baff chore(engine): 4.12.2 2026-09-08 18:00:18 +02:00
ff3bd8fd71 fix(engine): fromData accepts federation hexes saved as raw objects, not just strings
Player.toJSON serializes federationCache.federations[].hexes as coordinate strings, but a state
can be persisted with the raw hex objects (the engine's Object.assign({}, this) serialization
copies the cache by reference, bypassing the player's own toJSON). fromData then called
map.getS(object) -> 'coords.includes is not a function' during load, the viewer swallowed it, and
the board rendered blank with no console error (game Electric-plaza-5793, a Nevlas player with 4
federations). Accept both forms: string parses via getS, object is looked up by {q, r}.
2026-09-08 18:00:10 +02:00
65745dfe9e chore(engine): 4.12.1 2026-09-08 10:44:12 +02:00
1277b8ee12 fix(engine): rehydrate state in wrapper.currentPlayer before calling instance members
The game-server holds game state as plain JSON (Mongo + worker boundary both JSON-round-trip),
so currentPlayer() receives a plain object, not an Engine. sealedBidPendingSeats() is a METHOD -
it does not survive serialization - so calling it on the plain object threw
'engine.sealedBidPendingSeats is not a function' on every move in a sealed-bid game (incl. the
setup ban/pick moves, since currentPlayer runs after each). Restore via Engine.fromData like
move()/replay() already do. playerToMove survives as data (toJSON exports getters) but the method
does not, which is why this only broke once sealed bidding added a method call to currentPlayer.
2026-09-08 10:43:51 +02:00
49fc40dc40 feat(engine): simultaneous sealed bidding - any order, hidden until all in (BGS contract)
- engine.sealedBidPendingSeats(): seats still owing a bid (undefined outside bid phases)
- move()/loadTurnMoves: accept silentBid/preferenceBid from ANY pending seat regardless of
  playerToMove (was: strict turn-order assert -> 'not your turn to play' for off-turn bidders)
- bid phases resolve on the LAST pending bid, not on the sequential turn walk
- move() attributes the log line to the actual bidder, not playerToMove
- wrapper.currentPlayer() returns number[] of pending seats during bid phases (the platform's
  /move route authorizes any seat in game.currentPlayers, which it fills from currentPlayer())
- deterministic auction tiebreaks (last faction-nominator wins) replace the seeded PRNG, so the
  resolution no longer needs map.rng - which crashed hosted simultaneous bidding on a reloaded
  engine ('map.rng is not a function'); bids + nominations alone now reproduce the result
- viewer: SealedBidPanel drops the waiting-for-turn gate (every pending seat bids at once) and
  seat-prefixes the emitted move so the engine can parse the bidder

engine 4.12.0, viewer 5.16.0
2026-09-08 10:03:24 +02:00
ad99d3d633 feat(viewer): hide premove bar ('Plan your next turn') - BGS has its own planning UI (v5.15.6) 2026-09-06 08:19:56 +00:00
77a0d8b422 feat(viewer): remove auto-leech control (platform sidebar owns it); flat gaia planet on gaia track; automa final-score black text (v5.15.5) 2026-09-06 08:13:23 +00:00
d3754c5f3d feat(viewer): flat planets always - remove sphere gradient for planets (v5.15.4) 2026-09-06 07:58:58 +00:00
0f7bac0b6b fix(viewer): spectators no longer see/press the current player's action buttons (canPlay) (v5.15.3) 2026-09-05 20:00:37 +00:00
58af97b85a fix(viewer): Planet.classes default to [] - guard spread against undefined (v5.15.2) 2026-09-05 19:50:47 +00:00
70ef774ea0 fix(viewer): Itars visibility on final scoring, stale layout tests, AGENTS.md publish steps (v5.15.1) 2026-09-05 12:52:35 +00:00
b21245dcff Improve visual styling of planets, scoring tiles, and research board 2026-09-05 12:34:43 +00:00
88b3f0446b feat(engine): export hashSeed = false - keep raw seeds on BGS (4.11.1)
The game-server now reads `engine.hashSeed ?? !!engine.stripSecret` to
decide whether the seed is sha256-hashed before init. Gaia's only hidden
information is the sealed-bid auction - player CHOICE, not seed-derived -
so the stripSecret-based default hashed our seeds pointlessly (sidebar log
showed base64 instead of the game name since the LF engine). Force the
raw seed.
2026-09-01 10:34:55 +00:00
14347432f0 feat: remove Frontiers expansion; fix import cycles + base-game scoring clip; Vite dev app (engine 4.11.0, viewer 5.15.0)
FRONTIERS REMOVAL (engine + viewer). Old BGS games pin old engine
versions so replay compatibility is unaffected; no current-version
games used Frontiers.

Engine (745 tests passing, 0 lint errors):
- deleted available/ships.ts (+spec), move/ships.ts
- enums: Frontiers bitflag, ResearchField.Diplomacy, Resource Trade*/
  ShipRange/UpgradeDiplomacy, Building ships/Colony/CustomsPost block
  (+ships()/isShip()/isAvailableShip()/Ship), Command.MoveShip,
  Phase.RoundShip, Condition.Trade, TechFrontiers1, Diplomacy tech pos
  members; Expansion.All now = LostFleet
- research-tracks: Diplomacy track, frontiersEco, ship-range rewards
  stripped from base Navigation track; all other Frontiers-only fields,
  handlers, cases and AI dimensions removed
- wrapper.ts: frontiers expansion flag

Viewer (863 tests passing, lint clean):
- deleted logic/trade-rewards.ts, logic/buttons/ships.ts,
  charts/testdata/frontiers/; zero 'frontiers' references remain

IMPORT-CYCLE + CJS FIXES surfaced by the Vite dev server (ESM strict
order), all pre-existing bugs webpack/CJS masked:
- engine/src/buildings.ts imported from ".." (package root -> compiled
  dist) - now "./enums"
- engine/index.ts re-exported ~15 type-only names as values
  (BrainstoneDest, MaxLeech, EventSource, EngineOptions, the
  Available* block, ResourceConversion, FederationInfo, GaiaHexData,
  AvailableSetupOption, PreferenceSplit*/SilentAuction* types) -
  split into 'export type' (load-bearing for rolldown too)
- viewer: Rules.vue registers FactionInfoCard async, breaking the
  Rules -> FactionInfoCard -> PlayerInfo -> Rules cycle
- viewer: buttonStringLabel moved from logic/buttons/utils.ts to
  shortcuts.ts (re-exported), breaking utils <-> shortcuts

DEV APP ON VITE (npm run serve = vite --port 8080):
- vite.config.ts mode-aware: dev = SPA (index.html + public/ +
  engine-source aliases + optimizeDeps exclusion), build = the
  published IIFE lib (unchanged single-file contract, verified)
- package.json: pruned webpack-era files/unpkg entries (.map dropped
  - no map uploads per owner decision); deleted
  scripts/fix-package-imports.ts (referenced the vite build's
  nonexistent dist/package/css)
- dev boot verified in Chromium: self-contained picker renders,
  zero page errors

BASE-GAME SCORING CLIP (follow-up on 5.14.2, which shipped without
the intended fix due to a no-op string replace): ScoringBoard's
y=-25 offset removed for real; spec pins y===null; verified in the
built bundle (first final tile fully inside the canvas top).

AGENTS.md: no sourcemap upload to BGS (owner decision); bodyparser
exemption noted as deployed.
2026-09-01 10:33:08 +00:00
ac75ca9ab4 feat(viewer): drop the rounded board cards, fix base-game scoring board clip (v5.14.2)
Two follow-up layout fixes from owner feedback:

1. The rounded card chrome is gone in BOTH base and Lost Fleet games:
   the space map no longer paints a table-surface background, rounded
   corners and inset border ring (theme.scss's .space-map rule), and
   the research/actions canvas no longer draws its rounded
   research-actions-panel rect behind the tracks (Game.vue). The boards
   render on the page background like the pre-Lost-Fleet viewer; the
   analysis-mode hazard overlay still paints on the map element. The
   now-unused --ui-map-*/--ui-board-* theme vars are removed.

2. The base-game side ScoringBoard no longer clips at the top: the
   pre-LF y=-25 offset pushed its first final-scoring tile 25 units
   above the canvas viewBox top (the clip the owner saw); y=0 now
   aligns the board with the canvas top.

Also verified programmatically in Chromium: map background
transparent/radius 0/shadow none, no .research-actions-panel node,
scoring board top not clipped. 873 tests pass; Game.spec.ts pins the
panel rect's absence for Lost Fleet now.
2026-09-01 09:55:30 +00:00
fd3cc31662 feat(viewer): restore compact turn order, drop notes, fix base-game board layout (v5.14.1)
Three UI fixes from owner feedback on the Lost-Fleet-era layout:

1. Turn order: the Gaia-9/10 full-width rounded top banner is gone -
   back to the pre-expansion compact indicator (h5 + player circles,
   presence dots kept) sitting in the commands row (col-md-4, mobile
   order-flip restored). The banner was designed to be replaced by a
   platform-side HostedBar that never existed, so it rendered
   everywhere including hosted BGS games.

2. Notes: LostFleetNotes.vue removed entirely (component, spec, and
   the store's notesBackend/NotesBackend/setNotesBackend plumbing -
   never called from viewer code; per-game notes are the hosting
   platform's job now).

3. Base-game (non-Lost-Fleet) board layout: the LF merge had changed
   shared values for all games. Restored the pre-expansion framing for
   the base game, LF-conditional: viewBox min-x 0 (was -50), canvas
   width tracks+120 (was +170), canvas height 505 (was 550 - the extra
   45 was the empty strip at the bottom), ResearchBoard height 450,
   ScoringBoard y=-25 restored, action row back to translate(45i+6,455),
   and the 65/35 map/side-column split scoped to .lost-fleet only.

Verified in Chromium: base-game round-1 layout matches the old framing
(tracks left-anchored, scoring board right, no bottom gap, compact turn
order) and a Lost Fleet round-1 game keeps its ship/scoring/pool
layout. 873 viewer tests pass (LostFleetNotes.spec deleted, Game.spec
updated to pin the restored layout).
2026-09-01 09:33:03 +00:00
662e64891a feat(viewer): migrate build to Vite 8 + rolldown, tests to vitest 4 (v5.14.0)
The vue-cli/webpack 4 toolchain was the root cause of three shipped
production crashes this week (iterator-spread __spreadArrays RangeError,
stale cache-loader emitting raw vue_1.default for the vue external, and
the TDZ circular-import). Replace it:

- vite.config.ts: lib build of src/wrapper.ts -> dist/package/
  viewer.umd.js (IIFE, esnext, minified) + viewer.css + map. vue and
  bootstrap-vue stay external (window.Vue / window.BootstrapVue) via
  plain global reads - no .default interop possible. process.env is
  baked to ({}) via define, matching vue-cli's old defaults.
- vitest.config.ts: jsdom env, single fork, chai-compatible specs run
  unchanged. 879 tests pass (was 809 - the json-driven chart/resource
  suites now register their dynamic tests properly under vitest).
- import type correctness across the codebase: rolldown rejects
  value-imports of type-only exports, so type-only imports are now
  written as import type (and mixed imports split). Also fixes
  self-contained-state.ts's reassignment of a destructured const.
- Commands.spec.ts: split a two-render test into two its - two
  @testing-library renders of Commands in one test interfere under
  vitest.
- scripts: package/build -> vite build, test -> vitest run.
- devDeps: +vite +@vitejs/plugin-vue2 +vitest +jsdom +esbuild +events
  (browser polyfill for the engine's node 'events' import).

Verified in Chromium against the built bundle: loads with CDN Vue 2 +
BootstrapVue, Rotate sectors completes with and without rotations, zero
pageerrors; the bundle contains no __spreadArrays helpers.
2026-09-01 09:00:07 +00:00
1288a8978c docs(AGENTS.md): correct BGS upload API usage (raw body, query params, octet-stream for maps)
The admin endpoints take the file as the raw request body with query
parameters - not multipart. The map upload must use
application/octet-stream because koa-bodyparser's 1MB jsonLimit
intercepts application/json bodies before the route's raw reader and
413s anything larger. Also note the GET-before-PUT rule (the engine
upload mutates the doc; a PUT from a stale GET reverts it).
2026-09-01 08:14:53 +00:00
bb39d47586 fix: RangeError on Rotate sectors + bundle load crash (viewer 5.13.1, engine 4.10.3)
- Replace all iterator spreads ([...map.values()] etc) with Array.from() across
  engine and viewer: under the TS->babel downlevel chain they compiled to
  __spreadArrays, which reads .length on an iterator and produced
  'RangeError: invalid array length' on 'Sector rotations finished' (the
  reported boardgamers.space crash), plus several latent same-class sites.
- Break the research-tracks.ts -> ../index barrel import cycle (imports
  Event/Expansion from leaf modules now): the cycle left Engine in TDZ and
  the whole bundle failed with 'Cannot access engine_Engine before
  initialization' at module eval under the rebuilt module order.
- Fix stale cache-loader output producing raw vue_1.default accesses for the
  vue webpack external (window.Vue has no .default): 'Cannot read properties
  of undefined (reading extend)' at load. Clean rebuild emits babel interop
  wrappers correctly. vue-global-shim.js added as belt-and-braces doc for the
  external's shape.
- Add autoprefixer as an explicit viewer devDependency (pnpm 11 no longer
  hoists it; the lib build failed on postCSS plugin load).
- Update stale spec type signatures surfaced by the import change (tile
  position as EventSource, loadFaction arity, ChargeRequest literal cast,
  AvailableCommand data narrowing, FederationInfo new fields).

Verified: engine 750 passing / 4 pending; viewer 809 passing; lint + prettier
clean; rebuilt UMD has zero iterator-spread call sites and loads + completes
sector rotation (with and without rotations) in Chromium against the real
bundle with CDN-provided Vue 2.
2026-09-01 08:09:31 +00:00
bfed8f506e
Merge gaia-lost-fleet: Lost Fleet expansion, sandbox mode, sealed-bid auctions (#328)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Kim <kim.pham.nguyen2@gmail.com>
Co-authored-by: kimphamnguyen <82032729+kimphamnguyen@users.noreply.github.com>
2026-08-25 00:07:03 +02:00
github-actions
45951431e6 🔖 (viewer) v5.12.0
Some checks are pending
All / prettier (push) Waiting to run
2026-08-19 20:30:57 +00:00
67259ddff7 Add dark mode support and theme toggle button 2026-08-19 20:29:10 +00:00
1b241820cc Use choice dropdown for version bump type in workflows 2026-08-19 10:28:00 +00:00
github-actions
3471317603 🔖 (engine) v4.9.0
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2026-08-19 10:20:12 +00:00
2e6e4ce4d1
perf(engine): 10x federation enumeration — fixes >10s move timeouts in prod games (#325) 2026-08-19 12:19:05 +02:00
github-actions
bcdcd3256f 🔖 (engine) v4.8.52
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2026-08-12 21:29:13 +00:00
64cad793d6
fix: upgrade engine TypeScript to fix tsc publish build (#324) 2026-08-12 22:56:33 +02:00
f440b30c09
feat: add moveAI for bot players (#323) 2026-08-12 22:38:54 +02:00
a1835c39d7 🔧 Ignore .playwright-mcp artifacts 2026-08-12 20:20:35 +02:00
github-actions
9c8bca7e0c 🔖 (viewer) v5.11.53
Some checks are pending
All / prettier (push) Waiting to run
2026-08-11 20:57:15 +00:00
155e032569
💄 Fix charts icon clipped on the right edge of the map (#322) 2026-08-11 22:56:33 +02:00
github-actions
dc77d8ca49 🔖 (viewer) v5.11.52
Some checks are pending
All / prettier (push) Waiting to run
2026-08-07 22:40:00 +00:00
e3ab7c60f1 Fix text contrast in scoring and tech tiles for dark mode 2026-08-07 22:38:38 +00:00
github-actions
1b92dd06e9 🔖 (viewer) v5.11.51
Some checks are pending
All / prettier (push) Waiting to run
2026-08-07 22:26:29 +00:00
e66c98a444 Update repository URL in package.json files 2026-08-07 22:25:38 +00:00
06c934d5c8 Update pnpm config and enable transpile-only for viewer build 2026-08-07 22:21:19 +00:00
1d56c2ea9a Update publish workflows to Node 24 and OIDC publishing 2026-08-07 22:03:19 +00:00
c7c793151b
Remove Gitpod badge from README
Removed Gitpod badge from README.
2026-08-07 23:47:06 +02:00
cce50d5cc4 Ensure SVG text visibility and colors in dark mode 2026-08-07 21:45:23 +00:00
789 changed files with 217272 additions and 17020 deletions

View file

@ -4,11 +4,16 @@ on:
workflow_dispatch:
inputs:
newversion:
description: "Semantic Version Bump Type (major minor patch)"
description: "Semantic Version Bump Type"
type: choice
options:
- patch
- minor
- major
default: patch
env:
node_version: 14
node_version: 24
defaults:
run:
@ -17,23 +22,25 @@ defaults:
jobs:
version_and_release:
runs-on: ubuntu-latest
permissions:
contents: write # git push --follow-tags
id-token: write # OIDC trusted publishing
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v4
with:
node-version: ${{ env.node_version }}
# setting a registry enables the NODE_AUTH_TOKEN env variable where we can set an npm token. REQUIRED
# registry-url is required so npm publish targets the public npm registry
registry-url: "https://registry.npmjs.org"
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
- run: corepack enable
- run: pnpm install
- run: git config --global user.name github-actions
- run: git config --global user.email bot@github.com
- run: yarn config set version-git-message "🔖 (engine) v%s"
- run: yarn version --${{ github.event.inputs.newversion }}
- run: pnpm publish .
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# pnpm 10.16+ supports OIDC trusted publishing; publish via npx so we don't have to bump
# the repo-wide pnpm. No NODE_AUTH_TOKEN is set, so publishing authenticates with the
# OIDC token instead of the (now-rejected) npm token.
- run: npx -y pnpm@latest publish . --access public --no-git-checks
- run: git push --follow-tags

View file

@ -17,13 +17,11 @@ jobs:
lint_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "14"
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
node-version: "24"
- run: corepack enable
- run: pnpm install
- run: yarn build
- run: yarn lint

View file

@ -1,39 +0,0 @@
name: Old UI - Version and Release
on:
workflow_dispatch:
inputs:
newversion:
description: "Semantic Version Bump Type (major minor patch)"
default: patch
env:
node_version: 14
defaults:
run:
working-directory: old-ui
jobs:
version_and_release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v2
with:
node-version: ${{ env.node_version }}
# setting a registry enables the NODE_AUTH_TOKEN env variable where we can set an npm token. REQUIRED
registry-url: "https://registry.npmjs.org"
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
- run: pnpm install
- run: git config --global user.name github-actions
- run: git config --global user.email bot@github.com
- run: yarn config set version-git-message "🔖 (old-ui) v%s"
- run: yarn version --${{ github.event.inputs.newversion }}
- run: pnpm publish .
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: git push --follow-tags

View file

@ -1,32 +0,0 @@
name: Old UI - Test
on:
push:
paths:
- ".github/workflows/old-ui-test.yml"
- "viewer/**"
branches:
- master
pull_request:
paths:
- ".github/workflows/old-ui-test.yml"
- "viewer/**"
defaults:
run:
working-directory: old-ui
jobs:
test_and_build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: "14"
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
- run: pnpm install
- run: pnpm lint
# - run: pnpm test
- run: pnpm build

View file

@ -5,10 +5,10 @@ jobs:
prettier:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: pnpm/action-setup@v1.2.1
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
version: 5.17.1
node-version: "24"
- run: corepack enable
- run: pnpm install
- run: pnpm run prettier-check

View file

@ -4,11 +4,16 @@ on:
workflow_dispatch:
inputs:
newversion:
description: "Semantic Version Bump Type (major minor patch)"
description: "Semantic Version Bump Type"
type: choice
options:
- patch
- minor
- major
default: patch
env:
node_version: 14
node_version: 24
defaults:
run:
@ -17,23 +22,30 @@ defaults:
jobs:
version_and_release:
runs-on: ubuntu-latest
permissions:
contents: write # git push --follow-tags
id-token: write # OIDC trusted publishing
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v4
with:
node-version: ${{ env.node_version }}
# setting a registry enables the NODE_AUTH_TOKEN env variable where we can set an npm token. REQUIRED
# registry-url is required so npm publish targets the public npm registry
registry-url: "https://registry.npmjs.org"
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
- run: corepack enable
- run: pnpm install
- run: git config --global user.name github-actions
- run: git config --global user.email bot@github.com
- run: yarn config set version-git-message "🔖 (viewer) v%s"
- run: yarn version --${{ github.event.inputs.newversion }}
- run: pnpm publish .
# pnpm 10.16+ supports OIDC trusted publishing and rewrites the workspace:../engine
# dependency to a real version range; publish it via npx so we don't have to bump the
# repo-wide pnpm (which would force a lockfile rewrite). No NODE_AUTH_TOKEN is set, so
# publishing authenticates with the OIDC token instead of the (now-rejected) npm token.
# NODE_OPTIONS=--openssl-legacy-provider works around webpack 4's reliance on MD4,
# which OpenSSL 3 (bundled with Node >= 17) no longer supports out of the box.
- run: npx -y pnpm@latest publish . --access public --no-git-checks
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
NODE_OPTIONS: --openssl-legacy-provider
- run: git push --follow-tags

View file

@ -4,12 +4,18 @@ on:
paths:
- ".github/workflows/viewer-test.yml"
- "viewer/**"
- "old-ui/**"
- "pnpm-lock.yaml"
- "pnpm-workspace.yaml"
branches:
- master
pull_request:
paths:
- ".github/workflows/viewer-test.yml"
- "viewer/**"
- "old-ui/**"
- "pnpm-lock.yaml"
- "pnpm-workspace.yaml"
defaults:
run:
@ -19,14 +25,23 @@ jobs:
test_and_build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "14"
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
node-version: "24"
- run: corepack enable
- run: pnpm install
- run: pnpm --dir .. test:locales
- run: pnpm lint
# The full suite (810+ specs through mochapack/webpack) exceeds node's default ~4 GB heap (peaks ~10 GB; runners have 16 GB).
- run: pnpm test
env:
NODE_OPTIONS: --max-old-space-size=12288
- run: pnpm build
- run: pnpm --dir ../old-ui test
env:
NODE_OPTIONS: --max-old-space-size=12288
- run: pnpm --dir ../old-ui package
- run: pnpm --dir ../engine build
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm test:browser

4
.gitignore vendored
View file

@ -1,3 +1,7 @@
node_modules
batch/replay/
batch/dist/
.pnpm-store
.playwright-mcp/
/artifacts/achievement-portraits/
/artifacts/achievement-scenes/

2
.husky/.gitignore vendored
View file

@ -1 +1 @@
_
_

0
.husky/pre-commit Normal file → Executable file
View file

View file

@ -1,3 +1,4 @@
pnpm-lock.yaml
dist
replay

View file

@ -2,5 +2,6 @@
"tabWidth": 2,
"useTabs": false,
"printWidth": 120,
"trailingComma": "es5"
"trailingComma": "es5",
"plugins": ["prettier-plugin-organize-imports"]
}

View file

@ -1,9 +1,7 @@
<template></template>
<script lang="ts">
import {Vue, Component, Prop, Watch} from "vue-property-decorator";
import { Component, Vue } from "vue-property-decorator";
@Component
export default class $0 extends Vue {
}
export default class $0 extends Vue {}
</script>

83
AGENTS.md Normal file
View file

@ -0,0 +1,83 @@
# AGENTS.md
Monorepo for the Gaia Project engine + viewer hosted on [boardgamers.space](https://boardgamers.space)
(BGS). pnpm workspace: `engine/` (rules engine, plain TS) and `viewer/` (Vue 2.7 UMD lib consumed by
the BGS iframe wrapper).
## Build & test
```bash
pnpm install # pnpm 10+; CI=true to avoid the modules-purge prompt in scripts
cd engine && npm test # mocha + ts-node (TS via tsconfig "module": "commonjs")
cd engine && npm run build # tsc -> dist/ (wrapper.js, index.js)
cd viewer && npm test # vitest (jsdom); needs --max-old-space-size=12288
cd viewer && npm run package # vite lib build -> dist/package/viewer.umd.js + .css (+ .map, not uploaded)
```
- Viewer unit tests: `NODE_OPTIONS="--max-old-space-size=12288" npm test` (the suite peaks ~10 GB).
- The viewer builds with **Vite 8 + rolldown** (`vite.config.ts`), tests with **vitest 4**
(`vitest.config.ts`). Target is `esnext` — no downlevel helpers, no cache-loader, no webpack.
The old vue-cli/webpack toolchain is gone; `vue-cli-service serve` still exists for the dev app.
- The published IIFE keeps `vue` and `bootstrap-vue` **external** — the host page provides them
(`window.Vue`, `window.BootstrapVue`). Vite externals resolve to plain global reads (no
`.default` unwrapping), which is what CDN Vue 2 needs. Test any bundler change by loading the
built `viewer.umd.js` in a real browser page that loads Vue 2 from a CDN, then exercising the
viewer (`window.gaiaViewer.launch`).
- `process.env` is baked to `({})` via vite `define` (vue-cli's DefinePlugin used to supply it);
`VUE_APP_*` env prefs therefore default to undefined/false in the lib build, as before.
- `import type` matters now: rolldown errors on value-imports of type-only exports. When adding
an import of something that's only a type/interface, write `import type`.
## Publishing to boardgamers.space
You need an **admin token** (`bgs_admin_…`). Tokens are scoped and can be revoked; ask the BGS
admin for a current one. Do NOT commit tokens anywhere.
The game is registered on the v3 gameinfo service. Base URL: `https://admin.boardgamers.space/api/admin/gameinfo/gaia-project/3`.
All calls take `Authorization: Bearer <token>`.
1. **Engine** — publish the npm tarball (its `version` field becomes the engine version). The
endpoint takes the tarball as the **raw request body** (no multipart):
```bash
cd engine && npm run build && npm pack # -> gaia-project-engine-<version>.tgz
curl -X POST "$BASE/engine" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary @gaia-project-engine-<version>.tgz
```
2. **Viewer files** — upload the complete `viewer/dist/package` directory (entry JS,
CSS, language JSON and faction JPG files). Repeat for `old-ui/dist/package` with
`--alternate`. Use BGS's `scripts/publish-viewer.mjs` or admin **Upload folder**;
see [viewer publishing](docs/viewer-publishing.md). All files must share the same
immutable bundle directory. BGS handles gzip automatically. Sourcemaps stay local.
3. **Update the viewer** only after all files are uploaded and verified. Send
`{ viewer: ... }` to the version PUT endpoint to preserve engine and other metadata.
Read the current viewer immediately before updating to avoid overwriting another release.
4. Verify on a real BGS game page afterwards (hard-reload; the platform may cache the old
viewer URL per game).
Before publishing: engine tests + viewer tests + `npm run package` all green, and the built
viewer verified in a real browser (see the loading test above).
## Repo conventions
- `master` is the release branch; changes published to BGS must be pushed there
as part of publication. Other feature work can land via PRs. Keep CI green: prettier, engine
eslint (warnings tolerated, errors not), viewer eslint, both test suites.
- lint-staged runs prettier on commit; if its import ordering fights a hand-made change,
commit with `--no-verify` after confirming `npm run prettier` is clean.
- Version bumps: `engine/package.json` and `viewer/package.json` independently, patch-level
for fixes. The engine tarball version is what BGS games record per game.
## BGS publication and Git delivery
Whenever changes are published to BGS, commit the corresponding source, tests,
dependency/lockfile changes and version bumps, then push them to this repository's
`main` or `master` release branch in the same task. A BGS upload or a push only to
a feature branch does not complete delivery. This is standing authorization to
commit and push published changes without asking for separate confirmation.
Fetch and integrate the latest release-branch changes, run the relevant repository
checks, and push without force. Update any public mirrors required by this repo's
existing workflow too. Keep credentials, generated artifacts excluded by the repo,
and unrelated unfinished work out of the commit. Verify the remote branch contains
the delivered commit and report any blocker instead of claiming delivery.

View file

@ -1,7 +1,5 @@
# Gaia Project
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/boardgamers/gaia-project)
Mono repo containing the viewer & the engine for Gaia Project
Checkout their READMEs:
@ -9,9 +7,11 @@ Checkout their READMEs:
- [engine](./engine/README.md)
- [viewer](./viewer/README.md)
## Demo
## Play online at
Check out [boardgamers.space](https://www.boardgamers.space)! Reach out to us if you want to contribute.
[boardgamers.space](https://boardgamers.space/boardgame/gaia-project)
Reach out to us if you want to contribute.
## Install
@ -41,3 +41,5 @@ If the PR's commit history is clean, and commit messages conform to the policy,
If you need to squash, take care to add the appropriate gitmoji & scope to the commit message.
If the PR has [fixup commmits](https://jordanelver.co.uk/blog/2020/06/04/fixing-commits-with-git-commit-fixup-and-git-rebase-autosquash/) starting with `fixup!`, approve the PR first, let the contributor adjust their PR to remove the fixup commits, and then rebase.
Viewer releases: see [uploading the complete viewer build](docs/viewer-publishing.md).

267
docs/achievements.md Normal file
View file

@ -0,0 +1,267 @@
# Achievements
The engine implements optional Boardgamers.space (BGS) achievement hooks in
[`engine/src/achievements.ts`](../engine/src/achievements.ts), re-exported as named
exports by `engine/wrapper.ts`. This is engine-side support, not a BGS publication
or a claim that achievements have been enabled on the hosted service.
## Hook contract
- `achievementDefinitions()` returns `{ revision: 5, achievements }`. Each definition
has string `id`, `name`, and `description` fields and an optional strict `icon`:
`{ type: "asset", key: string }` or `{ type: "text", text: string }`. Asset keys
match `^[a-z0-9][a-z0-9-]{0,63}$`; text matches `^[A-Za-z0-9]{1,4}$`. No URLs,
style, crop, HTML, or SVG payloads are accepted. The complete 36-entry catalog is
returned regardless of the current game's ruleset or selected factions.
- `achievements(data)` accepts an `Engine` or serialized engine state and returns
`{ seat, earned, outcome? }[]`. `earned` contains catalog IDs. The structural
outcome type allows `"win" | "loss" | "draw"`; this implementation emits only
`"win"` and `"loss"` for eligible humans, because shared first place is a win.
- These optional exports use the official achievement types from
`@boardgamers/protocol@0.11.0`, imported from `@boardgamers/protocol/engine`.
Imports and re-exports are type-only: the CommonJS engine emits no runtime
protocol import. The engine declares the published package as a dependency
because its distributed TypeScript sources also reference these types.
Consuming and publishing awards remains a host integration concern.
### Authoritative completion only
The caller must supply authoritative completed game state, not a client view or
an arbitrary analysis position. Evaluation requires all three of:
1. `phase === Phase.EndGame`;
2. `round === Round.LastRound`;
3. an `advancedLog` entry whose phase is `Phase.EndGame`, emitted by final scoring.
Otherwise the hook returns `[]`. Merely ending or terminating a game is not enough.
The hook does not advance play, replay moves, or recompute final scoring. It reads
stored final victory points, including auction deductions already applied. The
completion marker is a state predicate, not proof that untrusted input is genuine;
a host must not accept fabricated client state as authoritative.
Seats are zero-based indices in the engine's **human-player list**, in original
player order after removing Automa players; they are not raw engine player numbers.
Automa never receives a result. Dropped humans retain their human seat index and
return `{ seat, earned: [] }`, with no outcome, rather than shifting later seats.
## Revision 5 catalog (36 IDs)
IDs follow BGS's `^[a-z0-9][a-z0-9-]{0,63}$` validator: lowercase letters,
ASCII digits, and hyphens, at most 64 characters. All 36 IDs are unique. The
pre-publication dotted spellings were replaced with hyphens; they are not aliases
and were never published. Revision 2 added 18 faction asset references and four
150/200 text emblems. Revision 3 replaced those text emblems with two shared
raster score assets: `achievement-score-150` and `achievement-score-200`.
That revision-2-to-3 artwork change preserved all 36 IDs and earned predicates.
Revision 4 raises both federation thresholds to four and renames the general
federation ID, as detailed below. Revision 5 adds original scene artwork to the
remaining 14 definitions: all 36 now reference 34 assets. The 22 previously illustrated
rows retain their exact 20 keys and public image bytes. IDs, descriptions, and
evaluation are unchanged from revision 4.
**Deployment order:** the platform icon contract (platform commit
`fca050c9509c1dec3afd8d4631cc57245f834f29`, platform PR
[578](https://codeberg.org/boardgamers/boardgamers/pulls/578)) must be deployed
before activating an icon-bearing manifest. Older strict validators reject `icon`.
No production assets or achievement activation are implied by this source change.
### Faction victories (18)
Each requires a win as the named faction; either ruleset qualifies where that
faction is available.
| ID | Faction |
| --------------------------- | ------------- |
| `win-faction-terrans` | Terrans |
| `win-faction-lantids` | Lantids |
| `win-faction-hadsch-hallas` | Hadsch Hallas |
| `win-faction-ivits` | Ivits |
| `win-faction-geodens` | Geodens |
| `win-faction-baltaks` | Bal T'aks |
| `win-faction-xenos` | Xenos |
| `win-faction-gleens` | Gleens |
| `win-faction-taklons` | Taklons |
| `win-faction-ambas` | Ambas |
| `win-faction-firaks` | Firaks |
| `win-faction-bescods` | Bescods |
| `win-faction-nevlas` | Nevlas |
| `win-faction-itars` | Itars |
| `win-faction-tinkeroids` | Tinkeroids |
| `win-faction-darkanians` | Darkanians |
| `win-faction-moweyds` | Moweyds |
| `win-faction-space-giants` | Space Giants |
### Ruleset victories and scores (6)
| ID | Requirement |
| ---------------------- | --------------------------------------------------- |
| `win-mode-base` | Win a base game |
| `win-mode-lost-fleet` | Win a Lost Fleet game |
| `score-base-150` | Finish a base game with at least 150 final VP |
| `score-base-200` | Finish a base game with at least 200 final VP |
| `score-lost-fleet-150` | Finish a Lost Fleet game with at least 150 final VP |
| `score-lost-fleet-200` | Finish a Lost Fleet game with at least 200 final VP |
`options.lostFleet` selects the ruleset; a Lost Fleet game does not also award base
mode IDs. Score achievements require **no win**, and 200 VP earns both thresholds
for the selected mode.
### Automa victories (5)
| ID | Exact difficulty |
| ------------------------- | ---------------- |
| `win-automa-automalein` | `automalein` |
| `win-automa-automa` | `automa` |
| `win-automa-automaechtig` | `automaechtig` |
| `win-automa-ultoma` | `ultoma` |
| `win-automa-alptrauma` | `alptrauma` |
Only the configured difficulty's ID is earned, not all lower difficulties.
In both multiplayer and solo Automa games, a human at the highest final score
wins: ties for first count as wins, including a human tied with Automa. Winners
also earn their faction and mode victory IDs. The comparison uses the maximum
stored VP across engine players, including Automa.
### General and faction feats (7)
None of these feats requires a win. They still require an eligible, non-dropped
human in an authoritatively completed game.
| ID | Requirement |
| ------------------------------------- | ---------------------------------------------------------------------------- |
| `build-all-standard` | All 18 standard building pieces simultaneously deployed at game end |
| `federation-form-4` | At least four federation formations in one game |
| `explore-all-types-base` | Main-owned colonies on all 9 required physical types in a base game |
| `explore-all-types-lost-fleet` | Main-owned colonies on all 11 required physical types in a Lost Fleet game |
| `faction-ivits-growing-federation` | As Ivits, at least four federation formation milestones |
| `faction-lantids-shared-civilization` | As Lantids, at least six additional mines on opponents' colonies at game end |
| `faction-bescods-balanced-research` | As Bescods, finish at level 3 or higher on all six research tracks |
**Full deployment:** the standard supply is 8 mines, 4 trading stations, 3 research
labs, 1 planetary institute, and both academies (18 pieces). The predicate checks
each standard building counter against its faction-board maximum. Lost Planet,
artifacts, Gaiaformers, and space stations do not count. Upgrading returns lower-tier
pieces to supply, so building new colonies and refilling those tiers makes all 18
simultaneously deployed structurally possible; upgrades do not impose a permanent
shortfall. Difficulty and practical attainability within a legal game's economy
remain uncalibrated. That is not an implementation blocker, nor is structural
possibility a claim of a demonstrated legal all-18 game.
**Federations:** use `federationCount`, not federation-token inventory. Rewards and
rescores do not count as formations. Ivits' growing-federation extensions count as
formation milestones; four completed formations qualify Ivits for both the general
and faction feat. Ivits' existing cost rule is `7 * (1 + federationCount)`, so the
fourth milestone requires 28 total federation value, not 28 newly added value.
Normal connection, satellite/QIC and token-availability constraints still apply.
The rules support this milestone without a three-formation cap; the threshold
unit test is not evidence of a demonstrated legal full-game route.
Revision 4 raises both federation feats from three to four as a user-authorized
pre-adoption correction (no existing awards reported). The general ID becomes
`federation-form-4`; the Ivits ID remains `faction-ivits-growing-federation`.
The old general ID is absent from the active catalog. There is no migration,
revocation or backfill. The other 34 definitions and all artwork are unchanged.
**Physical colony types:** the base set is Terra, Desert, Swamp, Oxide, Volcanic,
Titanium, Ice, Gaia, and Lost Planet (9). Lost Fleet adds Asteroid and Protoplanet
(11). Transdimensional (`m`) and empty space (`e`) are not required colony types.
The evaluator reads physical planets from `ownedPlanets`, not the broader scoring
condition that includes virtual artifact planet types. Artifact bonuses cannot
substitute for a physical colony. Gaiaformers and Lantids' shared/additional mines
do not satisfy this main-ownership requirement. Lantids' additional mines instead
count toward their separate shared-civilization feat.
## Portrait assets and release procedure
Faction win icons reference **named game assets**, not viewer-bundle URLs:
`achievement-faction-<faction-id>`. Score badges reference uploaded raster assets
`achievement-score-150` and `achievement-score-200`, shared across the two rulesets.
They include the authentic approved BGS Gaia pictogram and large score numerals,
not a plain text emblem or an invented logo. The approved pictogram is vendored
as a reproducible source with its original URL and SHA-256 recorded alongside it;
generation requires no network access.
Source artwork is in `viewer/src/assets/factions/*.jpg`, with provenance in
[`viewer/src/assets/factions/README.md`](../viewer/src/assets/factions/README.md).
Artwork is by Dennis Lohausen, published by Feuerland Spiele, used with publisher
permission as confirmed by BGS; it is **not** covered by the source-code license.
The faction `moweyds` intentionally maps to source file `mowyeds.jpg`.
Generate local release inputs (no network requests or uploads):
```sh
pnpm install --frozen-lockfile
pnpm run generate:achievement-portraits
pnpm run test:achievement-portraits
```
The generator crops a 167×167 square at x=13, y=0 from each 392×167 faction header,
matching the existing viewer's left-side portrait framing. Faction outputs are
square raster PNGs without a baked-in circular mask; the platform controls
presentation. Score artwork uses a dark space background and circular metallic
framing (silver for 150, gold for 200), the approved Gaia pictogram and large
numerals from pinned licensed raster glyphs. No system font, network fetch or
arbitrary SVG/HTML payload is used during generation.
Outputs are written to `artifacts/achievement-portraits/`: 18
`achievement-faction-<id>.png` files, two 512×512 score files
`achievement-score-150.png` / `achievement-score-200.png`,
`contact-sheet.png` (all 18 labeled faction crops), `score-contact-sheet.png`
(including small-size score previews), and `manifest.json` recording source/output
hashes, crop coordinates and toolchain. Score source provenance is documented in
[`scripts/assets/achievement-scores/README.md`](../scripts/assets/achievement-scores/README.md).
Review faction crops and score artwork at full and badge sizes before uploading.
Generated assets are ignored build outputs, not committed artwork copies. The
source map, approved pictogram, crop coordinates and dependency lockfile are the
reproducible inputs.
**Release only after separate publication authorization:**
1. Deploy the platform's revision-2 icon support first; do not activate this
engine's icon manifest against an older strict schema.
2. Generate and visually inspect the portraits locally. Keep the generated
input/output hash manifest with the release verification record.
3. Upload the raw bytes of all 20 image files (18 `achievement-faction-<id>.png`
plus `achievement-score-150.png` and `achievement-score-200.png`) to
`PUT /api/admin/gameinfo/gaia-project/assets/<filename-without-extension>` with
`Content-Type: image/png` and the authorized admin bearer token. This is the
**version-independent named game asset** endpoint, not `/gaia-project/3/viewer`.
Do not upload contact sheets or the hash manifest as achievement images.
4. BGS re-encodes images to WebP and records the content-hashed URL under the
metadata asset key. Production URLs must use the dedicated
`achievements/gaia-project/<key>/<hash>/<file>` namespace. Verify anonymous
HTTP 200, WebP dimensions and the SHA-256 content-hash URL for all 20 assets;
record input and stored hashes separately because WebP encoding is lossy.
Verify all 20 keys resolve to the expected artwork and verify the platform
fallback for a missing asset. Do not invent public URLs
or embed them in engine definitions; viewer-bundle retention is irrelevant.
5. For local platform review, its author must upload these real named assets to
the local environment **before capturing UI screenshots**. Do not intercept
image requests or inject replacement images to simulate a successful upload.
Local upload does not authorize production upload or activation.
6. Only after production release authorization publish/activate the engine/catalog
through the normal release workflow and verify portraits and score artwork in
the platform UI. Deploy the platform icon support before catalog activation.
Generation alone does not publish assets or activate the engine. Publication
status and verification receipts belong in `docs/releases/`; do not infer live
availability from generated files or a successful build.
The existing BGS viewer-bundle publisher cannot consume this manifest as named
assets. A follow-up shared publisher should accept an explicit game-local list of
`key`, relative `file`, content type and SHA-256, validate catalog coverage, and
upload through the named endpoint with dry-run by default and saved receipts.
The generator can supply that list from its existing manifest. This needs no
separate catalog editor and is not a prerequisite for this release.
## Verification and scope
Predicate tests may construct or modify final-state counters, scores, ownership,
and completion markers to isolate thresholds, exclusions, and seat mapping. Such
synthetic states test the evaluator contract; they do **not** prove that every feat
can be reached through legal play. A legal completed-game fixture exercises the
real completion/scoring path and serialization, but proves attainability only for
feats actually demonstrated by that fixture. In particular, do not interpret a
synthetic all-18 assertion as a legal all-18 playthrough or difficulty calibration.
These hooks do not publish a BGS catalog, persist account awards, or deploy the
engine to BGS. Those host-side operations are outside this implementation.

91
docs/bgs-premoves.md Normal file
View file

@ -0,0 +1,91 @@
# BGS premoves
Players compose turns in the existing Planning mode, then submit up to three complete turns.
On their own turn the first plays immediately; otherwise it waits. The remaining turns run
server-side when the player becomes active, including when their browser is closed.
The queue above the board is private and can be inspected or cancelled during live play or
while composing another planning line, or reviewing an earlier turn. Cancelling a later move also removes its successors.
## Execution and BGS protocol
`engine/wrapper.ts` uses the existing protocol hooks. No new protocol version is needed:
- `canMoveOutOfTurn` permits a seated player to submit a `premoves` command.
- `isLiveUpdate` marks changes to the queue so BGS saves them without advancing clocks,
notifications or the public move log. A queue command that executes a turn is a normal save.
- `timeIncrements` returns monotonic per-seat counters. Each completed manual decision or
executed premove earns one increment; automatic charging and queue edits earn none. Undo keeps
the counters and clears queues, so replaying the log cannot generate extra increments.
- `stripSecret` includes only the requesting player's plan, including through `logSlice`.
`automation` is optional on old saved games. It is initialized with zero counters so upgrading
an existing game does not retrospectively credit turns. The primary viewer enables its queue
only when this engine capability is present. The alternate viewer can continue making normal moves.
The engine resolves automatic charging/income first. A manual decision waits for the player and
retains their queue. Each premove is checked against a disposable copy of the current board
before being applied, so an unavailable action or a failed later command cannot spend resources.
An illegal turn stops the remaining queue and leaves a private explanation. Queues survive passing
and round changes; each move records its intended round and phase. Unplanned manual income or Gaia
choices wait for the player, while planned income choices can execute automatically. Income already
resolved by the normal auto-income setting is not applied twice. Dropping the seat or ending the
game clears the queue.
Initial building placements and booster choices can also be queued once factions are assigned.
`setupPremoves` advertises this capability. The queue contains only the player's own choices;
opponents' hypothetical setup moves stay in the preview. Each queued choice is checked again
on the real board when its setup turn arrives, including whether its planet or booster is available.
Commands carry the seat's setup/main-turn counter, round, queue revision and request ID. This rejects
stale replacements and makes retries idempotent. Automatic leech does not stale a plan. Cancelling
an existing suffix remains possible even when the retained prefix has become illegal.
The optional `timings` array is additive: older queues default to their recorded round's move phase,
and older viewers' new submissions infer a new round after passing. `roundPremoves` advertises the
new scheduling capability without a new BGS protocol release. Future-round legality is checked
atomically on execution because the intervening income and board changes are not known at submission.
## Sandbox and live updates
Planning is the single composer and enforces the simulated position’s resource costs. Future turns can use simulated income or explicit charges; each is checked
with actual resources when its turn arrives. Simulated charges are never commands or conditions.
The queue stops immediately if the next turn is illegal, without waiting for a charge. An immediately
played turn must already be affordable. A simulated-neighbour Trading Station keeps the `cheap`
qualifier as a 3-credit ceiling: the engine checks the actual upgrade cost and stops if that price
is unavailable, even if the player could afford 6 credits. It never grants a discount. The entire plan
is sent atomically. Saving or cancelling a queue keeps the local plans and variations.
Submitting a new plan replaces the existing queue, with confirmation before submission.
Real moves trim matching prefixes from every local variation, whether played manually or by a
premove. Repeated actions such as research are matched against actual move history, not inferred
from whether they remain legal. Simulation charges attached to a played turn are removed with it.
Unrelated or invalid alternatives are preserved for editing. Reopening a saved plan after a reload
applies the same reconciliation. A rollback requires explicit recovery instead of guessing.
Incoming turns and automatic charging rebase the simulation without closing it. Opponent updates
preserve the partly composed current turn; your own real turn clears that unfinished preview. Queue changes update the real backup without clearing the draft.
Local sandbox saves are scoped by the initial game move (BGS's game seed/name) and player seat,
since BGS uses the same iframe URL for multiple games. Old unscoped BGS drafts are not restored
into an arbitrary game.
## Local preview
```sh
npm --prefix engine run build
npm --prefix viewer run package
npm --prefix viewer run premove:preview
```
Open <http://127.0.0.1:5201/>. This small local host uses the built viewer and real engine wrapper;
its state stays in server memory until the preview process restarts. It does not access a BGS database.
1. Choose **Plan a move**, use the normal controls, and finish the simulated turn.
2. Choose **Queue moves**, then confirm. Reload: the private queue remains.
3. **View on board** opens the queued line; cancelling it keeps an unrelated sandbox draft.
4. **Play opponent's turn** upgrades Alex's adjacent mine, resolves your automatic charging,
then executes your premove.
5. **Other player's view** shows that seat's own queue, never yours. **Reset position** starts over.
Engine tests cover privacy, stale requests, chains, manual and automatic charging, atomic failure,
cancellation and replay counters. The retained contention tests exercise occupied planets,
research caps, federation and advanced technology tokens, and Lost Fleet space stations.

View file

@ -0,0 +1,727 @@
# AI Challenge Plan — a seed-locked "beat the AI" monthly game
> **Status — CONCEPT RECORD, EXTERNALLY REVIEWED (2026-07-13).** The first challenge's setup is
> **LOCKED** (§2: seed `lf-mrj5exuu-c680`, 2p Lost Fleet, Xenos vs Hadsch Hallas, validated to boot),
> but the implementation assumptions and milestone order in this document have now been audited
> against the real code. **Use `AI_IMPLEMENTATION_PLAN.md` as the authoritative execution plan.**
> It corrects the search-node/action model, determinism and federation assumptions, performance
> interpretation, neural encoding, training gates, and ranked anti-cheat design. This file remains
> the concept/brainstorming history; where the two conflict, the implementation plan wins.
>
> **Three companion docs in this worktree:**
>
> - `AI_IMPLEMENTATION_PLAN.md` — **authoritative** phased execution, safety gates, acceptance tests,
> and session boundaries;
> - this file — `AI_CHALLENGE_PLAN.md` (architecture, approach, strength boosters, wiring, milestones);
> - `AI_STRATEGY_NOTES.md` — the human-strategy intake (fill-in), incl. **the decoded board for this
> seed** and the Xenos / Hadsch Hallas ability notes (its §11 and §2), plus community-sourced tips (§13).
>
> **Document map:** §1 goal · §2 the locked setup · §3 measured feasibility · §4 module layout ·
> §5 approach + monthly reuse · §6 strength boosters · §7 how strategy folds in + the per-decision
> playbook (§7.1 contested races, §7.2 economy, §7.3 federations, §7.4 pass/overcharge/completeness,
> §7.5 burning power, §7.6 opponent-leech ordering) · §8 UI/Supabase wiring · §9 milestones ·
> §10 open questions · §11 references.
---
## 0. FOR AN EXTERNAL REVIEWER (e.g. ChatGPT) — READ THIS FIRST
You are being asked to brainstorm and critique this plan **with your latest flagship model**.
Before you analyze anything:
1. **Pull the latest `master` of `kimphamnguyen/gaia-lost-fleet` from GitHub and work against
that.** This plan references specific files, function names, and line-level behavior in the
_current_ engine and viewer. An older checkout (or reasoning from memory) will describe code
that no longer matches. Do a fresh `git clone`/`git pull origin master` and read the real files.
2. The relevant code lives in:
- `engine/` — the game engine (`engine/src/engine.ts`, `engine/src/move/`, `engine/src/available/`).
- `engine/src/fuzz/` — an existing **headless self-play harness** (this is the backbone we reuse).
- `viewer/` — the Vue app (`viewer/src/self-contained.ts`, `viewer/src/components/Game.vue`,
`viewer/src/logic/auto-decide.ts`).
- `supabase/functions/resolve-automation/` — a server-side single-turn resolver we mirror.
- `docs/lost-fleet/PROGRESS.md`, `FUZZER_PLAN.md`, `PREMOVE_PLAN.md`, `PERFORMANCE.md` — context.
3. **Verify the measured numbers in §3 yourself** if you can — they were taken with `ts-node`
(unoptimized) on one core and will differ on compiled JS / other hardware. They set the
feasibility envelope; don't treat them as fixed.
4. Then brainstorm freely: challenge the architecture, the training approach, the strength
boosters, the leaderboard/anti-cheat design, and the milestones. Push back where you disagree.
The goal we are optimizing for: **the strongest possible AI opponent for ONE specific, fixed game
setup**, so humans have a genuinely hard "beat the AI" monthly challenge.
**Review artifacts:** this file plus its companion `docs/lost-fleet/AI_STRATEGY_NOTES.md` (both on
`master`). The setup is locked in §2 and validated; **nothing is coded yet**, so review the _design_,
the _feature list_ (§6–§7), the _milestones_ (§9), and the _open questions_ (§10) — and push back
hard. The single biggest unknowns that only code resolves: engine simulation speed (§3 clone cost),
state-representation completeness (§7.4), and the free-action branching (§10).
---
## 1. Goal & scope
Build a monthly challenge where the board **seed, the factions, and the turn order are all fixed
and known in advance**. A human picks one of the pre-assigned factions and plays it; the AI plays
the remaining seat(s). The human's goal is to beat the AI — scored by **margin** (human final
score − AI final score), so it's an optimization puzzle, not a binary pass/fail.
**Why fixing the setup is the whole trick:** it deletes the hardest problem in game AI —
generalization across the astronomically large space of boards/tiles/factions/drafts. We no longer
need an AI that plays _any_ Gaia game well; we need one that plays **this one game** extremely well.
That turns "solve Gaia Project" (research-lab hard) into "deeply analyze one position" (tractable on
a single machine). Every design choice below exploits this.
**Chosen AI strength target:** a trained neural network **plus live MCTS** (AlphaZero-style),
specialized to the one fixed setup, with additional cheap strength boosters (§6).
**This is a recurring monthly challenge.** The architecture is built once and reused for every new
seed; only the challenge definition, the trained weights, and the opening book are regenerated each
month, and prior months' models/data warm-start and strengthen later ones. See §5.4 for the monthly
production workflow and cross-month transfer.
---
## 2. The fixed setup (LOCKED)
The first challenge's setup, supplied by the owner and validated against the engine:
```
Seed: lf-mrj5exuu-c680 (validated — boots a legal Lost Fleet 2p game)
Base or Lost Fleet: Lost Fleet
Player count: 2
Options: factionVariant "standard", no auction, advancedRules off
Turn/setup order + faction per seat (ORDER = turn order):
Seat 1 (first player): Xenos ← DEFAULT (owner's listed order); say the word to flip
Seat 2: Hadsch Hallas
Human's seat: human may pick EITHER faction; the AI plays the other
(one seed-locked self-play net plays both seats — free, see "Free replayability")
```
**This board, decoded from the engine** (round-scoring, final-scoring, boosters, ships) — full detail
- strategic read in `AI_STRATEGY_NOTES.md` §11:
* Round scoring: **R1** 3 VP/Trading Station · **R2** 3 VP/mine-on-Gaia · **R3** 2 VP/terraform-step ·
**R4** 3 VP/first-mine-in-a-new-sector (Lost Fleet) · **R5** 5 VP/PI-or-Academy · **R6** 4 VP/mine-on-Gaia.
* Final scoring: **most sectors** + **most Gaia planets**.
* Lost Fleet: 3 ships (2 shuttles), ship techs {tfmars, eclipse}, ship feds {twilight, tfmars, eclipse},
2 artifact tokens.
* **Central tension:** the board is Gaia-heavy (two mine-on-Gaia rounds + the Gaia final) _and_
expansion-heavy (new-sector round + Sector final); neither Xenos nor Hadsch Hallas is a native
gaiaformer, so gaiaforming investment vs wide expansion is the defining trade-off to solve.
Notes:
- **Order = turn order.** Gaia's initial turn order derives from setup pick order, so the listed
sequence _is_ the turn order (unless the owner specifies otherwise).
- Faction-specific setup steps (Ivits' PI placed last, Xenos' extra mine, the Lost Fleet expansion
factions placing 1 mine after base factions, etc.) are handled automatically in the scripted
setup prefix — the owner only supplies the lineup.
- The setup is expressed to the engine as `init <players> <seed>` followed by a **scripted prefix
of `ChooseFaction` (and any forced setup) move lines**. Deterministic replay (an enforced engine
invariant) guarantees the same starting position every time.
**Chosen format: 2-player (human vs one AI)** — committed. For a _strongest-possible-AI_ skill
leaderboard, 2p is the best choice on every axis, and it makes the game a clean zero-sum problem we
exploit hard in §6.7:
- **Strongest AI per unit of compute** — games are ~half the length (~53 vs ~111 turns, §3),
self-play is ~2× faster, and 2p search/value is far cleaner than the multiplayer case, which
brings kingmaking and the hard max-n opponent-cooperation problem. Fewer opponents → a better AI.
- **Purest, fairest test** — a clean head-to-head; no third-party AI whose interactions randomly help
or hurt the human (that variance is bad for a skill leaderboard).
- **Cheapest to make deterministic and verify** (one AI seat, fewer moves), and fastest to iterate.
- 3-player is a reasonable occasional variety; **4-player is the worst fit** (maximum variance, fuzzy
"did I beat it", weakest AI per unit of compute).
**Free replayability:** seed-locked self-play trains _one_ net that plays _every_ seat, so letting the
human pick **either** of the two factions (AI takes the other) costs no extra training — two ways to
play each monthly challenge. The challenge: 2p, fixed seed, two pre-chosen factions + fixed turn
order, human picks either faction and tries to out-score the AI, ranked by **margin**, easy/hard tiers
via AI search depth.
---
## 3. Feasibility findings from the current codebase (measured this session)
These numbers were taken via `ts-node --transpile-only` on a single core (i.e. a pessimistic floor;
compiled JS is several× faster). They define what's affordable.
| Operation | Cost | Note |
| ------------------------------------------------ | ------------------- | ------------------------- |
| Full random game, 2p (via fuzz harness) | ~355 ms, ~53 turns | includes fuzzer overhead |
| Full random game, 4p | ~770 ms, ~111 turns | |
| Raw `engine.move()` per committed line | ~0.8 ms | full-game rollout ≈ 40 ms |
| **Clone (`JSON.stringify` → `Engine.fromData`)** | **~1.4 ms** | **the MCTS bottleneck** |
| Serialized engine state | ~25 KB | fine |
| `generateAvailableCommandsIfNeeded()` | cheap | fine |
**Key structural facts that make this buildable:**
- **A headless self-play harness already exists**: `engine/src/fuzz/driver.ts` (`fuzzGame()`) plays
a full game `init → EndGame` with no UI, looping `generateAvailableCommandsIfNeeded()` → pick →
`engine.move()`. `engine/src/fuzz/random-player.ts` (`chooseMovePart()`) is a ready-made
**"legal command → concrete move string" mapper** for every command type — the action
enumeration layer any bot / policy head needs.
- **Legal moves are cleanly exposed** via `engine.generateAvailableCommandsIfNeeded()` →
`AvailableCommand[]`, each with structured `.data`. The branching factor lives _inside_ `.data`
arrays (factions, buildings+coords, tracks, tiles…), not in the number of commands.
- **Turns are sequential sub-moves**: a move "line" is built part-by-part, committed when
`engine.newTurn` flips true. Low per-decision branching — good for search.
- **State clone = JSON round-trip**, and games are **deterministic from seed + move list** (an
enforced fuzz oracle). Perfect for MCTS and for leaderboard verification.
- **Eval surface exists**: `player.data.victoryPoints` is live; resources are on `PlayerData`;
`finalScorings` gives endgame conditions. Enough for a heuristic evaluator.
- **Setup is fully inspectable**: `engine.tiles.scorings.round[]` (6 round tiles),
`.scorings.final[]`, `.boosters`, `.techs`, `engine.map`.
**The one engine change worth considering:** clone at ~1.4 ms caps naive MCTS at ~700 clones/sec.
An **incremental undo / copy-on-write** instead of full JSON clone is the single highest-leverage
performance change for a search-heavy bot. Not required to start, but flagged.
---
## 4. Architecture overview
Three layers, each reusing something that already exists:
1. **Engine-side AI module** (`engine/src/ai/`) — features, evaluation, MCTS, net inference,
opening book. Pure TS, runs on CPU (net inference is small; no GPU needed at play time).
2. **Seed-locked training pipeline** — offline self-play restricted to the one fixed setup,
producing the specialized net + opening book.
3. **UI / persistence wiring** — challenge entry in the viewer (client-side play + AI compute in a
Web Worker), Supabase for challenge definitions, leaderboard, and **replay-based verification**.
### 4.1 Proposed `engine/src/ai/` layout
| File | Responsibility | Notes |
| ---------------- | -------------------------------------------- | ----------------------------------------------- |
| `ai/features.ts` | engine state → numeric feature vector | encodes _what to look at_ (see §7) |
| `ai/evaluate.ts` | feature vector → scalar/vector value | Tier-0 heuristic; weights hand-set then learned |
| `ai/policy.ts` | move-ordering priors over legal moves | biases which moves MCTS tries first |
| `ai/mcts.ts` | Monte Carlo Tree Search (max-n) | uses net for policy+value at leaves |
| `ai/net.ts` | neural net inference (load weights, forward) | small MLP/CNN over features/planes |
| `ai/book.ts` | opening-book lookup keyed by move-prefix | precomputed for the fixed setup (§6.1) |
| `ai/bot.ts` | `decide(engine, seat): move line` | ties book → MCTS → net together |
| `ai/selfplay.ts` | seed-locked self-play game generator | reuses `fuzz/driver.ts` loop shape |
The bot's public entry mirrors the existing auto-decide hook (see §8): `decide(engine, seat)`
returns a committed move line, given the current engine state.
---
## 5. The AI approach (net + live MCTS, seed-locked)
**Reframe that governs everything:** a faction/position's value is _not_ a fixed number — it is the
expected result of the game that follows under good play. So faction choice and every in-game move
are the _same_ search problem; `ChooseFaction` is just an early node. With the setup fixed, we
specialize a single net + MCTS to that one tree.
### 5.1 Offline (training time — no human present, take as long as you like)
- **Self-play restricted to the fixed seed/factions/turn-order.** Because the "distribution of
games" is one board, the net needs a tiny fraction of the data a general net would — plausibly
**hours to a few days on one machine with a GPU**, versus weeks-to-months for a general model.
- **Loop (AlphaZero-style):** current net + MCTS play games against themselves → those games train
a better net → repeat. Old self-play data is deliberately discarded (rolling replay buffer);
the **deliverable is the small weights file**, not a growing archive.
- **Stop criterion:** train until the new net stops beating the previous version (measured
head-to-head on the fixed setup). Observable and tunable — no blind time commitment.
- **Exploration built in:** Dirichlet/temperature noise + some varied/weaker opponent lines so the
net is calibrated in the off-distribution positions **humans** actually create, not only
strong-vs-strong lines.
### 5.2 Online (play time — human is playing)
- The AI reads its move from: **opening book** (if in book) → else **live MCTS** guided by the net.
- Runs **client-side in a Web Worker** so the UI never freezes and search isn't constrained by
edge-function CPU/time limits.
- **Determinism:** seed the MCTS RNG from `game seed + ply` so the AI's moves are reproducible —
required for server-side leaderboard verification.
- **Owner-locked maximum mode (2026-07-13):** every supported device runs the same model/book and
fixed high simulation workload. Do not shorten search or substitute a smaller model for a slow
device; declare incapable devices unsupported. Faster hardware changes waiting time, not the
configured opponent. The later UI must show real search progress, a moving ETA range, and a
worker heartbeat, and must report browser background suspension distinctly.
### 5.3 Handling unexpected human moves
The net/MCTS does **not** memorize a fixed line — it evaluates positions, and live MCTS searches
from wherever the human actually took the game, so any move is answered by fresh analysis. The
exploration in §5.1 ensures unusual-but-good human lines aren't off-distribution surprises; bad
human moves land in positions the AI is winning comfortably anyway.
### 5.4 Monthly production & cross-month improvement
This is a **monthly** challenge, so the architecture is built once and reused every month.
Separate three kinds of thing:
- **Reusable / write-once (seed-agnostic):** the entire `ai/` module (features, evaluate, policy,
mcts, net architecture, selfplay, bot), the training pipeline, tuned MCTS hyperparameters, the
strength-measurement harness, the UI challenge framework, and the Supabase verification/
leaderboard plumbing. None of this changes month to month.
- **Per-challenge / regenerated monthly:** the challenge definition (seed + factions + turn order),
the trained **weights file**, and the **opening book** (100% seed-specific — never reused). Plus a
per-challenge leaderboard.
- **Accumulating across months:** a general **base net**, the self-play corpus feeding it, and the
**human-game corpus** the challenge itself produces.
So spinning up month N+1 = fill in a new challenge definition + run the (unchanged) pipeline to
produce new weights + a new book. **The code does not change.**
**Can previous months' data/model improve next month's? Yes — four mechanisms:**
1. **Warm-start / fine-tuning (biggest practical win).** Don't train each month from scratch.
Initialize the new seed's net from prior weights and fine-tune on the new seed's self-play — you
_re-specialize_ instead of re-learning Gaia. Turns each month's training from days into hours and
gives stronger starting play.
2. **Base model + monthly specialist.** Keep one persistent **base net** trained on the union of all
past self-play (general Gaia strength). Each month, fork it and fine-tune to the specific seed.
As the base grows, every month's starting point is stronger — a compounding effect.
3. **Reused features / hyperparameters / recipe.** Feature set, network shape, MCTS constants,
training schedule — all carried over unchanged.
4. **Human-game flywheel (the compounding advantage).** Every month's challenge generates real human
games on that seed. Accumulated, they train a **human-move predictor** (focus search on what
humans actually do), calibrate the value net in human-reachable positions, and serve as
evaluation. The challenge literally produces the data that makes future AIs better at beating
_humans specifically_.
**Data-reuse nuance (be precise):** raw self-play _games_ from month A are on board A, so they are
**not** direct training data for month B's _specialized head_ — but they are exactly the fuel for the
general **base net** (#2). Per-seed fine-tuning always uses fresh self-play on the new board; old
self-play lives on in the base model. Human games (#4) transfer across months because the skill they
teach (modeling human deviation) is board-general.
**Caveat — negative transfer:** warm-starting from _last month's over-specialized_ net can carry
that board's quirks into the new one. Prefer warm-starting from the **general base**, or fine-tune
with enough new self-play to wash out stale specifics. The opening book never transfers.
---
## 6. Cheap strength boosters (stack on top of net + MCTS)
Ordered by leverage-per-effort. The first four are the highest-impact cheap adds.
### 6.1 Opening book — the fixed-seed superpower (biggest cheap win)
The first N plies are the _same tree every game_. Analyze them exhaustively offline, store best
responses in a table keyed by the move-history prefix. Instant, near-perfect openings; live search
is saved for the midgame. Exists _only because_ the setup is fixed.
### 6.2 Search efficiency (all cheap, standard)
- **Transposition table** — cache evaluations; many move orders reach the same state.
- **Root parallelization** — MCTS across several Web Workers, combined.
- **Ponder on the human's turn** — keep searching likely replies while the human thinks (free
wall-clock currently wasted).
- **Tune MCTS constants** (PUCT `c`, Dirichlet noise, temperature schedule) via self-play.
- **Raise the simulation count** — the blunt lever; affordable when pondering + no human wait.
- **Adaptive time/compute allocation** — spend more simulations on pivotal, high-variance decisions
(federations, big forks, contested claims) and fewer on obvious ones.
### 6.3 Score-margin value target (make it relentless)
Train the value head to predict **score margin**, not win/loss (KataGo-style). A win/loss net
coasts once ahead; a margin-maximizing net keeps pressing for every point — exactly right for a
**margin-scored** "beat the AI" challenge. Cheap target change, large behavioral difference.
### 6.4 Per-player value vector (multiplayer only — NOT used in the 2p challenge)
Predict every seat's outcome, not a single scalar — the correct formulation _if_ you ever add a 3–4p
variety challenge. **For the committed 2p format this is superseded by §6.7** (a single margin scalar
- negamax is cleaner and stronger). Keep this only for a future multiplayer variant.
### 6.5 Auxiliary training heads
Also predict ownership / future scoring (KataGo-style). Buys strength and sample-efficiency for
little cost by forcing a richer representation. Training-only.
### 6.6 Human-coverage in training
(See §5.1.) Exploration noise + varied opponents so the net is calibrated where humans go.
**Does NOT apply:** board-symmetry data augmentation (a classic cheap AlphaGo trick) — the board is
one fixed _asymmetric_ layout, so there are no symmetric equivalents to augment with. Skip it.
### 6.7 Two-player is a clean zero-sum game — exploit it (the biggest 2p-only lever)
Committing to 2p + **margin** scoring (§1) makes this a genuine **two-player zero-sum game**:
my margin = −opponent's margin. That unlocks strength levers unavailable (or much weaker) in
multiplayer:
- **Single-scalar, low-variance value + negamax.** The value head predicts one number (expected
margin) with a clean negamax backup instead of a per-player vector + max-n → lower variance, faster
training, stronger net. (Supersedes §6.4.)
- **Alpha-beta / minimax search.** Zero-sum 2p admits alpha-beta pruning (impossible to apply cleanly
under multiplayer max-n). Complement MCTS with it — or use deep exact search near the end — for far
greater effective depth at the same budget.
- **A much deeper opening book (§6.1).** One opponent → a far narrower opening tree, so the fixed-seed
book pre-solves _much_ more of the game for the same storage/compute.
- **Exact late-game solving.** Late 2p positions have few branches; the last round or two of a
fixed-seed game may be **exactly solvable** by full search → perfect endgame play that directly
maximizes the scoring margin (squeezing the final points). Infeasible in 4p.
- **Clean best-response / human exploitation.** With exactly one opponent to model, the human-game
flywheel (§5.4 #4) feeds a single **human-move predictor**, and you can compute a **best response**
to it — a policy tuned to punish the mistakes real humans make on this seed, not just Nash-strong.
This makes the AI specifically hard for _humans_ to beat.
- **More valuable pondering (§6.2).** Only one opponent's move to anticipate; predict it and
pre-search the reply precisely.
Net effect: 2p lets you _drop_ multiplayer complexity (max-n, kingmaking, per-player value) **and**
run deeper, cleaner search with a lower-variance net — stronger AI for less effort.
### 6.8 Opportunistic denial (cheap thwarting) — without spite
Desired behavior: predict what the human is going for, take **cheap** chances to thwart it — even a
slightly suboptimal move — but never spite-block at real cost to yourself. This falls out of two
things already in the plan, combined:
- **The margin/zero-sum value (§6.7) sets the threshold automatically.** margin = my score −
opponent score, so a move that costs me 2 to deny the opponent 5 is **+3 margin** (search takes
it); costing me 5 to deny 3 is **−2 margin** (search rejects it). The exact "cheap thwart yes /
costly spite no" line _is_ the margin calculation — not a hand-tuned threshold.
- **Do NOT add a separate "hurt the opponent" bonus.** Margin already counts opponent losses; an
extra denial reward double-counts and produces an over-blocking, spiteful AI. Let margin own the
cost/benefit; this _is_ the "don't ruin it for yourself" guardrail, and it's automatic as long as
denial isn't over-encoded.
- **The opponent model (§6.7) makes the AI _see_ what to deny.** Search only blocks a plan whose
payoff it can see; if the human's target is beyond the search horizon, a cheap block is missed. A
**human-move predictor** ("the human is heading for X") lets the AI evaluate "cheaply deny X"
without searching all the way to X, and a **threat/denial feature** (§7-style: the opponent's
likely plan + the cost-to-me vs damage-to-them of the cheapest interfering move) makes it sharp.
**Why this needs the human model specifically:** self-play trains against a _strong, flexible_
opponent that rarely telegraphs a fat, deniable single-track plan — so a purely self-play AI tends to
_under_-value denial against humans. Humans commit to predictable plans that _can_ be cheaply
thwarted; the human-game flywheel (§5.4 #4) teaches the AI to notice and punish that. Much of "cheap
thwarting" is simply winning the §7.1 contested-resource races (block the hex they need, grab the
per-round action first, take the tile they're racing for); the new part is predicting the _softer,
non-obvious_ targets.
---
## 7. Where strategy knowledge lives (and how it "folds in")
Strategy tips are **never fed to the model as text** (no tokens; this is not an LLM). The developer
translates each tip into code, and training tunes how much it matters:
| What you know | Where it's written | Form |
| ------------------------------------------------------------------- | ------------------------ | ---------------------- |
| _What matters_ (leech potential, round-scoring alignment, blocking) | `ai/features.ts` | state → numbers |
| _How much_ it matters | `ai/evaluate.ts` weights | hand-set → **learned** |
| "Try these moves first" | `ai/policy.ts` | move-ordering priors |
| "Roll out roughly like this" | rollout policy | biased play |
**Principle:** encode knowledge as **features** (what to look at), not verdicts (what to conclude).
A tip becomes a feature with a _learnable_ weight; if the tip is wrong, self-play drives the weight
toward zero. Keep hard "never/always" rules to a bare minimum (only genuinely dominated moves), and
**ablation-test** anything uncertain (run with the heuristic on vs off over N seeded games: better
without → it was a ceiling; worse → it was a useful prior).
Feature ideas to seed from setup (`engine.tiles`, `engine.map`): round-scoring alignment (weighted
by round), final-scoring affinity, terrain/color reachability, booster/tech-tile fit, per-neighbor
leech potential, hex blocking/adjacency, seat/turn-order position.
A **human-readable strategy doc** (for maintainers) is separate from these machine-usable encodings
and does not feed the model. That doc lives at **`docs/lost-fleet/AI_STRATEGY_NOTES.md`** — a
fill-in intake of human play knowledge, organized so each tip maps to a concrete encoding (feature /
policy prior / eval weight / rollout bias / rare hard-avoid). A developer translates its entries into
the `ai/` code; the file itself is never read by the model.
### 7.1 Contested & limited-availability resources (races and tempo)
Gaia is full of **contested, limited-availability resources**, many of them powerful. They come in
two kinds, both races:
- **One-time claims (whole-game race):** advanced tech tiles (one copy each, gated by research level
- a federation token), federation tiles (limited stacks, can be exhausted), Lost Fleet **expansion
federations**, **artifact tokens** (limited, seeded), the Lost Planet, key blocking hexes. Once
taken, gone forever.
- **Per-round shared actions (within-round race):** the board **power actions**, the **QIC/green
actions**, and Lost Fleet **ship actions**. Any player may take them, but each is available only
_once per round_, so within a round it's a sprint to grab the one you want before a rival does —
and it hinges on **turn order this round** (can you reach it on your turn before an opponent reaches
it on theirs, with the resources ready?).
Whoever reaches the prerequisites first claims the prize and denies it to everyone else. The AI must
recognize the race, track how close every faction is, and avoid moves that surrender its lead.
**This is handled emergently by net + MCTS — no bespoke race-tracking code required:**
- MCTS with opponent modeling (max-n) literally simulates the opponents racing for the same prize.
"Keep track of everyone else's path toward it" _is_ the search tree exploring their best
responses — including them rushing the prerequisites and taking it in the branches where the AI
delays.
- The value net (with the score-margin target, §6.3) learns that being ahead in a race is winning,
because in self-play the games where it secured the prize scored higher. A move that surrenders the
tempo lead therefore _evaluates worse_, so the AI avoids it — exactly the "don't fall out of the
lead" behavior. It falls out of the objective; it is not hand-coded.
**Caveat + cheap fix:** races span many turns, which stresses search horizon and credit assignment,
so pure search alone can be shaky. Make it sharp and robust with an explicit **contention feature**
(a §7 "what to look at"), covering both kinds:
- _One-time claims:_ for each contested asset, _moves-until-I-can-claim-it_ vs
_moves-until-each-opponent-can_ → a per-asset **lead/deficit** signal.
- _Per-round shared actions:_ current **availability** + whether I can **afford/reach** it before
each opponent given **this round's turn order**.
This hands the net the race arithmetic instead of forcing it to rediscover the counting from raw
state, so it plays every race precisely even at modest search depth. Board-general and reused every
month; applies to the whole contested-resource family, not just advanced tech.
**Fixed-seed bonus:** because the opening is the same tree every game, the opening book (§6.1)
_pre-solves_ the early race optimally — the AI plays the fastest correct line to a contested prize
from move one.
---
### 7.2 "Economy" is projected position, not the Economy track
Round 1 is almost pure engine-building: early VP is tiny next to the compounding value of a strong
economy into round 2+. The AI should be strongly motivated to build that economy — two cautions on
_how_ that's encoded:
- **It's emergent from the value target, not a round-1 rule.** Because the value net is trained on the
**final score margin** (§6.3), not per-round points, it _learns_ that round-1 economic investments
pay off by round 6 — so it values them without any "round 1 = economy" rule. Train value on the end
result and the motivation appears on its own; a hard round-specific rule would only make it rigid
("shouldn't be that strict"). Reinforce it cheaply, if at all, with a **projected-economy feature**
(a prior), never a rule.
- **Economy is multi-dimensional — do NOT proxy it with "Economy track level."** That naive proxy is
exactly the brittle heuristic that makes an AI always climb Econ and ignore stronger paths. Measure
the real thing: **projected resource income & production per round + board presence (planets,
quality, expansion room) + leech/gaia potential + tech position.** Then "strong board presence" and
"denied the opponent a key planet" are valued on the same footing as income — board presence via
the positional part of the feature + the value net; denial via margin (§6.8). The AI trades "climb a
track" against "grab/deny a planet" by their effect on projected position and final margin, and
correctly picks the planet when it's worth more. That _is_ the "not always the Econ track" behavior,
automatic under a sound value function — the only way to break it is to over-encode a single track.
**Fixed-seed bonus:** round 1 on this board is largely _solved_ by the opening book (§6.1) — the best
economic path into round 2 (weighing income vs board presence vs denial) is precomputed by deep
search, so the AI plays it optimally from move one instead of approximating it with a heuristic.
---
### 7.3 Federation planning (look-ahead + combinatorial optimization)
Forming federations is one of the deepest planning problems in the game: you plan several turns ahead
to connect buildings into a group of ≥7 power value (the threshold; faction abilities can modify it),
choosing _which_ buildings and _how many satellites_ (each satellite spends a power token, permanently
shrinking your power economy). The competing factors:
- form **early** for the fed-tile boost (resources/tech/mines/VP) and to unlock the fed token that
gates advanced tech (§7.1) — vs form **efficiently** (least waste);
- hit the threshold with **minimal overshoot** (~7 power) and **fewest satellites**;
- but a **final-scoring tile rewarding satellites/federations** partly flips the satellite "cost" —
though even then, don't spend all your tokens on fed 1 and cripple the rest of the game;
- don't stuff a fed with many 1-power **mines** (more buildings + satellites, and later upgrading them
adds power the formed fed can't use);
- yet "**never upgrade a building already in a fed**" must NOT be a hard rule — sometimes the upgrade's
own income/tech/scoring value warrants it.
**The one genuinely new hard part — already solved by the engine.** Choosing the buildings + satellites
is a minimum-satellite connection (Steiner-tree-like) optimization. The engine **already enumerates
candidate federations**: `Command.FormFederation` offers `command.data.federations` (computed candidate
hex-sets) + a fed-tile choice. Search picks among _bounded candidates_ and decides _when_, instead of
solving the connection problem at every node — keeping fed branching tractable.
**The rest is soft/emergent under the value-on-final-margin net (not hard rules):**
- _7-power / few satellites_ → a **fed-efficiency** preference the net learns (overshoot + wasted
tokens lower the final margin).
- _satellite-scoring final tile_ → the net sees the final-scoring feature (§4) and flips the satellite
sign, while still balancing token economy across the whole game so it won't cripple itself.
- _don't overload mines; "upgrading a fed building is usually a no-go, sometimes right"_ → the net
values an upgrade for its _own_ benefits (income/tech/scoring) minus the now-redundant fed-power
(worth nothing), so it skips fed-power-only upgrades and takes the ones whose other value pays off.
The exceptions are automatic — encode as FEAT/WEIGHT, **never** AVOID.
**Cheap features for the long horizon (§7 "what to look at"):** a **federation-efficiency** feature
(power over threshold, satellite token cost, buildings committed) and a **federation-readiness/
potential** feature (how close a cheap fed is; how many feds the board can eventually yield — so the AI
places buildings to be connectable and doesn't strand power). Early-game feds on the fixed board are
shaped by the opening book (§6.1); fed tiles are contested singletons handled by §7.1.
### 7.4 Pass timing, overcharge, and state-representation completeness
Two subtle behaviors — and the meta-lesson they teach.
- **Pass early for tempo (don't reflexively use every action first).** The first player to pass takes
first position next round → first pick of the next booster and first grab of contested per-round
claim actions (power / QIC / ship / adv-tech). So passing _before_ spending every action or resource
is sometimes best — it's really a §7.1 race: passing first _wins_ the race for next round's booster
and claims. **But it is rare in strong play** — only when the actions/resources you'd forgo are
worth _less_ than the tempo; with a full hand of useful actions, do **not** pass. The pass-tempo
feature must be weighed _against_ the value of your remaining actions; the danger is a prior that
over-values passing, so bias Pass neither way and let the value comparison decide. To get it right:
- Treat **Pass as a first-class move** the search evaluates whenever legal — do **not** bake in the
common "spend everything, then pass" default (that bias is exactly what makes bots miss this; the
fuzzer's growing pass-weight is for termination only).
- Add a **pass-tempo feature**: if I pass now, do I get first player, and what is that first pick
worth (booster + which contested claims)? Plus keep power for next round's power actions rather
than dumping it — the net weighs "saved power for claims" vs "spend now."
- **Avoid overcharging power.** Charging when bowls are already full (or will be filled by income)
wastes it, so accepting leech (which costs VP) to overcharge is paying VP for nothing, and an
overcharging booster is wasted. Usually avoid — but _soft_ (faction/tempo exceptions), so encode a
**wasted-charge feature** (charge lost to full bowls, incl. incoming income) as FEAT/WEIGHT, never
AVOID. The engine's auto-charge (`auto-decide.ts`) already decides leech; the bot's choice should be
value-driven and see this waste.
- **Meta-lesson — audit state/feature completeness.** Both behaviors are only learnable if the AI's
representation _includes_ the relevant state: **power-bowl contents, pass status, turn/pass order.**
A net that can't see the bowls can't learn overcharge; one that can't see pass order can't learn
pass-tempo. Walk every strategic factor in this doc and `AI_STRATEGY_NOTES.md` and confirm each is
visible in the net's input — **most AI blind spots are missing input features, not weak search.**
### 7.5 Burning power: to enable/deny a power action — but prefer natural leech
Pros deliberately **burn power** to reach bowl 3 and take a power action (ore/credits/etc.) — but
selectively, and this is another "sometimes, not always" that must stay conditional (never a rule):
- **Justified only when the enabled action beats the burn's loss.** Burning is lossy (~half the
tokens are discarded), so it pays only when the power action gives something you really need — e.g.
**credits/ore at or near zero** — or as **denial** (a §7.1 race / §6.8: burn to take it _before_ the
opponent). Value/search computes the threshold; do **not** hand-code "burn whenever you can"
(wasteful) or "never burn."
- **Denial precondition — don't burn to race a ghost.** Burning to grab a power action _before the
opponent_ only has value if the opponent can actually take it **soon**: either they **already have
the bowl-3 power ready**, OR **your own upcoming move will charge them** into range (§7.6). If
neither holds, there is no one to deny — do not burn; it's pure waste. This needs the opponent
power/build model (§6.8) and visibility of the opponent's bowls (§7.4).
- **Prefer reaching bowl 3 naturally.** If the opponent is about to build where you can **leech**,
you'll charge for free — so don't burn. This needs the **opponent-build predictor** (§6.8): a
feature for **expected natural charge from the opponent's likely next builds** tells the AI whether
to wait for leech or burn now. Burn only when you _can't_ wait (e.g. the opponent can already take
the action this turn).
- Encode as FEAT/WEIGHT, never AVOID/always. Requires seeing bowl state + resource levels + the
opponent's build options (state-completeness, §7.4) — otherwise the AI can't tell "burn now" from
"wait for leech" and misfires both ways.
### 7.6 Deny/delay opponent leech via move ordering
The mirror of §7.5: building adjacent to an opponent lets _them_ charge power. Giving them a big
charge early (e.g. 4 power — a full bowl-3 fill — or enough in bowl 2 that they can burn to reach a
power action) hands them _timely_ resources. So when several moves are queued, **order them so the
leech-granting builds come as late as possible**, denying the opponent usable power.
- **The cost is already in margin.** The opponent's power gain is your loss, so the value net counts
it. What remains is a _sequencing_ problem — the search explores orderings of your moves and prefers
the one that leaks the least usable charge, with the value net evaluating the resulting states
(opponent power + what it enables).
- **Cheap feature:** an **opponent-leech-cost** signal per move — how much charge it grants and _how
usable it is to them right now_ (convertible to a power action they want, directly or via burn this
round?). The flip side of §7.5's expected-natural-charge; needs the same opponent power/build model
(§6.8). A move-ordering **prior** can also try low-leech orderings first.
- **Conditional, not a rule.** Don't delay a build you need now just to avoid leech — the value
function trades "my tempo from building now" vs "the opponent's power gain." "As long as possible"
means _when the ordering is otherwise free or the leech is costly_, not always.
- Needs to see opponent bowls + what a charge enables them (state-completeness, §7.4).
---
## 8. UI & flow wiring (reusing what exists)
Existing seams we build on:
- **`viewer/src/self-contained.ts`** — boots a full game client-side from `{players, seed, moves,
options}`. A challenge = fixed `seed` + scripted `moves` prefix. This is the challenge's home.
- **`viewer/src/logic/auto-decide.ts`** (`autoDecideChargePower`) — existing pattern for a
non-human seat auto-acting and feeding a move through the commit pipeline. The AI opponent is a
generalization of this call-site.
- **`supabase/functions/resolve-automation/`** — server-side single-turn resolver (premove/
auto-charge). Template for a server-side bot seat if ever wanted.
- **Deterministic replay + `(seq, move)` move storage + `engine.bundle.js`** (engine already
bundled for the edge) — gives **replay-based leaderboard verification for free**.
**Recommended shape — client plays + AI computes; server persists + verifies:**
1. **Challenge definition** — `{ id, month, seed, playerCount, options, setupMoves[],
humanFactionChoices[], modelAsset }`. Start as static JSON; graduate to a `challenges` table.
2. **Challenge entry UI** — a route beside `hosted/CreateGame.vue` / `Lobby.vue`: shows the current
challenge + leaderboard; "Play" boots the self-contained viewer with `seed` + `setupMoves`, lets
the human pick from `humanFactionChoices`.
3. **AI-seat driver** — `viewer/src/logic/ai-opponent.ts` mirroring `auto-decide.ts`:
`aiDecide(engine, seat): Promise<string>`, delegating to `ai.worker.ts` (net + MCTS in a Web
Worker). Wired at the same call-site as `autoDecideChargePower`: after each committed move, if
the next seat is AI, compute and `emit("move")`.
4. **Human-seat lock** — in challenge mode, `Commands.vue`/`Game.vue` accept input only when
`playerToMove === humanSeat`; AI seats are worker-driven. (Reuse hosted mode's "which seats are
mine" notion.)
5. **Model asset** — the trained weights file served as a static Vercel asset; loaded by the worker.
6. **Result submission + verification** — on `EndGame`, POST `{challengeId, faction, moveHistory,
scores}` to a Supabase RPC/edge function that **replays `moveHistory` through `engine.bundle.js`**,
recomputes scores, checks the human's margin/placement, and inserts a verified leaderboard row.
7. **Leaderboard UI** — read from Supabase; rank by **margin**.
**Leaderboard integrity note:** because net + MCTS has randomness, the AI must be **deterministic**
(seed RNG from game seed + ply) so the verifier can confirm the AI moves in the submitted log are
legitimate (not tampered to be weak). Two caveats to accept: (a) shipping the model to the client
means a determined player can study it — margin scoring + difficulty tiers make that fine (studying
it _is_ the puzzle); (b) if full re-verification of MCTS moves proves too expensive, fall back to
recomputing only a spot-check of AI moves, or run the authoritative AI seats server-side while
keeping client-side search as a "practice / hard mode."
**Difficulty tiers for free:** same setup, different AI search budget (shallow = easy, deep = hard).
---
## 9. Milestones (each independently testable)
1. **M0 — headless harness confirmed.** Reuse `fuzz/driver.ts`; add a strength-measurement runner
(bot A vs bot B, win-rate/margin over N seeded games).
2. **M1 — Tier-0 heuristic bot.** `ai/features.ts` + `ai/evaluate.ts` + 1-ply greedy `decide()`.
Drop-in for `chooseMovePart`. Benchmark vs random. This is the baseline and the eval harness.
3. **M2 — MCTS bot.** `ai/mcts.ts` (max-n) using the Tier-0 heuristic as leaf evaluator + rollout
policy. Benchmark vs Tier-0. Add transposition table.
4. **M3 — seed-locked self-play + net.** `ai/selfplay.ts` + `ai/net.ts`; train the specialized net
(score-margin value, per-player head, exploration noise). Net-guided MCTS. Train to plateau.
5. **M4 — opening book** for the fixed setup (§6.1) + ponder + root parallelization.
6. **M5 — UI wiring** (§8 steps 1–5): challenge entry, self-contained boot, `ai.worker.ts`,
human-seat lock, maximum-mode capability gate, and truthful progress/ETA/heartbeat.
7. **M6 — Supabase persistence + verification + leaderboard** (§8 steps 1, 6, 7).
8. **M7 — polish:** difficulty tiers, par-score display, margin leaderboard.
Perf escape hatch: if MCTS is starved by clone cost (§3), implement incremental undo / copy-on-write
in the engine before scaling sims.
**M8 — monthly production loop (§5.4).** Once M0–M7 work for the first seed, factor the per-challenge
artifacts (definition, weights, book, leaderboard) apart from the reusable machinery, stand up the
persistent **base net**, and wire warm-start fine-tuning + the human-game corpus so each new month is
cheap to produce and stronger than the last.
---
## 10. Open questions / for further brainstorming
- Is a full neural net worth it over a very deep MCTS + strong heuristic + opening book for a
_single_ board? (The net earns its keep only if the tree is too big for search alone.)
- Best state/feature representation for the net (planes for the hex map + vectors for
resources/tech/tokens vs. a pure hand-feature vector).
- Exact action encoding for the policy head (fixed enumerated action space + legality masking,
reusing `chooseMovePart`'s canonical mapping).
- How to model / exploit the _specific human population_ (they deviate from self-play). Worth a
learned human-move predictor to focus search, or overkill?
- Leaderboard anti-cheat: full re-verification vs spot-check vs server-authoritative AI seats.
- Whether to invest in the incremental-undo engine change up front.
- Cross-month transfer (§5.4): warm-start from last month's specialist vs from a general base net —
how to avoid negative transfer, and how much the human-game flywheel actually helps in practice.
- **Free-action / resource-conversion combinatorics** (Spend / BurnPower / QIC / brainstone / Gaia)
blow up per-turn branching; how to prune to _useful_ conversions or fold them into the action they
enable without hiding a good line (the fuzzer just caps conversions — a real bot needs smarter
handling).
- **State-representation completeness audit** (§7.4): systematically check every strategic factor is
visible in the net's input before blaming search for a blind spot.
---
## 11. References (read against latest `master`)
- `engine/src/fuzz/` — `driver.ts`, `random-player.ts`, `state.ts`, `run.ts` (self-play backbone).
- `engine/src/engine.ts` — `tiles.scorings/.boosters/.techs`, `map`, `generateAvailableCommandsIfNeeded`.
- `engine/src/available/` — `AvailableCommand` types + `.data` shapes.
- `viewer/src/self-contained.ts`, `viewer/src/components/Game.vue`, `viewer/src/logic/auto-decide.ts`.
- `supabase/functions/resolve-automation/` — server-side turn resolver template.
- `docs/lost-fleet/FUZZER_PLAN.md`, `PREMOVE_PLAN.md`, `PERFORMANCE.md`, `PROGRESS.md`.

View file

@ -0,0 +1,589 @@
# Lost Fleet AI — Current Session Contract
> Canonical compact entry point for the next AI session. Last updated **2026-07-15** after the AI-7
> absolute-score/productivity investigation. Full-game attribution proved that the bots pass with
> unused economies and score far below competent play. One Pass-opportunity candidate improved
> ordinary-turn activity but remained absolutely weak; AI-7 stays open and AI-8 remains unstarted.
> Read this file completely and use the routed references below rather than reconstructing current
> state from historical documents.
## Document ownership
- **This file:** current branch, completed gate, next scope, preserved invariants, and verification
cadence. Update it at each AI phase handoff.
- `engine/src/ai/STRATEGY_DOCTRINE.md`: canonical general strategy principles, evidence confidence,
plan archetypes, and their translation into inspectable AI terms. Read it completely before any
strategy/evaluator/planning change; do not copy seed-specific labels into it.
- `engine/src/ai/README.md`: stable module/API semantics. Update only sections whose implementation
changed; do not turn it into a second handoff.
- `AI_IMPLEMENTATION_PLAN.md`: architecture and actual decisions. Read only cited sections; append
to its decision log only for a new architectural decision or final measured phase result.
- `PROGRESS.md`: project-wide current-task pointer. Keep its AI entry short and link here.
- `AI_PHASE_*_HANDOFF.md`: immutable historical evidence. Do not reread or update unless diagnosing
that phase.
## Lean startup
1. Run `git status --short --branch`, `git log -5 --oneline`, and compare `HEAD` with the named
remote branch. Do not switch branches, discard changes, commit, or push without owner approval.
2. Read `AGENTS.md`, its routed `PROGRESS.md` sections, and this file. The target startup context is
under 4,000 lines / 200 KB.
3. When the task changes strategy, evaluation, or planning, read
`engine/src/ai/STRATEGY_DOCTRINE.md` completely. Otherwise do not preload it.
4. Read plan §1.1–§1.4, §6.3–§6.4, and §§14–15. Do not read the full plan.
5. Inspect these API surfaces first; read their full implementations only when the search design
needs them:
- `canonical-state.ts`: `CanonicalState`, `projectCanonicalState`, `canonicalStateHash`;
- `actions/turn-builder.ts`: `CommittedTurnMacro`, `CommittedTurnMacroSet`, options, and
`buildCommittedTurnMacros`;
- `evaluation.ts`: report types, `terminalUtility`, and `evaluateHeuristic`;
- `bots/types.ts`, `bots/common.ts`, and `bots/heuristic.ts`;
- `testing/self-play.ts` and focused bot/evaluator specs.
6. Use `rg` and follow direct imports when a contract is unclear. Do not preload the generated
manifest, corpus implementation/fixtures, resource planner internals, all canonical/macro specs,
historical handoffs, rules/component ledgers, or the whole AI tree.
## Repository and production state
- Working branch: `claude/gaia-phase-1-4-yjb6qo`.
- Published AI-7 handoff checkpoint: `5d3d8e758ca9f42480beb4e42939cb8c92fa9c27` (`Add AI-7
strategic planning and diagnostics`). It is pushed to the identically named `origin` branch; the
worktree was clean when this metadata follow-up began.
- Local/remote tip at AI-7 start: `16e0f0ae6cc0e4e1ba02d3083e461a0da6972008` (`Add AI-6 baselines
and lean handoff`). The older expected `7c92029e...` base in the owner prompt was one commit behind;
no history was discarded. `origin/master` was separately at `23caf5cca85c03b5d4016bfb817be05ee55e783f`.
- Start from the published branch checkpoint, then treat `git status` as authoritative and preserve
any later local changes exactly.
- `master` is the Vercel production deploy branch. Do not work on, merge to, or push it.
- Keep AI-7 offline under `engine/src/ai/`. Do not add production imports/exports or modify shared
engine behavior, viewer code, Supabase, deployment configuration, hosted data, or feature flags.
- Do not commit, push, deploy, migrate, or change flags without fresh owner approval.
## Completed foundation
- Phase 0: challenge/golden/benchmarks; semantic SHA
`ce3bdd7322860484dfae771320b9f12967d0677b908f91cdc682d9c4427bf51e`.
- Phase 1.1: committed canonical state/hash; 12 focused tests.
- Phase 1.2: typed atomic candidates; 62-candidate digest
`a28eb3d03e2b51e1bea28170b92f5e99991f41c76b1b1c8a2193a97a0ee704d9`.
- Phase 1.3: exact conversion planning; 36,159 reachable / 9,985 frontier / 45 candidates / depth 30;
digest `b4e266ef95ca8cc34cfd1cde4380a782ff01f4802a077d49ac9686924e222850`.
- Phase 1.4: committed-turn macros; locked 52 macros / 32 mains; digest
`972a1e9b062ebcda5a96e2242039bbc29eee83934c9eb41e175a493bb1009096`;
after integration 45 candidate frontiers / 130,532 exact seed pairs.
- AI-6: seeded random, immediate greedy, and deterministic inspectable heuristic bots; 28
independently ablatable features; exact terminal margin and paired full-game harness.
- AI-6 paired results: greedy over random `+43` total / `+21.5` mean / 2–0; heuristic versus greedy
`-36` total / `-18` mean / 0–2. The heuristic is a coverage baseline, not a promoted champion.
- Final AI-6 verification: 12 focused, 68 complete offline AI, full engine 698 passing / 4 pending,
TypeScript and changed-file ESLint clean, production isolation clean. Engine version 4.8.51.
- AI-7: deterministic fixed-frame minimax PUCT over committed macros; inspectable state-only
heuristic-softmax prior; seeded Gumbel/sequential-halving root allocation; selected-subtree reuse;
guarded/ablatable transpositions; visit/value/spread/PV/performance/cache diagnostics; generic
reference trees; paired strength and curated setup/Round-1 through Round-6 harnesses.
- AI-7 calibration: an optional probability-level `greedyMix` blends greedy and heuristic softmax
priors while preserving the frozen heuristic-only behavior exactly at its default of zero.
- AI-7 productivity diagnostics: exact full-game VP attribution, per-round raw scores/action/pass
counts, and end-state development are now part of baseline and search strength results.
## Locked search semantics
- Utility always uses a fixed seat-0 frame: final `seat0 score - seat1 score`.
- At every node, seat 0 maximizes and seat 1 minimizes the same un-negated value. Actor changes do
not imply sign changes; free/forced decisions may keep the actor, and leech may switch it.
- A search edge is exactly one Phase 1.4 committed macro. It is replayed host-style on a fresh
hydrated state, ends at `newTurn`, and matches its canonical destination hash and next actor.
- Terminal utility is exact. Non-terminal leaves use the inspectable AI-6 heuristic.
- Deterministic behavior uses canonical macro keys for ordering/tie-breaking. Any sampling uses an
explicit reproducible evaluation-only seed.
- Search configurations must pin and report `macroBuildOptions`. The AI-6 baseline defaults both
expensive conversion-integration axes off; changing that policy requires a measured comparison,
and enabling an axis must retain the existing exact uncapped planner.
- Fixed simulation counts define comparable search budgets. Do not use wall-clock early exit,
device-dependent silent downgrade, heuristic beams, or caps inside macro/conversion generation.
## AI-7 implemented scope — search baseline and strength harness
All seven planned implementation items are present offline:
Implement offline search only:
1. Deterministic minimax MCTS/PUCT over Phase 1.4 committed macros, with actual-actor max/min backup
and the AI-6 heuristic at non-terminal leaves.
2. An explicit, inspectable non-neural prior policy; no neural or learned opponent model.
3. Seeded Gumbel root action sampling plus sequential halving for the planned low-budget/root
allocation variant. The fixed-budget plain PUCT baseline must remain independently measurable.
4. Tree reuse after an actual selected move.
5. Transposition support only after parity tests prove equal canonical keys, legal macro sets, and
values. Keep it ablatable and report whether it materially helps; correctness comes first.
6. Diagnostics sufficient to inspect visits, prior, mean/fixed-frame value, value spread or
uncertainty, principal variation, expansions/second, reuse, and transposition/cache hits.
7. A strength harness with paired faction assignments, common deterministic seeds, fixed simulation
budgets, margins/wins/nodes/latency, and curated committed positions across setup and rounds 1–6.
The implementation/search-correctness gate is complete. The original search arms did not beat both
greedy and heuristic, but the later scale-16/greedy-75 arm is now the current search-only leader on
paired margin. Both factions completed without command gaps, and fixed-budget cost/reuse/
transposition evidence was recorded. The formal statistically clear Phase 2 gate remains open.
## Frozen AI-7 measurement
The one deliberate campaign used eight simulations per candidate decision, conversion integration
and after-conversion integration both explicitly off, paired faction assignments, and common
evaluation seeds.
- Plain PUCT, one deterministic pair per opponent: vs greedy margins `[-12, -18]`, total `-30`, mean
`-15`, 0-2; vs heuristic `[+10, +16]`, total `+26`, mean `+13`, 2-0.
- Gumbel/sequential halving, four seeds/eight games per opponent: vs greedy
`[-16, -39, -6, -17, -14, -14, +14, -36]`, total `-128`, mean `-16`, 1-7; vs heuristic
`[-10, -1, +11, +30, -1, -9, -6, -8]`, total `+6`, mean `+0.75`, 2-6.
- Plain PUCT expanded 552 nodes / 18,176 edges over 71 candidate selections; mean measured search
latency was 2,781 ms vs greedy and 1,802 ms vs heuristic. Reuse occurred on 63/71 selections.
- Four-seed Gumbel expanded 3,190 nodes / 92,106 edges over 435 selections; aggregate measured search
time was 1,143,801 ms (2,629 ms/selection). Reuse occurred on 418/435 selections.
- The common-seed guarded-DAG ablation produced the same game margins and curated choices as the tree
arm. It recorded 90 transposition hits and 90 successful parity checks, but no demonstrated latency
benefit; transpositions therefore remain off by default.
- Seven deterministic committed probes covered setup and the first RoundMove position in rounds 1-6.
Every probe conserved its eight-simulation budget and selected/applied a legal committed macro.
## AI-7 focused search calibration
The focused follow-up kept plain PUCT, Gumbel off, transpositions off, both conversion axes off, and
the existing exact macro builder. It compared the frozen heuristic-only prior with a 50/50
probability-level greedy/heuristic softmax blend at fixed budgets 1, 2, 4, 8, and 16 on the same seven
setup/Round-1–6 positions. This was a curated probe grid, not a strength campaign.
| Simulations | Heuristic prior: greedy / heuristic matches | 50/50 prior: greedy / heuristic matches | Seven-probe latency, heuristic / blend |
| ----------- | ------------------------------------------- | --------------------------------------- | -------------------------------------- |
| 1 | 1 / 7, 7 / 7 | 1 / 7, 7 / 7 | 4,267 / 4,297 ms |
| 2 | 1 / 7, 7 / 7 | 1 / 7, 7 / 7 | 6,628 / 6,667 ms |
| 4 | 1 / 7, 7 / 7 | 1 / 7, 7 / 7 | 10,116 / 10,076 ms |
| 8 | 2 / 7, 5 / 7 | 2 / 7, 5 / 7 | 14,823 / 14,964 ms |
| 16 | 1 / 7, 5 / 7 | 1 / 7, 5 / 7 | 33,793 / 34,020 ms |
The blend changed **0 of 35** paired curated choices. PUCT initializes an unvisited edge with its
full raw heuristic leaf value, while the exploration term is only about `1.25 × prior`; at these
budgets the heuristic Q scale therefore overwhelms a prior-only mixture. Budget scaling was also
non-monotonic against greedy: two matches at 8 simulations fell back to one at 16.
Two truncated eight-simulation traces (maximum 32 committed lines, never EndGame) identified the
first greedy-evaluator gaps of at least 1 point:
- Xenos line 7: PUCT chose `build m 5B2` over greedy's `build ts 6A4`, leaving 4.25 immediate
greedy-value points. The heuristic primarily favored final-scoring projection (+5.4), projected
ore income (+4), Gaia pipeline (+1.5), and sector progress (+1.25), despite current-score (-3),
projected-credit (-3.3), and stock (-1.38) penalties. Fresh heuristic-prior and blended searches
made the same mine choice.
- Hadsch Hallas line 9: PUCT chose `build m 5A9` over `build ts 4B5`, a 3.15 greedy-value gap. The
leading tradeoff was projected ore income (+4), final scoring (+2.7), Round-tile timing (+2.069),
and sector progress (+1.25) versus current score (-3) and projected credits (-3.3). Fresh and
blended searches again chose the mine.
- Hadsch Hallas line 18: the stateful tree chose `up sci` over greedy's `pass booster8`, a 6.85
greedy-value gap. A fresh heuristic-prior search and the fresh blend both chose `pass booster9`;
the research choice was specific to a descendant reuse root with 5 retained visits, not repaired
by changing the prior.
No diagnostic trace completed a game, so this pass has no final-score result and no raw final scores
to report. The strength result schema and campaign summary retain both raw seat scores for every
completed game; all future completed-game results must continue to print them.
The 50/50 blend is an ablation, not a promoted default or a campaign candidate. The next pass must
address heuristic/Q scaling and evaluator calibration, and separately decide how retained visits
should affect a new root, before autonomously freezing and measuring a new paired candidate.
## AI-7 scale/evaluator calibration and predeclared candidate
The follow-up added three independently ablatable controls without changing their frozen defaults:
- `puctValueScale` divides fixed-frame Q before PUCT adds its dimensionless exploration bonus;
- `leafGreedyMix` blends immediate greedy value into non-terminal heuristic leaf Q while leaving
exact terminal margin untouched; and
- `rootReuseVisitPolicy="reset-subtree"` can retain expanded structure while clearing all reachable
visit/value moments. Diagnostics report visits available before promotion separately from visits
actually retained.
Focused probes narrowed the candidate to value scale 16 with a 75% greedy / 25% heuristic blend in
both leaf Q and the prior. The reproducible seven-position grid compared it with the frozen arm:
| Simulations | Frozen: greedy / heuristic matches | Candidate: greedy / heuristic matches |
| ----------- | ---------------------------------- | ------------------------------------- |
| 1 | 1 / 7, 7 / 7 | 3 / 7, 4 / 7 |
| 2 | 1 / 7, 7 / 7 | 3 / 7, 4 / 7 |
| 4 | 1 / 7, 7 / 7 | 3 / 7, 4 / 7 |
| 8 | 2 / 7, 5 / 7 | 5 / 7, 3 / 7 |
| 16 | 1 / 7, 5 / 7 | 5 / 7, 3 / 7 |
On the fixed candidate's two stateful 32-line traces, retained moments produced one stateful/fresh
choice difference across both seats. The reset arm produced four differences (one trace ended at
line 22), retained zero old visits, and did not expose any material immediate-greedy gap of at least
one point. Retain is therefore the falsifiable candidate policy; reset remains an ablation, not the
campaign arm.
Before any paired result was observed, `testing/strength-campaign.ts` predeclared exactly one new
campaign arm behind `--scaled-greedy-75-candidate`: plain PUCT, eight simulations per candidate
selection, value scale 16, `leafGreedyMix=0.75`, prior `greedyMix=0.75`, retained visits, Gumbel and
transpositions off, both conversion axes off, common seed `ai-7-common-01`, both faction assignments,
and both greedy and heuristic opponents.
That arm was frozen, verified, and run exactly once. Against greedy its candidate margins were
`[-7, +28]`: raw scores `65-72` as Xenos and `56-84` as Hadsch Hallas, total `+21`, mean `+10.5`,
record 1-1. Against heuristic its margins were `[+30, +18]`: raw scores `73-43` as Xenos and `49-67`
as Hadsch Hallas, total `+48`, mean `+24`, record 2-0. Relative to frozen plain PUCT, mean margin
improved by 25.5 points against greedy (`-15` to `+10.5`) and 11 points against heuristic (`+13` to
`+24`). The candidate therefore leads both baselines on paired margin, but one deterministic pair is
not a statistically clear claim and it lost the Xenos/greedy game by 7. Do not rerun, retune, or
reinterpret this measured arm.
Campaign cost: 36 candidate selections / 288 simulations / 9,630 expanded edges / 73,518 ms against
greedy (2,042 ms/selection), and 38 / 304 / 10,998 / 80,828 ms against heuristic (2,127 ms/selection).
Reuse retained all 63 and 75 available promoted-root visits respectively; transpositions remained
off. All four games reached EndGame without command gaps.
## AI-7 absolute-score diagnosis and ordinary-turn productivity
The earlier relative result was not competent play. A decent normal setup is roughly 150–160 VP and
200 is exceptional; the measured search/baseline range of 43–84 is therefore inadequate regardless
of paired margin.
`testing/full-game-report.ts` now attributes every completed game without changing the engine. It
records raw score after every round; per-round Round-tile, Federation, research-track, and other
immediate VP; both named final-scoring tiles/counts/VP; endgame resource and bid VP; ordinary actions,
action families, and Pass turn per round; and final buildings/research/tokens/resources. The reporter
reconciles both every round boundary and the final score exactly against the engine's advanced log.
It is attached to baseline and search game results and printed by the strength campaign.
Fresh heuristic-versus-greedy reporting exposed the common failure:
- the four players took only 1, 3, 4, and 9 ordinary actions over all six rounds, including many
rounds with zero actions and an immediate Pass on turn 1;
- raw Round-6 scores before final scoring were only 13, 36, 32, and 20;
- every player scored zero Federation VP and zero research-track/endgame VP;
- endgame resource conversion was 18, 13, 13, and 19 VP, with several wallets at or near the 30-credit,
15-ore, and 15-knowledge caps.
The first bounded hypothesis added an opt-in income-normalized greedy value while preserving the
frozen immediate default. It did not repair productivity: across paired games against greedy and
heuristic its scores remained 45–72, paired margins were `[-1,-25]` and `[-9,-5]`, and most rounds
still passed immediately. It remains an inspectable ablation, not a candidate.
The next diagnosis measured Pass versus the best ordinary macro at the seven curated boundaries.
At the problematic positions Pass led by only 0.25–3.4 actor-oriented value points. A new opt-in
`nonTerminalPassValuePenalty=4` therefore charges the action opportunity cost only to non-terminal
Pass leaf/prior values; zero preserves every frozen arm, and exact terminal utility is never changed.
At budgets 1/2/4/8/16 the new arm selected zero Passes in all 35 curated searches. At the campaign
budget it completed all 56 probe simulations and selected ordinary actions at every probe.
Before full-game results were observed, `testing/strength-campaign.ts` predeclared the isolated
`--pass-opportunity-4-candidate` arm: plain PUCT, eight simulations, scale 16, 75% immediate-greedy
leaf/prior mix, retained visits, Pass opportunity cost 4, Gumbel/transpositions/conversion axes off,
and fresh seed `ai-7-productivity-01`. The historical scale-16/greedy-75 arm was not invoked.
The one-shot campaign completed all four games. Against greedy it scored `76-57` as Xenos and
`72-70` as Hadsch Hallas: margins `[+19,+2]`, mean `+10.5`, record 2-0. It used 39 candidate
selections / 312 simulations / 10,133 expanded edges / 79,912 ms (2,049 ms/selection), with all 61
available promoted-root visits reused. The retained output also records 77 VP and nine ordinary
actions for the candidate as Hadsch Hallas against heuristic, but the compact terminal capture
truncated the other heuristic game before it could be transcribed into this handoff; do not rerun
the arm merely to recover presentation output.
This is a real local productivity improvement, not the AI-7 exit. The retained candidate scores of
72, 76, and 77 remain far below 150–160; even those reported games still contained zero-action middle
rounds, zero Federation VP, zero research-track/endgame VP, and only 7–9 ordinary actions. Relative
wins between weak policies remain insufficient evidence of good play.
## AI-7 owner-labelled opening placement prior
The owner supplied an expert setup rule for the fixed challenge: prefer proximity at distances one,
two, then three to spaceships, the opponent's home colour, Gaia planets, Asteroids, one-step terrain
colours, and a dense set of nearby planets. Spaceship access must reflect the actual board plus its
seeded tech/Federation rewards; the ships are not interchangeable.
Before this label, all four legal Xenos first Mines evaluated to exactly `5.81`; `1A3` was selected
only by stable-key tie-break. `setup-placement.ts` now exposes the six component scores separately,
and the ablatable `setup-placement-opportunity` evaluator term is active only during setup. The
owner-labelled order is locked as `3A0 > 6A4 > 1A3 > 2A11`. Their placement contributions are
`20.20`, `17.85`, `17.35`, and `12.40`; full heuristic values are `26.01`, `23.66`, `23.16`, and
`18.21`. The leading `3A0` separates primarily through adjacent access to Eclipse and access within
three to three Gaia planets plus two Asteroids.
This is a corrected expert decision, not evidence of competent full-game play. The deterministic
heuristic-versus-greedy regression changed from `49-67` / `66-48` to `52-77` / `72-38`: three of
four raw seat scores rose, but the heuristic margins worsened from `[-18,-18]` to `[-25,-34]`.
No strength campaign was run. The coordinate order remains only a regression fixture; policy must
generalize through the reported geometry components rather than memorize the challenge seed.
## AI-7 consolidated strategy doctrine
The owner's expert labels and the BoardGameGeek/official Lost Fleet review are consolidated in
`engine/src/ai/STRATEGY_DOCTRINE.md`. It is now the durable input for strategic AI work and contains:
- general setup geometry, engine-building, tempo, passing, scoring, research, ship, and advanced-tech
principles;
- plan archetypes rather than scripted openings;
- Xenos and Hadsch Hallas modifiers without forcing faction-specific routes;
- evidence/confidence and anti-overfitting rules; and
- the AI-7 translation into plan prerequisites, resource reservations, feasibility, progress, abort
conditions, fallbacks, and inspectable action-value components.
Forum tier disagreements are preserved as evidence that value is contextual. No forum sequence,
coordinate, ship rank, or advanced-tech tier is an unconditional evaluator bonus.
`engine/src/ai/strategy/knowledge.ts` makes the research auditable: 20 sources currently map to 37
deduplicated principles, each with confidence, scope, contrary evidence where relevant, and an
explicit active feature/plan, qualitative fixture, context modifier, documented hypothesis, or
rejected-universal disposition. Its tests reject missing sources/applications and prevent contested
claims from silently becoming unconditional policy.
The first two active plan applications are implemented in `strategy/opening-plans.ts`,
`strategy/research-plan.ts`, and `bots/strategy-plan.ts`. The opening layer compares Academy, PI,
and Mine-spread plans during rounds 1–2. The continuation layer selects and retains a research /
Advanced Tech target during rounds 3–6 from the actual seeded tile, current track levels, green-
Federation readiness, remaining uses, and small faction-context modifiers. It reserves four
knowledge, rewards focused track/tech/Federation-readiness progress, and rejects fixed track orders
or permanent Advanced Tech tier lists. Both layers use inspectable completion, abort, material-
switch, reserve, and productive-Pass reports. The frozen heuristic baseline remains unchanged.
One non-promotional diagnostic game—not a paired campaign—put the plan bot's Xenos against greedy
Hadsch Hallas. It scored `74-61` in 45 committed lines and 54.1 seconds. Xenos took 14 ordinary
actions by round `[7,1,0,0,0,6]`, built Academy 2 plus eight Mines, explored two ships, formed one
Federation for 12 VP, and ended with 74 VP. It still scored zero research-track/endgame VP and took
zero actions in rounds 3–5. This validates the opening-plan mechanism but not strong play or the
AI-7 promotion gate.
The bounded research continuation was then measured once in the same diagnostic matchup after its
source and qualitative contracts were fixed. Xenos won `107-60` in 53 committed lines and 20.6
seconds. Its ordinary actions rose from 14 to 21, with per-round activity `[7,1,5,4,4,0]` instead of
`[7,1,0,0,0,6]`; raw scores after rounds 1–6 were `[4,11,23,42,56,72]`. It formed a Federation,
reached AI 5 / Terraforming 3 / Science 2, took three tech tiles, earned 16 research/endgame VP, and
finished at 107 rather than 74. This is material evidence that persistent midgame goals repair the
diagnosed empty rounds, but 107 remains far below the owner's 150–160 competent benchmark and is
not an AI-7 exit or a campaign result.
The next interaction audit rejected several tempting generalizations instead of promoting them.
Final-scoring track bonuses plus path-progress terms scored 103; a blunt Advanced Tech reachability
discount scored 88; productive-action Pass guards at 8 and 4 scored 105 and 99; and gating a multi-
turn Advanced Tech goal on a Federation formable that exact turn scored 94. The Pass guard and
same-turn Federation gate remain explicit opt-in diagnostics only; their defaults are zero/off. The
scoring and reachability experiments were removed. None replaced the 107-point policy.
The retained evidence-backed change simply carries the successful research plan through round 6.
In the same diagnostic it scored `110-60`, took 22 actions by round `[7,1,5,4,4,1]`, raised raw
Round-6 score from 72 to 76, spent four of seven stranded knowledge on Terraforming 4, and raised
research/endgame VP from 16 to 20. This is the current AI-7 plan default. It is a genuine local gain,
not an exact Round-6 solver, paired campaign, or competent-play claim; 110 remains well below 150–160.
## AI-7 offline economy-plan layer and the engine-building bottleneck (2026-07-15)
The recommended compatible-income / action-budget economic plan is implemented as
`strategy/economy-plan.ts` and wired into `StrategyPlanMacroBot` behind `economyPlanning` (default
`false`, bot schema v3→v4, nullable `economy` report field). It is committed at
`3501c22` on `claude/gaia-phase-1-4-yjb6qo`. The layer scores each macro against the plan's
`roundActionBudget` (the next up-to-three action cost bundles, not one prerequisite) with inspectable
terms: bundle-combination coverage, plan income coverage, cap-waste, stranded-surplus, wasteful-spend,
and a resource-preserving Pass. Default-off reproduces the frozen `110-60` diagnostic exactly.
The retained enabled arm is the multi-action budget: one non-promotional diagnostic (plan bot Xenos
vs greedy Hadsch) scored `110-50` with **Federation VP 0→8** and **stranded ore 15→9** at equal
absolute score — a healthier composition, not a promotion.
Four separate attempts to raise the **absolute** score from the evaluation layer each failed or
regressed, and they triangulate on one cause:
- income-normalized greedy value: `45–72`, no productivity repair (prior AI-7 note);
- plan-relative income coverage: inert — the mine-spread budget is ore-only and ore income is already
adequate, so there is nothing to fix;
- a plan-independent operating-income floor (credits/knowledge) at weight 10: **regressed to `95`**,
still built zero Trading Stations, and hoarded 23 credits;
- a late-game anti-hoard correction (claw back the frozen `resource-stock` over-valuation of held
convertible resources toward their true 3:1 endgame worth): **regressed to `103`**.
Root cause (now well-evidenced, not a guess): the ceiling is **upstream in opening-plan selection**,
not in economy evaluation. For Xenos, `opening-plans.ts` ranks **mine-spread** top (+0.35 modifier), so
the bot builds ~8 mines and **one** non-mine building, ends with **0 Trading Stations / Labs / PI** and
**0 credit income**, and is therefore credit-locked into single-action rounds (observed 1-action rounds
2 and 5). Because the engine is that thin, the bot genuinely has **no higher-scoring late action** than
holding resources for 3:1 conversion — which is exactly why the anti-hoard correction _loses_ points:
it forces marginal spends worth less than the conversion it replaces. A transition evaluator can only
reweight macros the bot already generates and takes; it cannot manufacture the TS/Lab the bot never
adopts. The frozen `resource-stock` weights (ore 0.8, knowledge 1.0) plus `endgame-leftover-conversion`
(0.85) do over-price late held resources, but correcting that is only useful once better scoring
actions exist to spend on.
Three further attempts confirmed the diagnosis and sharpened it from "engine selection" to
"multi-turn planning":
- a cost-gated cheap-Trading-Station opening reward (only the ~3-credit adjacent variant, never the
6-credit isolated one; ablatable): **inert** — the move trace shows the bot already builds one
Trading Station on 1B2, then upgrades that same piece TS→Lab→Academy (MV 17/27/32), so it ends
with **0 Trading Stations and 0 credit income**. It is not failing to build a TS; it consumes its
only one for the research line;
- a "retain credit engine" guard penalising a transition that collapses existing credit income to
~zero (ablatable): **regressed to `102`** and _still_ ended with 0 Trading Stations. Any Lab/Academy
is built by upgrading a Trading Station, so keeping a credit engine while climbing research needs a
**second** income building the bot never builds (and which may need a second cheap opponent-adjacent
spot on this board);
- every combination with the economy layer regressed further (`92–100`).
Sharpened conclusion (owner-confirmed): the frozen `110` line — rush research to the Academy for
Intelligence-5 (~20 research/endgame VP) and take one-off credit from the Eclipse ship action — is a
**robust local optimum on this seed**, and it is defended by a real structural limit, not a missing
weight. `StrategyPlanMacroBot` is **1-ply**: it scores one macro at a time and cannot represent
"upgrade away credit income this round, then restore sensible income next round" — form a
credit-paying Federation, or claim the credit power action first thing next round given bowl-3 power.
That is a sequencing/lookahead requirement. Myopic evaluator terms can only fake it with an
instantaneous penalty/reward, which is why all seven attempts either did nothing or forced a worse
immediate trade. The AI-7 PUCT search is the right mechanism for such lookahead but scores worse
(`43–84`) at feasible budgets. Single-seed relative results are also not valid promotion evidence.
Recommended next AI-7 direction: stop tuning the myopic bot for absolute score on this seed — that
avenue is exhausted. The real feature is an explicit **multi-turn income/restoration plan**: allow an
upgrade that breaks the economy for an action or two only when a concrete restoration path is reserved
(a formable credit-Federation, or sufficient bowl-3 power for the credit power action next round), and
validate it with paired campaigns across multiple seeds, not one diagnostic game. Do **not** add more
economy-evaluation weight terms for absolute score. The committed default-off economy layer (Federation
channel 0→8, ore stranding 15→9 at equal score) stands as the retained deliverable.
## Claude handoff: strategic implementation map
This section is the compact handoff view. `STRATEGY_DOCTRINE.md` remains the canonical strategy
input and `strategy/knowledge.ts` remains the checked 20-source / 37-principle disposition registry.
The labels below distinguish an implemented evaluator signal from an implemented persistent plan;
having a feature does not mean the bot can yet pursue it coherently across turns.
| Strategic area | Implemented now | Still missing / limitation |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Absolute play diagnosis | Exact per-round actions, Pass timing, raw score, VP-channel attribution, final scoring, development, and leftover resources | More faction/seed evidence; 110 is still far below 150–160 |
| Starting placement | Setup-only distances to actual seeded ships/rewards, opponent colour, Gaia, Asteroids, cheap terrain, and planet density; owner fixture `3A0 > 6A4 > 1A3 > 2A11` | Broader owner-labelled boards/factions; never promote the fixture coordinates into policy |
| Opening engine | Persistent Academy, PI, and Mine-spread archetypes; next-building costs, reserves, progress, affordability, completion, abort, and material switching | Research-Lab-flexibility, early-Federation, Gaia/Asteroid, and ship-engine archetypes are not primary opening candidates |
| Research / technology | Persistent rounds 3–6 research target; actual seeded Advanced Tech event, remaining uses, current level, four-knowledge reserve, Standard/Advanced Tech progress, green-Federation readiness, and small Xenos/Hadsch context | Real multi-turn acquisition feasibility, cover choice, opponent contest, and track/action opportunity cost remain approximate |
| Passing / tempo | Opening/research Pass penalty activates only when a measurable plan transition exists | General “productive action” guards at 4/8 scored 99/105 and are opt-in/off; purposeful stalling and booster-order timing are not planned |
| Economy | Resource stock, projected income by resource, uncovered building income, Trading Station adjacency, endgame conversion, and per-plan prerequisite reserves | **Primary next gap:** no compatible-income/action-budget plan; the retained game ends at 15 ore / 4 credits, so resource complementarity and cap waste are not controlled |
| Federation | Current token/green-token value, structure-value progress, legal engine-enumerated Federation macros, Federation-readiness reward inside research planning | No persistent Federation payoff/geometry plan; exact/custom geometry remains AI-8/out of scope; same-turn feasibility gate scored 94 and is off |
| Gaia / Asteroids | Setup access, Gaia pipeline, Asteroid/Gaia counts, legal actions, evaluator scoring, and final-score projection | No persistent Gaia/Asteroid expansion plan with former/QIC/power/build reserves, expected uses, timing, abort, and fallback |
| Lost Fleet ships | Actual seeded action board, tech/Federation reward, setup access, explored-ship value, action availability, and legal repeated use; the 110 game explores and uses two ships | No retained ship-engine/synergy plan, contest forecast, or explicit “two deep versus three shallow” expected-use model |
| Round/final scoring | Current/future round-tile potential, exact current final-scoring projection, and full-game VP attribution | No persistent engine-to-scoring conversion plan; attempted track/final-scoring coupling scored 103 and was removed |
| Power / leech | Power-bowl capacity, shared actions, exact marginal charge/VP report, and resource valuation | No multi-round bowl-3 budget or contest schedule; do not force depletion before Pass |
| Faction identity | General plans plus small Xenos and Hadsch Hallas modifiers; no coordinate scripts | Only Xenos has the retained full-game strategy diagnostic; Hadsch remains a very weak opponent and faction-specific feasibility needs broader validation |
| Search | Deterministic committed-macro PUCT/Gumbel, reuse, diagnostics, strength harnesses, and frozen measured arms | Strategy-plan bot is not a promoted search champion; scale-16/greedy-75 and Pass-opportunity-4 must not be rerun or retuned |
| Exact endgame | Round-6 research plan now avoids one observed immediate Pass | Exact Round-6 solving is AI-8 and must not start yet |
### Retained defaults and rejected ablations
- `StrategyPlanMacroBot` with default options is the current 110-point policy.
- `productivePassPenalty` defaults to `0`; values 4 and 8 are retained only for inspection.
- `federationFeasibilityGate` defaults to `false`; the current-turn gate is not a multi-turn
feasibility model.
- Final-scoring track bonuses and the blunt Advanced Tech reachability discount were removed.
- The frozen heuristic, greedy baseline, shared engine, production imports, and hosted code remain
unchanged by the plan layer.
### Recommended next bounded AI-7 task
Implement one inspectable **compatible-income/action-budget economic plan**. It should forecast the
cost bundles of the plan's next meaningful actions, value credit/ore/knowledge/QIC combinations
rather than raw stock independently, detect cap waste and stranded surplus, protect prerequisites,
and allow Pass when only wasteful conversions or negative-value spending remain. Lock qualitative
fixtures before one non-promotional diagnostic. Do not begin with another weight sweep, forced-Pass
rule, coordinate label, paired campaign, or AI-8 Federation/endgame solver.
Claude should start with `AGENTS.md`, this file, `STRATEGY_DOCTRINE.md`,
`strategy/knowledge.ts`, `strategy/opening-plans.ts`, `strategy/research-plan.ts`,
`bots/strategy-plan.ts`, and their focused specs. Continue from the published AI-7 checkpoint on
`claude/gaia-phase-1-4-yjb6qo`; preserve any later dirty worktree and do not switch, pull, commit,
push, deploy, or touch `master` unless the owner supplies new authority.
## AI-7 non-goals
- No alpha-beta or exact late-game solver.
- No federation solver, Round-6 solver, opening book, neural features/models/training, Web Worker,
viewer integration, backend/Supabase work, ranked authority, or production flag.
- No separate learned human/opponent model.
- No shared engine legality, serialization, hydration, replay, or availability changes.
## AI-7 verification record
- Frozen focused suite: 12/12 passing (reference core plus committed-engine integration/smoke).
- Development-only directly affected evaluator/bot suite: 12/12 passing.
- Complete three-glob engine suite: 710 passing / 4 pending in 14 minutes. The first exact command
was externally terminated after 182 seconds with Windows status `0x40010004` and no Mocha failure;
the unchanged recovery run completed successfully.
- Final `npx tsc --noEmit` and focused changed-file ESLint passed. Diff/whitespace/newline and
changed-path/production-import isolation audits were clean.
- No complete historical AI suite, duplicate campaign, or ad hoc digest script was run after source
freeze. Documentation-only handoff edits followed the completed source gates.
- Focused calibration verification: 13/13 search tests; complete engine 711 passing / 4 pending in
13 minutes; final TypeScript and changed-AI-file ESLint clean. No strength campaign was run.
- Scale/evaluator source freeze: 16/16 focused search/integration tests; complete engine 714 passing /
4 pending in 13 minutes; TypeScript and changed-AI-file ESLint clean; diff/whitespace, changed-path,
and production-import isolation clean. The predeclared campaign then completed without source
changes; only documentation was updated afterward.
- Productivity source freeze: 16/16 focused bot/search tests; complete engine 717 passing / 4 pending
in 13 minutes; TypeScript, focused changed-file ESLint, and diff/whitespace checks clean. The
predeclared Pass-opportunity campaign then ran exactly once without source changes; only
documentation was updated afterward.
- Strategy corpus/opening-plan source check: 9/9 focused traceability and behavioral tests; 18/18
with the directly affected evaluator suite; `npx tsc --noEmit`; focused ESLint clean. One
single-game productivity diagnostic completed; no
paired campaign or measured-arm rerun was performed.
- Research/tempo continuation source check: 11/11 focused research/tempo tests; `npx tsc --noEmit`;
focused ESLint clean. Development diagnostics recorded and rejected every weaker default before
retaining the 110-point round-6 continuation. No paired campaign and no measured
scale-16/greedy-75 or Pass-opportunity-4 rerun was performed.
## AI-7 autonomous execution authority
Offline AI-7 work no longer requires an owner checkpoint between calibration and strength
measurement. A fresh session is authorized to:
1. diagnose and change offline search, prior, evaluator, reuse, diagnostics, tests, and AI docs under
`engine/src/ai/` while preserving shared-engine and production isolation;
2. use focused traces and curated positions to select one falsifiable candidate;
3. predeclare its fixed campaign configuration in the canonical handoff or checked-in campaign
source before seeing the paired results;
4. freeze and verify source, then run that one comparable paired campaign autonomously against both
greedy and heuristic with common seeds, fixed budgets, both faction assignments, and both raw
final scores for every game; and
5. record an unsuccessful result honestly and begin another bounded AI-7 hypothesis without asking
the owner, provided it changes source/config for an evidence-backed reason and does not rerun or
cherry-pick seeds from the failed campaign.
This is continuing authorization, not a request for repeated confirmations. Stop only when work
would cross into AI-8, shared-engine/viewer/backend/production changes, commit/push/deploy, private or
external data, or another material scope expansion. Full-suite and campaign cadence still follows
the source-freeze/no-duplicate rules in `PROGRESS.md`.
## Next autonomous AI-7 step
- Do not start AI-8. The Pass-opportunity arm improved ordinary-turn activity and went 2-0 against
greedy, but its retained 72–77 VP scores are still grossly inadequate absolute play and the formal
statistically clear gate is not established.
- Do not campaign the measured 50/50 prior: it changed no curated choice.
- Do not rerun or retune the measured scale-16/greedy-75 arm, and do not rerun the
Pass-opportunity-4 campaign merely to recover its truncated console presentation.
- The Academy/PI/Mine-spread opening and rounds 3–6 research/Advanced Tech continuation are locally
validated. Do not promote from the `110-60` diagnostic alone.
- Do not enable the productive-Pass or same-turn Federation gates by default: their measured scores
were 99/105 and 94. Do not restore the removed scoring/reachability experiments.
- The next bounded hypothesis should address the current 15-ore/4-credit imbalance through a real
economic plan with compatible income and action budgets, not forced spending. Federation payoff
and Gaia/Asteroid goals remain relevant, but existing ship use was already active and should not
receive a flat bonus.
- After one such evidence-backed interaction improves a qualitative trace, consider one fresh,
predeclared paired campaign. Do not rerun either previously measured campaign arm.
- Primary risks: the improved candidate still scored only 110 and took only one action in round 6;
Hadsch Hallas remained a 60-point weak opponent; Federation VP attribution was zero despite taking
a Federation reward; one deterministic diagnostic is not
statistically clear; exact macro expansion costs roughly 2 seconds per measured selection; and
the current DAG shares states correctly but did not show practical benefit.
## Handoff discipline
At completion, update this file with AI-7 status, measurements, final counts, risks, and the next
phase pointer. Update the AI README only for new stable APIs; append to the plan decision log only
for actual decisions/results; keep the PROGRESS current-task entry to a short link here. Do not
create another long phase handoff unless the owner explicitly requests an archival evidence file.
The final response should contain only: changed files, search design, paired measurements, final
verification summary, production-isolation result, remaining risks, exact git status, and the next
phase stop. Link here for inherited hashes/details instead of repeating this document verbatim.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,488 @@
# Lost Fleet AI — Phase 1.4 handoff
> **Status (2026-07-14): PHASE 1.4 COMPLETE.** Phases 0, 1.1, 1.2, 1.3, and 1.4 are done; the
> measured Phase 1.4 results are in the "Phase 1.4 result" section below. The next authorized
> slice is AI-6 (greedy/heuristic bots + evaluator, plan §6) and requires fresh owner approval.
> Do not start search, evaluation, federation solving, neural features, training, viewer
> integration, or backend work without that approval. The original Phase 1.4 contract below is
> retained unchanged as the record of what this phase had to satisfy.
## Phase 1.4 result (2026-07-14)
Implemented on `claude/gaia-phase-1-4-yjb6qo` (built from `agent/phase-1-3-resource-planner`
commit `8b9ee84b`), offline-only under `engine/src/ai/` and `engine/scripts/ai/`.
### Delivered
- `engine/src/ai/actions/turn-builder.ts` + `turn-builder.spec.ts` (12 focused tests): committed-
turn macro construction. Every macro is built and validated by replaying its complete line
against a fresh clone of the committed source with the production commit rule (one `move()`,
commit only on `newTurn` — the same rule as `viewer/src/hosted/host.ts`, `self-contained.ts`,
and the fuzzer). Macro keys (`macro-v1:` + SHA-256) hash the semantic choice only: source
canonical hash, actor, Phase 1.3 conversion-destination wallet key (null for no prefix), Phase
1.2 main-candidate key, chosen candidate keys at meaningful follow-up decisions in order, and
the retained AfterMove conversion destination key. Forced one-choice follow-ups stay on the
spine, never branch, and never enter the key; the conversion-integrated and conversion-free
construction routes produce identical keys for the shared macros, and equivalent conversion
prefixes cannot duplicate macros because Phase 1.3 already canonicalizes one plan per
destination wallet. `DeadEnd` follow-ups reject the line before exposure
(`rejected[].reason === "dead-end-follow-up"`); committed leech choices are separate subsequent
edges built from the committed leech state. Setup, income, Gaia, and leech decisions flow
through the same generic committed-decision path.
- `engine/src/ai/testing/corpus.ts` + `corpus.spec.ts` (3 focused tests) and
`engine/scripts/ai/corpus-campaign.ts`: macro-sampled full games from the locked prefix
(host-style commit chain) and the corpus campaign.
- Additive, output-preserving extensions to earlier phases (verified by the preserved suites):
- `canonical-state.ts` projects `federationCache.custom` through the engine's own truthy
coercion (`!!`), byte-identical for every live boolean and making hydrated mid-game caches
hashable instead of a projection crash;
- `resources/planner.ts` gained `planAfterActionConversionsForLine` (exact-prefix variant of
`planAfterActionConversions`, shared implementation) and drops the engine's custom-only
FormFederation fallback at conversion-reached wallets (custom federations are out of scope; see
the finding below).
### Locked branch statistics (before/after conversion integration, locked Round-1 state)
- Before: 52 committed macros over 32 root main candidates, zero rejections, macro
key/destination digest `972a1e9b062ebcda5a96e2242039bbc29eee83934c9eb41e175a493bb1009096`.
- After (seed level, from the locked Phase 1.3 result): 45 candidate frontiers; 130,532
(conversion prefix, main candidate) seed pairs; 130,500 with a non-empty prefix; the 32
empty-prefix seeds are exactly the root-affordable mains; per-candidate prefix counts 5 min /
2,134 median / 9,985 max. Emitting all ~130k lines is a measured multi-hour offline job (each
line is replay-validated), so the focused suite locks the exact seed-pair counts and emits
complete integrated macro sets on smaller wallets; an integrated turn on a real mid-game state
is exercised end-to-end in the corpus spec.
### Corpus campaign (locked challenge, macro-sampled games, integration off)
18 complete games, every game reached `EndGame`; 1,039 committed corpus states; per state:
canonical hash + serialize/parse hydration parity, typed expansion with unique sorted macro keys,
every emitted macro fresh-clone validated, sampled macro re-applied host-style with destination
hash + next-actor equality, constructor replay of the accumulated history hash-checked (all 1,039)
with full macro parity on 155 deep-check states. 106 committed leech-decision states; rounds 0–6
and phases setupBuilding/setupBooster/roundMove/roundLeech covered; 20,834 macros built (1–400
per state); 132 rejected lines, all `dead-end-follow-up`; zero deduplications; wall time 653 s
under load. ChooseIncome and PlaceLostPlanet never occur naturally in these trajectories and have
explicit synthetic coverage in the focused suite (as in Phase 1.2); BrainStone/PISwap/Tinkering
are outside the locked Xenos/Hadsch-Hallas boundary.
### Engine-reality findings (surfaced, not concealed; no shared-engine change)
1. **Custom-federation fallback in real play (deliberately excluded).** Macro-sampled Xenos/HH
games reach states where the engine offers a federation only through its custom (hand-picked
hex set) fallback (`federations: []`, `federationCache.custom`), which Phase 1.2 rejects by
contract. Per owner decision (2026-07-14) custom federations are out of scope: the AI forms
only the engine's enumerated satellite-path federations, so when only the custom fallback is
offered it forms no federation that turn. The macro layer drops the un-enumerable offer and
records the dropped tiles in `excludedCustomFederationTiles` (11 of the 1,039 corpus states) so
the exclusion is audited, not silent. A custom-only offer means the heuristic found no
satellite-path federation at that wallet, so nothing enumerable is lost. This is not a gap
awaiting a later custom-federation feature.
2. **federationCache replay divergence (base-003 class).** `Player.toJSON()` drops the cache's
boolean `custom` flag while current engine behavior reads it, so a live `custom: true` state
and its serialized counterpart are genuinely different states; Phase 1.1 hashes the cache on
purpose. 39 of 1,039 corpus states show replay-path hash differences, every one proven by a
cache-masked byte comparison to be confined to this class and counted
(`federationCacheHashDivergences`); macro parity on those states is checked on
hash-independent semantic content and holds. Any divergence outside the masked cache fails the
campaign. The shared-engine fix remains a Phase 3/maintenance-window item.
### Verification results (2026-07-14)
- Phase 1.4 focused: `turn-builder.spec.ts` 12 passing; `corpus.spec.ts` 3 passing.
- Preserved focused suites: Phase 1.3 `planner.spec.ts` 15, Phase 1.2 `expand.spec.ts` 10, Phase
1.1 `canonical-state.spec.ts` 12, Phase 0 `challenge-manifest.spec.ts` 3 + `benchmark.spec.ts` 1
= 41 passing (unchanged), confirming the Phase 1.2 62-candidate digest `a28eb3…04d9`, the Phase
1.3 locked result 36,159 / 9,985 / 45 / depth 30 digest `b4e266…850`, and the Phase 1.1 corpus
hashes all still hold after the additive `canonical-state.ts`/`planner.ts`/`types.ts` edits.
- Complete offline AI suite (`src/ai/**/*.spec.ts`): 56 passing (41 + 12 + 3).
- Complete engine suite (`src/**/*.spec.ts` `src/*.spec.ts` `*.spec.ts`): 686 passing, 4 pending
(671 + 15 new; the 4 pending are the pre-existing engine pendings).
- `npx tsc --noEmit`: clean. Focused ESLint on every changed/added TS file: clean.
- Fresh Phase 0 manifest: byte-identical to `challenge-manifest.v1.json` (81,991 bytes, byte SHA
`3c872d…449e`), semantic SHA `ce3bdd…51e`, engine version 4.8.51 — all unchanged.
- `git diff --check`: clean. Final-newline/trailing-whitespace checks on new files: clean.
- Production isolation: no `engine/index.ts`, viewer, or Supabase path imports `engine/src/ai/`;
every new AI file imports only engine internals and other `engine/src/ai/` modules.
### Measured planning cost (descriptive, no caps added)
Exhaustive conversion planning is wallet-dependent: 0.01–12 s on typical mid-game wallets, ~80 s
on the pristine locked Round-1 wallet, 738 s on a measured power-rich Round-6 state, and the
pristine-wallet AfterMove axis exceeds practical wall-clock entirely (one complete fixpoint per
distinct post-main wallet). `conversionIntegration` and `afterConversionIntegration` therefore
stay separately selectable — exact and uncapped whenever enabled — and every statistic states
which axes ran. Scheduling which turns a sampled player converts on is a play-policy choice;
no depth cap, timeout, weight, beam, or heuristic prune was added anywhere.
### Remaining risks carried to later phases (nothing open blocks Phase 1.4)
| # | Item | Owner phase | Notes |
| --- | ------------------------------------------------------------------------------ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | Custom (hand-picked hex set) federations | none — descoped by owner (2026-07-14) | The AI forms only engine-enumerated satellite-path federations; the custom-only fallback is deliberately excluded and recorded (`excludedCustomFederationTiles`), not a gap. A Phase 3 federation planner, if built, would still select among engine-enumerated federations, not construct custom hex sets — confirm scope when Phase 3 starts. |
| 2 | Shared-engine fix for the base-003 `federationCache.custom` serialization drop | Phase 3 / maintenance window | Requires the §"maintenance-window checklist" in `engine/src/ai/README.md`; not authorized during the live-game freeze. Phase 1.4 counts and mask-verifies the divergence rather than hiding it. |
| 3 | Brainstone / PISwap / Tinkering follow-up families | later, if the challenge factions change | Outside the locked Xenos/Hadsch-Hallas boundary, so not exercised; the builder already routes them through the same generic path if they ever appear. |
| 4 | AfterMove-integration wall-clock on resource-rich wallets | AI-6/AI-7 search budgeting | Split onto the `afterConversionIntegration` axis; the eventual search layer decides when to pay for it. No cap was added. |
| 5 | Phase 1.3 regression tests recommended by the #68 race-condition audit | still open (pre-existing) | Unrelated to Phase 1.4; noted so it is not lost. |
## Production boundary
- Real players may have active hosted games.
- `master` is the Vercel production branch; every push to it deploys.
- Keep Phase 1.4 under `engine/src/ai/`, offline, and unreachable from production imports/exports.
- Do not modify shared engine rules, serialization, hydration, replay, viewer, Supabase, deployment,
feature flags, hosted data, or production entry points.
- Do not commit, push, deploy, migrate, or change flags without fresh owner approval.
- Do not use subagents unless the owner separately authorizes them.
## Start and read order
Run `git status --short --branch`, `git fetch origin`, `git rev-parse HEAD`, and
`git rev-parse origin/master` before editing. Work from the latest
`origin/agent/phase-1-3-resource-planner`; do not switch to or push `master`.
Read completely, in this order:
1. `AGENTS.md`.
2. `docs/lost-fleet/PROGRESS.md`, especially Working agreements and Testing.
3. `docs/lost-fleet/RULES_CLARIFICATIONS.md`.
4. `docs/lost-fleet/COMPONENTS.md`.
5. `docs/lost-fleet/AI_IMPLEMENTATION_PLAN.md`, especially §§1, 5.4, 14, 15, and 16.
6. `engine/src/ai/README.md`.
7. Every file under `engine/src/ai/`.
8. The production committed-turn/replay paths already cited by the plan: the self-contained host,
hosted move application, fuzzer driver, leech/forced follow-up handling, and end-turn flow.
Preserve all existing work. Never reset, clean, stash, checkout, revert, or overwrite owner changes.
## Completed foundation
### Phase 0
- Locked challenge manifest and reproducible offline benchmark foundation.
- Engine version: `4.8.51`.
- Manifest semantic SHA-256:
`ce3bdd7322860484dfae771320b9f12967d0677b908f91cdc682d9c4427bf51e`.
- Fresh normalized manifest bytes: 81,991 bytes with SHA-256
`3c872d121f71447842e027a49de75e57c22e6919f2ac152d0cdf4f8a57f8449e`.
### Phase 1.1
- Canonical future-relevant state projection and stable state hash.
- Constructor replay, `Engine.slowMotion`, and hydration parity are locked.
- Canonical focused suite: 12 passing.
### Phase 1.2
- Typed atomic decision expansion with stable candidate keys and executable fragments.
- Locked Round-1 candidate count: 62.
- Candidate digest:
`a28eb3d03e2b51e1bea28170b92f5e99991f41c76b1b1c8a2193a97a0ee704d9`.
- Focused suite: 10 passing.
### Phase 1.3 behavior
- Exhaustive semantic conversion-state fixpoint with no depth or time cap.
- Canonical unit actions for ranged `Spend`, burn aliases, and commutative/equivalent states.
- Lossy-cycle detection and context-aware, weight-free Pareto dominance.
- Explicit brainstone, bowls, Gaia tokens, Gaiaformers, token modifiers, and faction conversions.
- Phase 1.2 candidate affordability and nondominated post-payment frontiers.
- Separate `AfterMove` bowl-opening and safe-deferral handling.
- Stable keys, diagnostics, and executable conversion fragments.
## Phase 1.3 performance hardening
### Measured root cause
The first instrumented locked Round-1 run was still incomplete after 120.038 seconds. It had not
started candidate/payment construction. At that cutoff it had performed 11,131,245 dominance
comparisons. The old predicate serialized exact-context JSON twice per comparison: 22,262,490
serializations by the cutoff. Repeated full componentwise frontier scans, amplified by stable JSON
inside each comparison, were the primary bottleneck. Canonical plan/state keys, cycle graph
reconstruction, path retention, and candidate construction were not the initial blocker.
Baseline cutoff counters:
| Counter | Value at 120.038s |
| -------------------------------- | ----------------: |
| Generated states | 9,742 |
| Accepted states | 3,317 |
| Active/max frontier | 1,528 |
| Transitions considered | 14,150 |
| Exact-state merges | 5,662 |
| Pareto prunes | 2,553 |
| Lossy-cycle prunes | 0 |
| Dominance comparisons | 11,131,245 |
| State-key calls | 19,485 |
| Plan-key computations | 3,317 |
| Cycle graph reconstructions | 9,742 |
| Maximum depth | 8 |
| Candidate states/payment results | 0 / 0 |
### Semantics-preserving optimization
- Cache canonical state keys per immutable projected-state object.
- Cache exact-context JSON and all ten monotone dominance dimensions per immutable state.
- Replace `queue.shift()` with a monotone cursor.
- Use deterministic exact-context dominance buckets and necessary-condition resource indexes before
the complete strict ten-dimensional predicate. No bucket alone can prune a state.
- Preserve insertion order for deterministic diagnostics.
- Select the lexicographically smallest duplicate payment fragment in one pass.
- For payments that subtract only credits, ore, knowledge, QIC, and victory points, skip a redundant
second Pareto pass: translating a subset of an already nondominated frontier by the same vector
cannot create a new dominance relation. Nonlinear payments still use the complete index.
- Add deterministic counters, descriptive phase timings, and an optional work-count progress
callback. No elapsed time participates in planning behavior.
The optimization does not add a depth cap, timeout, resource weight, beam, heuristic prune, or
missing semantic dimension. Every discarded reachability/payment state still has either an exact
semantic merge or a proven full componentwise dominator.
### Completed locked-state result
Final representative run:
| Result/counter | Value |
| --------------------------- | --------: |
| Total elapsed | 46.113s |
| Setup | 0.014s |
| Reachability | 27.207s |
| Result assembly | 1.104s |
| Candidate construction | 14.236s |
| Payment frontiers | 3.551s |
| Generated states | 151,249 |
| Accepted/reachable states | 36,159 |
| Active/max frontier | 9,985 |
| Transitions considered | 254,360 |
| Exact-state merges | 85,126 |
| Pareto prunes | 56,139 |
| Lossy-cycle prunes | 0 |
| Dominance comparisons | 1,091,376 |
| Exact-context computations | 170,652 |
| State-key computations | 281,782 |
| Plan-key computations | 36,159 |
| Cycle graph reconstructions | 151,249 |
| Candidate states expanded | 9,985 |
| Payment results generated | 130,532 |
| Candidate frontiers | 45 |
| Maximum conversion depth | 30 |
Diagnostics: 85,126 exact merges, 56,139 Pareto prunes, zero lossy-cycle prunes, 111 canonical
aliases, and no unavailable effects. Stable result digest:
`b4e266ef95ca8cc34cfd1cde4380a782ff01f4802a077d49ac9686924e222850`.
Elapsed time is descriptive and machine-dependent. The regression locks completion, counters that
describe semantic work, keys, and replay parity; it deliberately has no fragile time assertion.
### Verification already passed
- Phase 1.3 focused: 15 passing.
- Phase 1.2 focused: 10 passing.
- Complete offline AI: 41 passing.
- Phase 1.1 canonical: 12 passing.
- Phase 0 manifest: 3 passing.
- Complete engine: 671 passing, 4 pending.
- `npx tsc --noEmit`.
- Focused ESLint for all modified TypeScript files.
- Fresh Phase 0 byte/golden and both SHA checks.
- Explicit Phase 1.2 base/constructor/slow-motion/hydration 62-candidate digest and fragment check.
- Every representative conversion-fragment shape applies to a clone and reaches its projected state.
- `git diff --check`, final-newline/whitespace checks, and production-isolation audits.
- No production import/export references `engine/src/ai/`.
## Phase 1.4 objective
Build complete committed-turn macros from the last committed snapshot. A macro may contain:
1. a Phase 1.3 conversion plan;
2. exactly one Phase 1.2 main-action candidate;
3. every forced follow-up needed to make the action executable;
4. meaningful after-action choices that cannot safely be deferred;
5. `end` when required; and
6. a committed leech choice as a separate subsequent decision edge when control passes through
leech before the next committed turn.
Do not serialize or cache arbitrary transient engine states. Construct and validate each complete
line by replaying from the last committed snapshot, matching the production host and fuzzer flow.
Forced one-choice follow-ups must not become policy branches. Preserve real choices such as tech
tile, covered tile, research advance, federation token, artifact, booster, Gaia target, Lost Fleet
special choices, and leech. Stable macro keys must encode the complete semantic choice, not timing,
object identity, or incidental command order.
## Required Phase 1.4 evidence
- Every emitted macro applies to a fresh clone and ends at a committed state, or is rejected before
exposure.
- No `DeadEnd` macro is exposed.
- Constructor replay, `Engine.slowMotion`, hydration, and host-style replay produce the same macro
keys and committed destination hashes.
- Actor transition is recorded correctly, including pass order and leech interruption.
- Equivalent conversion prefixes do not create duplicate macros.
- Phase 1.2 candidate keys/fragments/count/digest and Phase 1.3 locked digest/counters remain exact.
- Randomly sampled macro play reaches `EndGame` without the fuzzer's historical conversion cap.
- At least 1,000 diverse committed corpus states pass hash/legal/apply/replay properties.
- All locked-setup command/follow-up types have explicit coverage.
- Branch statistics are measured before and after conversion-plan integration.
- No unsupported custom-federation state is silently treated as “no federation.”
- No shared production-engine behavior or production import/export changes.
If the 1,000-state campaign exposes an engine-rule discrepancy, stop and report it. Phase 1.4 does
not authorize changing shared rules.
## Later runtime decision — document only, do not implement in Phase 1.4
The owner selected a maximum-strength local AI for the private challenge:
- Same model, opening book, and fixed high simulation count on every supported device.
- No time-based early exit and no automatic low-device search/model downgrade.
- Faster hardware returns the same work sooner; it does not receive a stronger configured opponent.
- Devices that cannot run the full configuration are declared unsupported rather than silently
receiving weaker play.
- Primary target devices are the owner's Ryzen 5 5600G / RTX 3060 12GB / 16GB Windows desktop and
iPhone 16 Pro Max. Actual support must be benchmarked; phone support must not weaken desktop AI.
- The later Web Worker UI must show real completed/target simulations, evaluated positions, elapsed
time, a moving ETA range, and a heartbeat/last-update status. It must detect background suspension
and distinguish it from a dead worker. A supported screen-wake request may be offered.
- Server-authoritative AI remains an optional later choice only if ranked anti-cheat or identical
server execution is desired. It is not required for the private local challenge.
“No device-driven limit” does not mean infinite search: an infinite search never moves. The final
fixed workload must be selected from strength-versus-compute measurements and diminishing returns,
not from a requirement to support low-end devices.
## Verification commands for Phase 1.4
Run from `engine/` unless noted:
```powershell
# New Phase 1.4 focused suite, then preserved focused suites
npx mocha -r ts-node/register --reporter min '<new Phase 1.4 spec paths>'
npx mocha -r ts-node/register --reporter min 'src/ai/resources/planner.spec.ts'
npx mocha -r ts-node/register --reporter min 'src/ai/actions/expand.spec.ts'
npx mocha -r ts-node/register --reporter min 'src/ai/canonical-state.spec.ts'
# All offline AI and full engine
npx mocha -r ts-node/register --reporter min 'src/ai/**/*.spec.ts'
npx mocha -r ts-node/register --reporter min 'src/**/*.spec.ts' 'src/*.spec.ts' '*.spec.ts'
npx tsc --noEmit
```
Also run focused ESLint on every changed TypeScript file, a fresh Phase 0 manifest byte/golden/SHA
comparison, the explicit Phase 1.2 62-candidate replay/hydration digest check, the Phase 1.3 locked
completion/digest regression, `git diff --check`, untracked whitespace/final-newline checks, final
status, and changed-path plus production-import/export isolation audits.
## Stop conditions
Stop for owner guidance if Phase 1.4 appears to require:
- changing shared engine semantics;
- transient-state serialization or production hydration changes;
- unsafe conversion/macro dominance or dropping executable plans/diagnostics;
- a depth cap, timeout, weighted heuristic, or beam;
- changing Phase 0/1.1/1.2/1.3 outputs;
- viewer, Supabase, deployment, production export, feature-flag, or live-game changes; or
- beginning search, evaluation, federation solving, neural/training, or UI work.
## Required handoff
Report exact changed files, macro representation and completeness argument, corpus composition and
branch statistics, every verification count/hash, production-isolation evidence, remaining risks,
PASS/FAIL for every Phase 1.4/AI-5 criterion, and exact `git status`. Stop for owner review.
## Ready-to-paste Claude Code prompt (HISTORICAL — Phase 1.4 is complete; do not reuse)
```text
You are taking over Phase 1.4 of the Gaia Lost Fleet AI project in:
C:\Users\okimm\Documents\Projects\gaia-lost-fleet
Work from the latest origin/agent/phase-1-3-resource-planner. First run:
git status --short --branch
git fetch origin
git rev-parse HEAD
git rev-parse origin/agent/phase-1-3-resource-planner
git rev-parse origin/master
The starting tree should be clean and HEAD should match the remote agent branch. Do not work on or
push master: it is the Vercel production branch and real hosted games may be active.
Read completely before editing:
1. AGENTS.md
2. docs/lost-fleet/PROGRESS.md, especially Working agreements and Testing
3. docs/lost-fleet/RULES_CLARIFICATIONS.md
4. docs/lost-fleet/COMPONENTS.md
5. docs/lost-fleet/AI_IMPLEMENTATION_PLAN.md, especially §§1, 5.4, 14, 15, and 16
6. docs/lost-fleet/AI_PHASE_1_4_HANDOFF.md
7. engine/src/ai/README.md
8. every file under engine/src/ai/
9. the production committed-turn/replay, forced-follow-up, leech, end-turn, host, and fuzzer paths
cited by the plan
Implement Phase 1.4 only: committed-turn macro construction plus the 1,000-state corpus campaign.
Do not start heuristic evaluation, MCTS/search, federation solving, opening books, neural features,
training, Web Workers/viewer integration, Supabase/backend work, or any later phase. Do not use
subagents unless the owner separately authorizes them.
Keep all changes offline under engine/src/ai/ and unreachable from production runtime paths. Do not
modify shared engine rules, serialization, hydration, replay semantics, viewer code, Supabase,
deployment configuration, production exports/entry points, hosted data, or feature flags. Do not
commit, push, deploy, migrate, or change flags without fresh owner approval.
Build each complete macro from the last committed snapshot and validate it by replay. Combine an
optional Phase 1.3 conversion plan, one Phase 1.2 main action, every required forced follow-up,
meaningful non-deferrable after-action choices, and EndTurn when required. Treat an intervening
committed leech choice as a separate subsequent edge. Forced one-choice decisions must not become
policy branches; meaningful choices must remain distinct. Never serialize arbitrary transient
engine states and never expose a DeadEnd or non-committed macro.
Preserve exactly:
- engine version 4.8.51
- Phase 0 semantic SHA:
ce3bdd7322860484dfae771320b9f12967d0677b908f91cdc682d9c4427bf51e
- Phase 1.1 focused count: 12
- Phase 1.2 candidate count: 62
- Phase 1.2 digest:
a28eb3d03e2b51e1bea28170b92f5e99991f41c76b1b1c8a2193a97a0ee704d9
- Phase 1.3 focused count: 15
- Phase 1.3 locked result: 36,159 reachable states, 9,985 frontier states, 45 candidate
frontiers, maximum conversion depth 30
- Phase 1.3 digest:
b4e266ef95ca8cc34cfd1cde4380a782ff01f4802a077d49ac9686924e222850
- current complete offline AI count: 41
- current complete engine result: 671 passing, 4 pending
Required Phase 1.4 gates:
- every emitted macro applies to a fresh clone and ends committed;
- no DeadEnd macro is exposed;
- stable macro keys and committed destination hashes match constructor replay, Engine.slowMotion,
hydration, and host-style replay;
- actor transition, pass order, and leech interruption are correct;
- equivalent conversion prefixes do not duplicate macros;
- sampled macro play reaches EndGame without a conversion cap;
- at least 1,000 diverse committed corpus states pass hash/legal/apply/replay properties;
- locked command/follow-up types have explicit coverage;
- branch statistics before/after conversion integration are reported;
- unsupported custom federations are never silently treated as no federation;
- no production behavior/import/export changes.
Do not use arbitrary depth/sequence caps, algorithmic timeouts, weighted resource scores, heuristic
beams, unsafe dominance, or dropped diagnostics/executable plans. If Phase 1.4 appears to require a
shared-engine correction or changes any earlier phase output, stop and ask the owner.
Run the focused Phase 1.4 suite, preserved Phase 1.3/1.2/1.1/Phase 0 checks, complete offline AI,
the exact complete engine command from the handoff, npx tsc --noEmit, focused ESLint for every
changed TypeScript file, fresh Phase 0 byte/golden/SHA checks, explicit Phase 1.2 replay/hydration
digest, Phase 1.3 locked completion/digest, git diff --check, final-newline/whitespace checks, final
status, and changed-path plus production-import/export isolation audits.
Update the AI documentation with measured Phase 1.4 results. Report exact changed files, macro
representation and completeness argument, corpus composition and branch statistics, every test
count/hash, production-isolation evidence, remaining risks, PASS/FAIL for every AI-5 criterion, and
exact git status. Then stop for owner review; do not begin Phase 2.
```

View file

@ -0,0 +1,342 @@
# AI Strategy Notes — human play knowledge to bake into the AI
> **Purpose.** A structured intake for _your_ Gaia Project strategy knowledge. You fill it in; a
> developer translates each entry into code in `engine/src/ai/`. See `AI_CHALLENGE_PLAN.md` §7.
>
> **Status:** template — fill in later. Examples are marked _(example — replace)_.
---
## 0. How to write tips so they actually help (read first)
The model **never reads this file as text** — it is not an LLM, there are no tokens. Instead, each
tip you write is translated by a developer into one of a few code forms, and then **training tunes
how much it matters**. So write tips accordingly:
- **Prefer "what to look at" over "always do X".** "Being closer than the opponent to an advanced
tech tile is valuable" (a _feature_) is far better than "always rush advanced tech" (a brittle
_rule_). Features get a learnable weight; if you're wrong, self-play drives it to zero. Hard rules
bake in your blind spots and cap the AI.
- **State the conditions.** A tip that's only true in some situations should say when. "Prefer the
navigation booster **in early rounds on a spread-out map**" beats "navigation booster is good".
- **It's OK to be uncertain or wrong.** Mark confidence; low-confidence tips are still useful as
priors and get ablation-tested (run the AI with the tip on vs off; keep it only if it helps).
- **Note contested/tempo tips specially** (§8) — those feed the race/contention feature.
### Two special cases: openings and "must-not-do" moves
- **Opening moves ("moves to yearn for").** Because the seed/factions/turn order are fixed, the
opening is _solved offline_ by the opening book (plan §6.1), not guessed. So write opening tips as
**PRIOR** (move-ordering hints): they make the book's search converge faster and cover off-book
positions, but **the book overrules them.** General opening folklore is board-agnostic and this
specific board may reward something different — you _want_ the solver free to find that. Almost
never encode an opening as a hard rule.
- **"Must-not-do" moves.** Ask: _can you construct any position where the move is correct?_
- **No, provably never** (e.g. passing up a strictly-free scoring action, wasting a QIC for
nothing) → **AVOID** (hard prune). Effect is _speed, not strength_ — use sparingly, only when
certain.
- **Yes, somewhere** ("usually don't over-expand / neglect power") → **FEAT + WEIGHT** (negative),
learnable and overridable. Most "must-nots" are really this kind. When in doubt, make it soft.
### Encoding legend (put one of these in the "Encode as" column)
| Tag | Meaning | Where it lands in code |
| ---------- | ------------------------------------------------------ | ------------------------------------- |
| **FEAT** | A thing to measure about a position | `ai/features.ts` |
| **WEIGHT** | How much some feature/outcome matters | `ai/evaluate.ts` (hand-set → learned) |
| **PRIOR** | "Try these moves first" in search | `ai/policy.ts` (move ordering) |
| **ROLL** | Bias for how rollouts/playouts play | rollout policy |
| **AVOID** | A genuinely dominated move to prune (use sparingly!) | search pruning |
| **HUMAN** | A tendency/mistake real humans make (for exploitation) | human-move model (§6.7 of plan) |
### Row format used in every section below
`| # | Tip / heuristic | When it applies (conditions) | Confidence H/M/L | Encode as | Notes |`
---
## 1. General / whole-game principles
Tempo, economy-vs-VP, engine-building curve, when to pivot from building to scoring, resource
efficiency, etc. When noting economy tips, describe **projected position** (income + board presence +
expansion room + leech/gaia/tech potential), **not** "climb the Economy track" — see plan §7.2 — and
prefer FEAT/WEIGHT over rules. Round-1-economy emphasis is a strong _motivation_, not a strict rule:
good board presence or denying a key planet can beat pure income.
| # | Tip / heuristic | When it applies | Conf | Encode as | Notes |
| --- | -------------------------------------------------------------------------------------------------------- | ---------------- | ---- | --------- | ----------------- |
| 1 | _(example — replace)_ Prioritize actions that both build the engine **and** score the current round tile | early–mid rounds | M | WEIGHT | tempo compounding |
| 2 | | | | | |
| 3 | | | | | |
---
## 2. Faction play
General notes per faction. (For the monthly challenge only the two chosen factions matter, but keep
general notes here so they're reused across months.) Duplicate the small table per faction.
> **Note on abilities.** These faction abilities are **already implemented in the engine** (base-game
> factions + the Lost Fleet free actions). So the AI automatically _has_ them via legal-move
> enumeration and _learns_ to use them through self-play — nothing here is a rule to hard-code. What
> these notes capture is the strategic **usage/weighting** (soft), and they flag the ability-related
> state the net's features must _see_ (§7.4 completeness) so it can time them.
### Faction: Xenos (engine-accurate)
- **Core engine / plan:** wide expansion; extra starting mine; forms federations cheaply (PI counts as
power 4); QIC-rich.
- **Abilities:** start income `3k,4o,15c,q,up-int` (free Intelligence/AI step at start), mine income
`+o,k`; **PI income `+4pw,+q`** and PI counts as power 4 for federations; **Lost Fleet free action
`OreToPowerTokenArea3`: 1 ore → 1 power token straight into bowl 3.**
- **Strong on:** this board's R1 (TS), R4 (new sector), Sector final — wide-expansion fits Xenos.
- **Key timings:** PI early (the +4pw+q and cheap feds); grab sectors before HH.
- **Common traps:** NOT a native gaiaformer — this board's two mine-on-Gaia rounds + Gaia final demand
deliberate gaiaforming; don't neglect it.
| # | Tip | When | Conf | Encode as | Notes |
| --- | ------------------------------------------------------- | ------------------------------------------- | ---- | ----------- | ---------------------------------------------- |
| 1 | Use ore→bowl3 to fund a power action instead of burning | ore spare + a bowl-3 power action is wanted | M | FEAT | LF Xenos free action; cheaper than burn (§7.5) |
| 2 | Lean into sector spread (Sector final + R4 new-sector) | this board | M | FEAT+WEIGHT | Xenos strength; race it (§7.1) |
### Faction: Hadsch Hallas (engine-accurate)
- **Core engine / plan:** economic powerhouse; credits fund everything (terraform, range, buildings);
highly flexible.
- **Abilities:** start income `3k,4o,15c,q,up-eco` (free Economy step), mine income `+o,k,3c` — the
**extra +3 credits**; **PI free actions (once PI built): `4c→1q`, `3c→1o`, `4c→1k`** (convert gold
into QIC / ore / knowledge).
- **Usage — soft, not a rule:** the credit→QIC conversion is _often_ used late to top up QIC (range/
tech/actions), but that's a tendency; early credit→ore/knowledge can be right when it unblocks a
build or tech now. Encode as FEAT (credit surplus + what the conversion unblocks), never a hard
"only late / only QIC" rule.
- **Common traps:** hoarding credits without converting; building PI too late to use the conversions.
| # | Tip | When | Conf | Encode as | Notes |
| --- | ----------------------------------------------------------- | ----------------------------------------- | ---- | -------------------------------- | ---------------------------------------- |
| 1 | Convert credits→QIC late for range/tech/actions | late, credit surplus, QIC needed | M | FEAT (credit-surplus→conversion) | soft tendency — NOT "only late/only QIC" |
| 2 | Convert credits→ore/knowledge early to unblock a build/tech | when it enables a higher-value action now | M | FEAT | the explicit "not a hard rule" case |
---
## 3. Round-scoring tiles
How to exploit / align with each round-scoring tile type, and how much to bend your plan for it.
| # | Round tile (type) | How to exploit it | Which factions love it | Conf | Encode as |
| --- | ------------------------ | --------------------------------- | ------------------------ | ---- | ----------- |
| 1 | _(example)_ mine-scoring | front-load mine builds this round | terraform-cheap factions | M | FEAT+WEIGHT |
| 2 | | | | | |
---
## 4. Final-scoring conditions
Affinity notes per final-scoring condition (buildings on a planet type, sectors, tech levels,
gaia planets, federations, satellites, etc.).
| # | Final condition | How to chase it | Which factions favor it | Conf | Encode as |
| --- | --------------- | --------------- | ----------------------- | ---- | --------- |
| 1 | | | | | |
---
## 5. Round boosters
Which boosters are strong when, and pick/priority order.
| # | Booster | Value / when strong | When to grab vs pass | Conf | Encode as |
| --- | ------- | ------------------- | -------------------- | ---- | --------- |
| 1 | | | | | |
---
## 6. Tech tiles (standard + advanced)
Value and timing of standard tech tiles and advanced tech tiles; which are worth racing for.
| # | Tech tile | Value | Timing / threshold to take | Race-worthy? | Conf | Encode as |
| --- | --------- | ----- | -------------------------- | ------------ | ---- | --------- |
| 1 | | | | | | |
---
## 7. Power / charge / leech economy
Leech (charge vs decline) decisions, brainstone handling, gaiaforming timing, power-bowl management.
| # | Tip | When | Conf | Encode as | Notes |
| --- | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| 1 | _(example)_ Decline a small leech if the VP cost outweighs the charge this round | low bowls, early | L | FEAT+WEIGHT | engine already has auto-charge; this tunes it |
| 2 | _(example — replace)_ Don't accept leech / pick a booster that makes you overcharge | bowls full or income will fill them | M | FEAT (wasted-charge) | paying VP for nothing |
| 3 | _(example — replace)_ Consider passing early for first player next round | RARE — only when few useful actions/resources left and the first booster / a per-round claim beats them | M | FEAT (pass-tempo) + PRIOR | don't reflexively spend everything first; with a full hand, don't pass; keep power for next-round power actions |
| 4 | _(example — replace)_ Burn power to take a power action you need or to deny one the opponent needs | credits/ore near zero; OR (denial) the opponent ALREADY has bowl-3 power OR your next move will charge them into range — and natural leech won't get you there in time | M | FEAT+WEIGHT | lossy (~half); NO denial value if the opponent can't take it soon (§7.5) |
| 5 | _(example — replace)_ Prefer natural leech over burning — wait if the opponent will build where you can charge | opponent likely to build adjacent soon | M | FEAT (expected-natural-charge) | needs opponent-build prediction (§6.8) |
| 6 | _(example — replace)_ Order queued moves so leech-granting builds come last | multiple moves queued and the opponent could use/burn the charge this round | M | FEAT (opponent-leech-cost) + PRIOR | conditional — don't delay a build you need now (plan §7.6) |
| 7 | | | | | |
---
## 8. Contested resources & tempo (feeds the race/contention feature — plan §7.1)
The powerful "claim" things: advanced tech tiles, federation tiles, Lost Fleet expansion feds,
artifact tokens, the Lost Planet, key blocking hexes (one-time claims); and power actions, QIC
actions, ship actions (per-round shared). For each, note **who tends to win the race and why**, and
any **thresholds** (e.g. "needs level-4 track + a fed token by round 3 to beat a rival to it").
| # | Contested thing | Who wins the race / key threshold | One-time or per-round | Conf | Encode as |
| --- | -------------------------------- | ------------------------------------------- | --------------------- | ---- | ------------ |
| 1 | _(example)_ advanced tech tile X | whoever hits nav L4 + has a green fed first | one-time | M | FEAT (tempo) |
| 2 | | | | | |
---
### Federations (formation & timing) — feeds plan §7.3
Note your rules of thumb for _when_ to form (early fed-tile boost + unlocking the fed token vs
efficiency), _what_ to include (hit the threshold with minimal overshoot & satellites; avoid
overloading 1-power mines), and the _exceptions_ (a satellite/federation final-scoring tile flips the
satellite cost; sometimes upgrading a building already in a fed is still right). Encode as FEAT/WEIGHT,
never hard rules — see §0. The engine enumerates candidate feds, so these notes tune _choice + timing_,
not the connection math.
| # | Federation tip | When / condition | Conf | Encode as | Notes |
| --- | ----------------------------------------------------------------- | ---------------- | ---- | --------------------- | --------------------------------- |
| 1 | _(example — replace)_ Aim for ~7 power with the fewest satellites | default | M | FEAT (fed-efficiency) | overshoot wastes tokens/buildings |
| 2 | _(example — replace)_ Don't sink all power tokens into fed 1 | always | M | FEAT+WEIGHT | keep economy for later feds |
| 3 | | | | | |
---
## 9. Lost Fleet–specific (if the challenge uses Lost Fleet)
Ships, exploration, artifact tokens, expansion federations, Examine Artifact, the new expansion
factions. Note the strong lines and the contested/tempo bits (cross-reference §8).
| # | Tip | When | Conf | Encode as | Notes |
| --- | --- | ---- | ---- | --------- | ----- |
| 1 | | | | | |
---
## 10. Human tendencies (for exploitation — 2p best-response, plan §6.7)
Since it's 2p, we can model the human and best-respond. List common **mistakes / habits** real
players make (on this kind of seed) that the AI can punish. Tag these **HUMAN**.
Also list **telegraphed plans** humans commit to and the **cheapest move that thwarts each** (its cost
to you vs damage to them) — this feeds the opportunistic-denial behavior (plan §6.8). Note: margin
scoring already decides _whether_ a thwart is worth taking; these notes only help the AI _see_ the
opportunity, so don't inflate them into "always block."
| # | Human tendency / mistake | How the AI exploits it | Conf | Notes |
| --- | ----------------------------------------------- | ------------------------------------------ | ---- | ------------------------- |
| 1 | _(example)_ humans under-leech early to save VP | build to force big leech decisions on them | L | verify against real games |
| 2 | | | | |
---
## 11. Per-challenge (per-seed) notes
Fill a fresh copy of this block **for each month's specific seed/factions/turn order**. These are
the setup-specific reads that don't generalize.
### Challenge: `lf-mrj5exuu-c680` (2p Lost Fleet — Xenos vs Hadsch Hallas)
- **Seed / factions / turn order:** seed `lf-mrj5exuu-c680`; 2p Lost Fleet; Seat 1 **Xenos** (first
player), Seat 2 **Hadsch Hallas** (default order — confirm/flip); human picks either, AI plays the
other. Validated: boots a legal game.
- **Round scoring (decoded from engine):**
- **R1** `score8` — 3 VP per **Trading Station** built
- **R2** `score9` — 3 VP per **mine built on a Gaia planet**
- **R3** `score1` — 2 VP per **terraforming step**
- **R4** `lfsector3` — 3 VP the **first time you build a mine in a new Space/Deep-Space sector** (LF)
- **R5** `score10` — 5 VP per **Planetary Institute / Academy** built
- **R6** `score6` — 4 VP per **mine on a Gaia planet**
- **Final scoring:** F1 `sector` = **most sectors colonized** · F2 `gaia` = **most Gaia planets**
- **Boosters in box:** booster5, booster7, booster8, booster9, booster10
- **Lost Fleet ships:** ship techs {tfmars, eclipse}; ship feds {twilight, tfmars, eclipse}; 2 artifact
tokens. Only 2 shuttles for 3 ships — choose carefully (§9, §13e).
- **The big read:** **Gaia-heavy** (R2 + R6 mine-on-Gaia + F2 Gaia final) _and_ **expansion-heavy**
(R4 new-sector + F1 Sector final), with R3 rewarding terraforming and R5 rewarding big buildings.
Neither Xenos nor HH is a native gaiaformer, so **gaiaforming investment vs wide expansion is the
central trade-off to solve.** Xenos naturally hits sector spread (F1/R4) + TS (R1) + cheap feds; HH
funds terraform/gaiaform/expansion via credits (and up-eco start).
- **Opening plan for each faction (fills / feeds the opening book):** _to fill_
- **Known strong lines / traps specific to this setup:** _to fill_
| # | Seed-specific tip | When | Conf | Encode as | Notes |
| --- | -------------------------------------------------------------------- | --------------- | ---- | ------------ | ------------------------------------------------ |
| 1 | Invest in gaiaforming — two mine-on-Gaia rounds (R2,R6) + Gaia final | whole game | M-H | FEAT+WEIGHT | central to this board; neither faction is native |
| 2 | Race sector spread (F1 + R4 new-sector) | expansion phase | M | FEAT (tempo) | contested (§7.1); Xenos favored |
| 3 | Value the R5 (PI/Academy = 5 VP) window | round 5 timing | M | FEAT | time a big-building for R5 |
---
## 12. Uncertain / to ablation-test
Park low-confidence or contradictory tips here. Each becomes an A/B test: run the AI with the tip on
vs off over N seeded games; keep it only if it measurably helps (plan §7).
| # | Tip to test | Hypothesis | Status |
| --- | ----------- | ---------- | -------- |
| 1 | | | untested |
---
## 13. Community-sourced general strategy (captured from forums/guides)
Captured from public Gaia Project / Lost Fleet strategy guides and community discussion (see the
Sources note at the bottom). **Treat these as priors to ablation-test, not truths** — they are
board-agnostic folklore, and per §0 the fixed board may reward otherwise. **Faction/ship "tier"
claims are LOW confidence and must NOT be hard-coded** — use as weak priors at most; the whole point
of the seed-locked value model is to find the truth for _this_ setup.
### 13a. Setup evaluation & faction selection
| # | Tip | Conf | Encode as | Notes |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---- | ------------ | ----------------------------------------------------------------- |
| 1 | Gaia is setup-driven: evaluate board + tech tiles + round & final scoring + boosters **and opponents' picks** _before_ choosing a faction; pick the one the setup favors | H | FEAT | validates the whole faction-value approach (plan §5) |
| 2 | Community "often-strong" factions: Taklons, Itars, Ivits, Lantids; beginner-friendly: Terrans, Xenos, Hadsch Hallas | L | PRIOR (weak) | board-dependent folklore — do NOT hard-code; a weak prior at most |
### 13b. Game arc, tempo, engine
| # | Tip | Conf | Encode as | Notes |
| --- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ---------------------- | ---------------------------------------------------------------------------- |
| 1 | Rounds 1–3 build economy + expand to ~3–4 planets; rounds 4–6 form federations + take tech tiles; late game pivot to round-goal/endgame scoring | M | WEIGHT / emergent | matches plan §7.2 |
| 2 | Secure the Planetary Institute early (R1–2) when it unlocks the faction's power | M | FEAT+WEIGHT | conditional per faction |
| 3 | "Always Be Charging" — settle near opponents to leech power | M | FEAT (leech potential) | balance against overcharge (§7.4) and against feeding opponents leech (§7.6) |
### 13c. Federations & research tracks
| # | Tip | Conf | Encode as | Notes |
| --- | --------------------------------------------------------------------------------------------------------------------- | ---- | --------------------- | --------------------------------------------------------------------- |
| 1 | Aim for 3+ federations; power-7 efficiency + tight satellite placement is critical | H | FEAT (fed-efficiency) | matches §7.3 |
| 2 | Commit fully to 2–3 research tracks; don't spread thin across all 5 | H | FEAT+WEIGHT | |
| 3 | Advance ~2 tracks to L4+ for endgame scaling; endgame research VP can reach 30–40 | M-H | WEIGHT | emergent under final-margin value |
| 4 | With a resource surplus in R5–6, prioritize research to close gaps; grabbing extra L3 milestones each adds endgame VP | M | FEAT | mild tension with "only 2–3 tracks" — it's about milestone thresholds |
### 13d. Advanced tech, boosters, power
| # | Tip | Conf | Encode as | Notes |
| --- | ----------------------------------------------------------------------------------------------- | ---- | ----------------------------- | -------------------------------- |
| 1 | Advanced tech tiles are ~15 pts each — prioritize them over chasing every final objective | M-H | FEAT+WEIGHT | validates the §7.1 adv-tech race |
| 2 | Economic boosters early, VP boosters late | M | FEAT (booster value by round) | |
| 3 | Pass early to grab the best booster + first player — but only once you've met the round's goals | H | FEAT (pass-tempo) | matches the bounded §7.4 |
| 4 | L2→L3 power lets you charge 3; manage burn/charge cycles (esp. Itars/Taklons) | mech | — | mechanical context for §7.4/§7.5 |
### 13e. Lost Fleet–specific
| # | Tip | Conf | Encode as | Notes |
| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | --------------------------- | ---------------------------------------------------------------------- |
| 1 | You can't explore every ship (2 shuttles / 3 ships in 2p; 3 / 4 otherwise) and exploring costs 5 VP (7 for one faction) — choose which ships carefully | H | FEAT (explore cost/benefit) | real VP-now vs actions/fed-token/tech-later tradeoff; contested (§7.1) |
| 2 | Starting close to the ships you need matters (range-gated like mines) | M | FEAT (ship reachability) | feeds setup/faction eval |
| 3 | Each ship holds 1 info + 1 power + 1 credit/knowledge action, 1 fleet skill tile, 1 fleet federation token; the explorer may take a fleet action, a fleet tech tile (instead of a normal one), or a fleet fed token when forming a fed | mech | — | mechanical context |
| 4 | Artifacts are strong and generally underrated; bought with power tokens | M | FEAT+WEIGHT | limited/contested (§7.1) |
| 5 | Ships add flexibility to the rigid base game (e.g. 3 credits→terraform step; 1 knowledge→+3 range) — best for factions with spare credits/knowledge | M | FEAT | |
| 6 | Community opinion: Twilight ship strongest, then Rebellion | L | PRIOR (weak) | board-dependent — do NOT hard-code |
> **Sources (captured 2026-07):** victoryconditions.com Gaia Project factions guide; officialgamerules.org
> Gaia Project strategy; BoardGameGeek & Board Game Arena Lost Fleet threads; namu.wiki Lost Fleet
> page; Board Game Quest Lost Fleet review. Community folklore — verify by ablation (§12), don't trust
> blindly.

View file

@ -0,0 +1,930 @@
# Analysis Mode — Implementation Plan (ready for handoff)
> **Setup update (2026-10-22):** Planning skips opponents’ remaining placements and booster picks;
> it never invents moves for them. Existing placements and picks stay on the cloned board.
> `advanceSetupTurn` preserves the normal setup order and transition to round-one income.
> Booster choices are limited to the tiles selected for this game. During setup, opponents’ chosen
> boosters remain unavailable; later rounds may assume they become available again.
> This supersedes the historical pass-and-play and unrestricted booster-pool descriptions below.
> Status: **Phases 1-7 all done, plus §5.4, off-turn entry, §11's round-0 faction seed, and §12's
> simplification pass (viewer v5.69.0, 2026-08-17, PROGRESS.md #166-179) — the whole feature is
> landed. §12 is the one to read before touching anything here: it replaced the injected sandbox
> wallet with lifted affordability, so several mechanisms described below no longer exist.** Board takeover + line + replay +
> enter/exit/undo/reset/persistence, the sandbox wallet + resource-diff counter, real solo round flow
> (Pass/income/Gaia, the two-round cap, opponent decision auto-resolution), setup-phase pass-and-play
> (opponent mine placement, faction pick, sealed-bid auctions), the hazard-stripe visual treatment
> with the counter's two real surfaces (header headline + full breakdown panel), staleness handling
> on re-entry (§3.5's four-row table, including the own-seat Restore/Discard prompt and the
> `externalData` re-anchor notice), the leech adjustment stepper (§4.4), the commit path (§6, decision
> #13: move 1 live, the rest queued as Sequential premoves in hosted play, gated on real affordability
> with every `adjust` entry stripped out first), and §5.4's map-corner button (bottom-right of the
> hexmap, mirroring the chart icon's top-right placement - built in a follow-up session after being
> deliberately deferred in Phase 5). Every open question in this document was put to the owner and
> answered; §1 is the record of those decisions and should not be relitigated. §2 is a traced account
> of how the existing code actually works — every file:line in it was read, not recalled, so a fresh
> session (Sonnet is fine) can execute this plan without re-deriving the mechanics, though
> PROGRESS.md #167-172 found and corrected five real gaps along the way:
>
> - Shrinking `turnOrderAfterSetupAuction` (via `engine.setup`) for `beginRoundStartPhase`'s benefit,
> as §2.5 originally said to, would have also broken `beginLeechingPhase`'s unrelated use of the
> same getter for table-seating order — so the solo switch shrinks `turnOrder` directly instead,
> and steers `beginRoundStartPhase`'s own fallback via `passedPlayers`, never touching
> `engine.setup`. Recorded in `applySoloRoundFlow`'s own doc comment (`viewer/src/logic/analysis.ts`).
> - Pre-seeding `passedPlayers` unconditionally (needed to make a **setup**-phase entry's eventual
> round-1 transition resolve correctly) breaks a **mid-round** entry instead: `passedPlayers` is
> also the current round's own live pass accumulator, so seeding it non-empty while a round is
> already under way double-counts this seat's own next pass. The fix checks whether round 1 has
> ever started (`passedPlayers === undefined`) before pre-seeding, and otherwise resets it to a
> fresh `[]`, matching what `beginRoundStartPhase` itself always does at an ordinary round
> boundary. Same file, same doc comment.
> - That same `passedPlayers` pre-seed had a UI-side consequence unit tests never caught: entering
> analysis mode during setup made `TurnOrder.vue` show a duplicate player circle, since its own
> `passedPlayers` getter had no round guard (real games never populate that field before round 1,
> so this was never exercised before). Found via a live-browser check (Playwright against the dev
> server) in Phase 5 - fixed by gating that getter on `round >= Round.Round1`.
> - Phase 7's `committableAnalysisMoves` first passed `initialWallet: null` into `replayAnalysisLine`
> unconditionally, assuming its lazy wallet grant would cover a fresh, adjust-stripped replay the
> same way it covers a setup-phase entry. It doesn't: that lazy grant only fires on the _transition_
> into `Phase.RoundMove`, never when `origin` already starts there - the overwhelmingly common case
> (anything past setup). Left unfixed, every round-flow line would have been treated as free to
> commit, with no affordability check at all. Caught by a test built specifically to exercise it
> (zero real credits/ore, a move only affordable via the sandbox top-up) before it ever shipped.
> Fixed by mirroring `enterAnalysisMode`'s own split: grant a fresh wallet eagerly, up front, when
> `origin.phase === Phase.RoundMove`, only falling through to the lazy path for a genuine
> setup-phase entry. Recorded in `committableAnalysisMoves`'s own doc comment.
> - `analysisOffered` gated entirely on `canPlay`, which only ever reads true for whichever seat
> `engine.playerToMove` happens to point at - but a simultaneous sealed-bid round (Silent Auction/
> Preference Split) isn't gated by turn order from the player's point of view at all
> (`Commands.vue`, what `canPlay` actually gates, is not even rendered during one). Found from a
> live owner report on an actual game stuck in that exact round, first fixed narrowly (fall back to
> `sealedBidPhase(engine) !== null` for a locked seat) - then generalized once the owner asked for
> entry to be available off-turn everywhere, not just there. It turned out the narrow fix was one
> instance of a pattern the mechanics already supported for free: `applySoloRoundFlow` already
> forces the clone's turn to the entering seat outright once it reaches `Phase.RoundMove`,
> regardless of the real `playerToMove` at entry, and `grantSandboxWallet` has no turn dependency
> either - the gate was always the only turn-hostile part. `analysisOffered` now reads
> `myLockedSeat !== undefined ? true : canPlay`, and the now-redundant `sealedBidPhase` check was
> removed rather than kept alongside the broader rule. Composing a move or bid once inside already
> worked regardless of turn either way (Phase 4 had already built that half). Recorded in
> `analysisOffered`'s own doc comment.
>
> **§4.4's `adjust` entry is back as a UI control and now has a readout** (PROGRESS.md #188, viewer
> v5.72.4): the Charge 1 / Undo Charge buttons feed it, and the header carries a running total of
> what has been charged that way alongside the engine's own top-up figure. Two things §12 left broken
> were fixed with it — the top-up figure never reached the header at all (it was read off the
> plain-JSON `analysisComposeBase`, and `analysisAssumedPower` is absent from `PlayerData.toJSON()`)
> and it restarted on every replay step rather than counting the line, and pressing Charge 1 while a
> turn was half-composed silently threw that turn away. **§3.5's forced exit is also narrower now:**
> an opponent's move re-bases the line in place (`reanchorAnalysisLine`) instead of closing the
> sandbox; only this seat's own move, a lost two-round window, or a diverged history still force-exit.
>
> §11 was added after the fact, from an owner request that round 0 let you pick ONE faction and go —
> and building it turned up two real bugs in Phase 4's own setup-entry path (the sandbox wallet not
> being re-applied on later replays, and a false "infeasible from move 1"), both found by driving the
> flow through a real browser rather than by any unit test, and both fixed. See PROGRESS.md #173-175.
>
> **Nothing left to continue - this plan is complete, including §5.4 and §11.** The map-corner button lives
> in `SpaceMap.vue` (bottom-right, mirroring the chart icon's top-right placement, `bounds()` extended
> with a second bottom-band reservation) and toggles both directions through one emit Game.vue
> resolves against its own state; the panel's own Enter/Exit buttons and the striped-header
> tap-to-exit from Phase 5 all still coexist with it, matching §5.4's own reasoning for more than one
> exit path. §10's "out of scope" items (AI/move suggestion, opponents moving outside setup mine
> placement, sharing/exporting a line, any database object/RPC/migration/Edge Function) were never in
> scope for this plan and remain exactly that.
>
> Read `CLAUDE.md` and `PROGRESS.md`'s **Working agreements** first. This plan touches the viewer and
> makes one small engine change; it touches no database object and no Edge Function.
---
## 0. What this feature is
**Analysis mode** turns the live board into a local sandbox. You press a button, the board becomes
yours, and you take turn after turn as yourself — unrestricted by what you can currently afford —
while a counter tells you what the whole chain of actions costs. Then you leave, and the real game is
exactly as you left it.
The question it answers is _"can I actually afford this line, and what does it leave me with?"_ — the
thing players currently work out on paper.
It is **not** an AI, an evaluator, or a hint system. It executes exactly the moves you click.
Scope: hosted and self-contained/offline modes both. Nothing about it is server-side.
---
## 1. Owner decisions (settled — do not relitigate)
| # | Question | Decision |
| --- | ---------------------------------------- | ------------------------------------------------------------------------------------------------- |
| 1 | Do opponents move? | **No** — with exactly one exception, opponent mine placement during setup (see #7). |
| 2 | What does exit do? | **Discard the board preview, keep the line.** Re-entering restores it. |
| 3 | Reset / undo | Both. A **Reset** button and an **Undo last move** button. |
| 4 | Where is the line stored? | localStorage, per game, per seat. **Never the database.** Store move strings, never engine state. |
| 5 | Name | "Analysis mode". Header text reads `ANALYSIS — not saved`. |
| 6 | Round 0 / setup | Playable. Pick any faction, place mines, take a booster, play on. |
| 7 | Opponent mines in setup | **Yes** — placed by you, in real setup turn order, so trading-station adjacency is realistic. |
| 8 | Already past faction pick? | Faction pool restricts itself to what is actually available. Falls out for free — see §2.6. |
| 9 | Income / Gaia / pass / round transitions | Work normally, via the engine's own code. See §3.1. |
| 10 | How far can a line run? | **Current round + one more round. Hard cap.** |
| 11 | Shared single-use resources | **Out of scope.** Do not build "assume this board action is taken". Document the limitation. |
| 12 | Leech power you would realistically gain | **In scope.** A manual "assume I leech N power" adjustment. See §4.4. |
| 13 | Commit the line for real | **In scope**, with no move-count limit. See §6. |
| 14 | Visual treatment | Yellow/black hazard stripes: full strength on the sticky header, dimmed on the map. See §5. |
---
## 2. How the existing code works (traced, not recalled)
Do not skip this section. Three of the five hard parts of this feature are already solved somewhere
in the codebase, and two of the traps below will silently produce wrong numbers if you miss them.
### 2.1 The viewer is a renderer; moves leave through one funnel
`state.data` is an `Engine`, replaced wholesale on every update and wrapped in `markRaw`
(`viewer/src/store.ts:228`) so Vue never deep-observes it. Moves leave the viewer at
`viewer/src/launcher.ts:129`:
```ts
if (type === "move") { ...; item.emit("move", payload); return; }
```
The host (`self-contained.ts` or `hosted.ts`) applies that move to the real engine and emits the new
state back. **Anything that must not reach the real game simply must not dispatch the `move` action.**
### 2.2 Board takeover already exists — twice
Both premove compose and cancel-trigger compose already do "stash the real engine, take the board
over, play against a throwaway clone, restore on exit":
- `Game.vue:994` — `applyPremoveMove()`
- `Game.vue:1139` — `applyCancelTriggerMove()`
- `Game.vue:1335` — the dispatch switch that routes a click to `premoveMove` / `cancelTriggerMove`
instead of `move`
- `store.ts:401-408` — the three no-body actions those ride on
Analysis mode is the third instance of this pattern. Follow it: add an `analysisMove` action, route
to it in the `Game.vue:1335` switch, intercept it in the `created()` subscribeAction block near
`Game.vue:486`.
**Replay from a stable base, never from `this.engine`.** `Game.vue:1003` has the comment explaining
why — `handleData()` commits the partial-move-applied result back into `this.engine` on every call, so
cloning from it re-executes an already-applied partial move and throws. This bit premove once already.
### 2.3 Resources: affordability is enforced in command _generation_
`canPay` / `hasResource` (`player-data.ts:433` and `:395`) gate roughly ten call sites across
`engine/src/available/*.ts` — actions, research, federations, ships, spaceship-actions, artifacts.
There is no "ignore cost" flag. **If you cannot pay, the button is never generated.** The only way to
offer an unaffordable move is to make the engine believe you can afford it. That is exactly what
cancel-trigger compose does at `Game.vue:1109`:
```ts
data.credits = 30; data.ores = 15; data.knowledge = 15;
data.qics = 10; data.power.area1 = 4; ...
```
### 2.4 TRAP: the resource caps will silently eat your grant
`player-data.ts:28-30`:
```ts
const MAX_ORE = 15;
const MAX_CREDIT = 30;
const MAX_KNOWLEDGE = 15;
```
They are applied **on gain**, in `gainRewards`:
```ts
this.credits = Math.min(MAX_CREDIT, this.credits + count);
```
Set `credits = 200`, then gain 1 credit from a power action, and you get `Math.min(30, 201)` = **30**.
170 credits vanish with no error. Note the cancel-trigger grant above sits at _exactly_ the caps —
whoever wrote it hit this wall.
This lands precisely on the feature's headline case ("take a power action, watch the counter"). It is
fixed in Phase 2 and is the one engine change in this plan.
### 2.5 Round flow: shrinking the turn order gives you everything
This is the key architectural finding. `move/round.ts:34-35` — passing does:
```ts
engine.passedPlayers.push(player);
engine.turnOrder.splice(engine.turnOrder.indexOf(player), 1);
```
and `move/phase.ts:219` reacts:
```ts
if (executedCommand === Command.Pass) {
if (engine.turnOrder.length === 0) { cleanUpPhase(engine); return; }
```
So with `turnOrder = [mySeat]`, your pass empties the list and triggers the engine's real
`cleanUpPhase` (`phase.ts:517`) → `beginRoundStartPhase` (`:405`) → `beginIncomePhase` (`:469`) →
`beginGaiaPhase` (`:487`) → back to `RoundMove` (`:513`). Round scoring tiles, booster return,
power/QIC action resets, income selection, Gaia phase — all genuine engine code.
And `beginRoundStartPhase` sets `turnOrder = passedPlayers` — which is `[mySeat]` again. **The solo
loop is self-sustaining.**
Two things to know:
- `phase.ts:405` and `phase.ts:366` both fall back to `turnOrderAfterSetupAuction`, so that list must
be shrunk too, or it re-expands your turn order.
- Do **not** use `forcePremovePreviewTurn` (`engine.ts:598`) for this. It sets `phase = RoundMove`
unconditionally, which by definition skips income, Gaia and round transitions — the exact opposite
of decision #9. It stays useful only for the one-shot preview it was written for.
**Correction, found implementing Phase 3 (PROGRESS.md #167) — do not shrink `turnOrderAfterSetupAuction`
after all.** It has no setter; the only way to "shrink" it is mutating its backing `engine.setup`
array. But `beginLeechingPhase` (`phase.ts:561`) reads the SAME getter via `playersInTableOrderFrom`
for a completely different purpose — table-seating order, used to find who a new building offers
leech to. Shrink `engine.setup` and `canLeechPlayers` is always empty from that point on, so a real
leech offer (the "your very first mine" scenario §2.8 is about) never happens at all — the exact
opposite of what the feature needs to demonstrate. The actual fix ships in `applySoloRoundFlow`
(`viewer/src/logic/analysis.ts`): shrink `turnOrder` and clear `passedPlayers` only, applied once
from `enterAnalysisMode` (today's entry gate always already lands at `Phase.RoundMove`, round ≥ 1,
so `beginRoundStartPhase`'s `turnOrderAfterSetupAuction` fallback — which only fires when
`passedPlayers` is still `undefined`, i.e. only on the real game's own setup→round1 transition — has
already happened before analysis mode exists; `engine.setup` never needs touching in that case).
**Phase 4 still needs to work this out for a setup-phase entry**, where `analysisOrigin` starts
before that transition: applying the same `turnOrder=[seat]`/`passedPlayers=[]` reset needs to
happen lazily, mid-replay, at the exact point the clone first reaches round 1's `beginRoundStartPhase`
— probably by pre-seeding `passedPlayers = [seat]` right before that transition fires, so the
`|| turnOrderAfterSetupAuction` fallback never triggers, rather than shrinking `setup` and risking
the same leech-adjacency breakage for round 1 itself.
**Booster reservation correction:** keep already-passed opponents in `passedPlayers` while shrinking
`turnOrder`, so their new boosters stay reserved for the upcoming round (§4.5). At the next boundary,
`beginRoundStartPhase` selects only the analysis seat for income/Gaia/turns and clears `passedPlayers`
as usual. This preserves solo flow and naturally expires those reservations without extra saved state.
### 2.6 Setup already does what decision #7 wants — if you leave it alone
`beginSetupBuildingPhase` (`phase.ts:366`) builds the setup turn order including Lost Fleet expansion
stages, the reverse-order second mine, and Ivits' late placement. `beginSetupBoosterPhase` (`:399`)
does the reverse booster order.
**Do not shrink the turn order during setup.** Run setup as pass-and-play — you make every seat's
choices, which _is_ opponent mine placement, in the correct order, with zero special-casing. Shrink to
`[mySeat]` only when round 1's move phase begins (§3.1).
Decision #8 also falls out for free: start the clone from the live state and the engine's own
available-commands already offer only the factions still available.
### 2.7 Auction phases: null the sealed-bid backend
`store.ts:113-120` documents it: a non-null `sealedBidBackend` means bids are collected server-side;
**null means offline/hot-seat play, where the bid form submits an ordinary move.** So analysis mode
forces it to null, you enter every seat's bid locally, and analysis never touches
`auction_sealed_bids`.
### 2.8 Opponent decisions can be auto-resolved
`engine.autoMove()` (`engine.ts:767`, implementation in `move/auto.ts`) already has handlers for
`autoChooseFaction`, `autoChargePower`, `autoIncome` and `autoBrainstone`.
This matters because of **leech**: `beginLeechingPhase` (`phase.ts:561`) switches to
`Phase.RoundLeech` and waits for opponents to answer a charge offer. Without handling, analysis mode
stalls on your very first mine.
### 2.9 The sticky header already supports context variants
`Commands.vue:55`:
```html
:class="premoveContext ? `sticky-bar-title--${premoveContext.variant}` : null"
```
with `#move-buttons .sticky-bar-title` at `Commands.vue:1296` and the amber `&--trigger` variant at
`:1320`. Analysis mode is one more variant.
Two things not to break:
- The `::before` pseudo-element (`Commands.vue:1305-1315`) is the bottom-sheet **grab handle**. Put
stripes in `background`, not `::before`.
- The auto-leech dropdown (`Commands.vue:76`, `class="ml-auto auto-leech-select"`) is **meaningless in
analysis mode** (opponent decisions are auto-resolved) — that slot is where the counter goes (§5.3).
### 2.10 The map surface is on the container, and it is shared
`theme.scss:755`:
```scss
.space-map,
.space-map-canvas {
background-color: var(--ui-map-canvas);
```
The comment above it notes _"The SVG's transparent inter-sector gaps reveal this material"_ — so
striping this rule makes stripes show through the gaps between sectors, framing the board while
leaving hexes legible. That is the desired effect.
**But that rule is explicitly shared with setup and open-game previews.** Scope the striping under an
analysis-mode class or every lobby preview turns into hazard tape.
Map corners, for button placement: faction wheel occupies a top-left pocket, the chart button
(`SpaceMap.vue:49`) and terraform swatches (`:55`) occupy a top-right band, the colour legend runs
down the left. **Bottom-right and top-centre are free.** `bounds` (`SpaceMap.vue:389`) reserves
footprints so hexes do not overlap map UI, and `SpaceMap.spec.ts` tests that clearance — a new
occupant must be added to that reservation logic.
### 2.11 The premove queue accepts the full valid plan
The original three-move limit was removed from both the viewer and engine on 2026-10-04.
The confirmation submits every valid move; the engine rechecks each turn against the live position.
---
## 3. Architecture
### 3.1 The analysis clone
On entry:
1. Snapshot the real engine (`analysisBackup`), exactly as `premoveBackup` does.
2. Clone it: `Engine.fromData(JSON.parse(JSON.stringify(engine)))`.
3. Record `baseRound = clone.round` and `baseMoveCount = engine.moveHistory.length`.
4. Mark the clone `analysis = true` (§3.4) and grant the sandbox wallet (§4.1) — **only if already in
`RoundMove`**; during setup the grant is withheld (it would allow builds setup does not permit).
5. Force `sealedBidBackend = null` in the store (§2.7).
6. `generateAvailableCommandsIfNeeded()` and hand it to `handleData()`.
The **solo switch** — setting `turnOrder = [mySeat]` and `turnOrderAfterSetupAuction = [mySeat]` — is
applied lazily, the first time the clone reaches `Phase.RoundMove` with `round >= 1`. Before that
point setup runs pass-and-play (§2.6).
### 3.2 The line
The line is an **ordered list of entries**, not just move strings, because §4.4's leech adjustment
must survive replay:
```ts
type AnalysisEntry = { kind: "move"; move: string } | { kind: "adjust"; charge: number };
```
Every change replays the whole line from the entry snapshot. This is the established pattern
(`Game.vue:1003`) and it gives **Undo** (pop the last entry, replay) and **Reset** (clear, replay
nothing) for free. Replaying at most two rounds is cheap — the engine replays entire games routinely.
After each replayed move, resolve any opponent-side pause via `autoMove()` until control returns to
you (§2.8). Setup-phase building placement is the one deliberate exception — that pause is yours to
answer.
### 3.3 Persistence
Key on game id + seat. Store **only** the entry list plus `baseRound` and `baseMoveCount` — never a
serialized engine. This sidesteps engine schema drift in localStorage and makes it structurally
impossible for the §3.4 flag to round-trip into anything real.
### 3.4 The uncapped flag
Add a non-serialized `analysis` flag to `PlayerData` (or thread it from the engine) and make the three
clamps in `gainRewards` conditional on it:
```ts
this.credits = this.analysis ? this.credits + count : Math.min(MAX_CREDIT, this.credits + count);
```
Set it **after** `Engine.fromData`, and confirm it does not appear in `toJSON` (`player-data.ts:167`).
An engine spec should assert both: uncapped gain works when the flag is set, and the flag never
survives a `toJSON` → `fromData` round trip.
### 3.5 Staleness on re-entry
Compare stored `baseMoveCount` against the live `moveHistory.length`:
| Situation | Behaviour |
| --------------------------- | ---------------------------------------------------------------------------------- |
| Unchanged | Restore the line silently. |
| Only opponents moved | Replay; keep the valid prefix, stop at the first entry that throws; show a notice. |
| **Your own seat moved** | **Prompt to keep or clear.** Do not silently replay. |
| Live game advanced past cap | Clear the line; the two-round window has moved on. |
The third row matters: the common case is "I analysed a line, then played it", and silently replaying
it would double the move or throw.
Note that a mid-analysis `externalData` arrival must **not** nuke the line the way premove does at
`Game.vue:461-483`. Keep the line; re-anchor and show a notice.
### 3.6 Isolation
Non-negotiable, in rough order of danger:
- Never dispatch `move` — use `analysisMove` (§2.2).
- Exclude analysis state from `HostedGameHost.onCommittedState` — `CLAUDE.md` names it as the hook for
anything that saves or exports hosted state.
- Exclude it from the offline mirror (`hosted/offline-mirror.ts`), or a sandbox line could be written
into the offline copy and uploaded.
- Analysis mode, premove compose and cancel-trigger compose must be **mutually exclusive**. Three
board-takeover modes contending for `state.data` is a bug farm. Entering one disables the others.
### 3.7 The two-round cap
Allow Pass while `clone.round < baseRound + 1`; suppress it after, with a short explanation in the
panel. Entering during setup gives you setup plus round 1.
**Round 6 is the deliberate exception**: passing there hits `finalScoringPhase` (`phase.ts:542`) and
ends the game. Allow it — seeing a line's final score is genuinely useful — but make it explicit
rather than incidental, and make sure the EndGame state does not fire real game-over UI.
---
## 4. Resource accounting
### 4.1 The sandbox wallet
Once the clone is flagged (§3.4) the caps are gone, so grant generously — enough that affordability
never blocks a button. Record the granted amount per resource as `grant`.
### 4.2 Display: real numbers, negative when overdrawn
Displayed value = `cloneValue − grant`. So a player with 3 credits who spends 10 shows **−7**, in red.
Negative means "this line is not affordable as it stands", which is the answer players actually want.
### 4.3 The counter itself
Diff-based, never accumulated: `net = current − baseline`, per resource. Gains from power actions,
income and leech then fall out automatically as negative usage with no special-casing.
Three things to surface:
- **Per-resource net** — c / o / k / q / VP, plus power as a **bowl-state delta** (`4/2/3 → 2/2/1`)
rather than an invented scalar, since power is derived (`player-data.ts:456-462`), not stored.
- **Feasibility verdict** — not a single number. If you overdraw at entry 4, everything after it is
hypothetical: say **"infeasible from move 4"**, not "short 6c".
- **Per-round breakdown** once a line crosses a round boundary, since income muddies a cumulative
total.
### 4.4 The leech adjustment (decision #12)
Because opponents never build, you never gain the leech power you would realistically collect, so
analysis is **pessimistic on power**. Provide a small stepper — "assume I leech N power" — which
appends an `{ kind: "adjust", charge: N }` entry to the line. On replay it applies as a
`Resource.ChargePower` gain to your player data. It is an explicit, visible line item, never silent.
### 4.5 Known limitation (decision #11 — document, do not build)
Board actions, tech tiles, boosters and federation tiles are **shared, single-use** pools. With
opponents frozen, analysis shows all of them available, so a line built on the 7-credit power action
assumes nobody takes it first. This is deliberately out of scope. State it in the panel's help text so
the number is not over-trusted.
For boosters, this assumption applies only to future **undecided** choices: the pool contains only
this game's drawn tiles, excludes your current booster, and excludes the new boosters already chosen
by opponents who passed in the current real round. Opponents still playing may return their old
boosters before your planned pass, so those remain selectable. Existing reservations expire once
the simulation enters the next round; its next pass chooses for a later round, not the one already
reserved. Entering after your own real pass starts in that next round too. Setup still uses actual
availability. Reanchoring or reloading derives reservations from the current real position, without
adding metadata to saved plans.
---
## 5. Visual design
The board must be unmistakably not-live at a glance. The treatment is **yellow/black diagonal hazard
stripes**, at two different strengths.
### 5.1 Header — full strength
A new `&--analysis` variant beside `&--trigger` (`Commands.vue:1320`), using a
`repeating-linear-gradient` at 45°. Text reads `ANALYSIS — not saved`. Keep the grab handle (§2.9) and
ensure text contrast against the stripes — a solid or scrimmed text backing, not raw text on stripes.
Desktop does not render the sticky bar (`showStickyMobileBar`), so give the standalone `#move-title`
the same treatment, or desktop is the one place analysis mode looks like live play.
### 5.2 Map — dimmed
Same gradient, **much lower contrast**, on the `theme.scss:755` rule, scoped under an analysis-mode
class (§2.10). Stripes read through the inter-sector gaps and frame the board without fighting planet
colours or straining the eye over a long session. Verify in both light and dark themes — the block
right below that rule adjusts hex strokes per theme.
### 5.3 Where the counter goes
The owner's instinct that `StickyResourceBar` is too tight is right — it is already ten SVG icons
wide on a phone, and adding deltas would double it.
**Recommendation — split by urgency, using two surfaces that already exist:**
- **Headline in the striped header**, in the slot freed by the auto-leech dropdown (§2.9). Compact:
net deltas plus the feasibility verdict. This is the surface that is _always_ visible on mobile,
which matters because the map scrolls away.
- **Full breakdown as a compact HTML overlay pinned to the map's top-centre** — genuinely free space
(§2.10), and it reads well against the dimmed stripes. Per-resource, per-round, plus the leech
stepper and Reset / Undo / Commit controls.
On desktop both are visible at once; on mobile the header carries you when the map is scrolled off.
### 5.4 Entering and leaving
Enter via a button at the **map's bottom-right** (free, §2.10 — remember to extend the `bounds`
reservation). Exit from either that button **or by tapping the striped header**, since on mobile the
map is often scrolled and a map-anchored control can be off-screen when you want out.
---
## 6. Committing a line (decision #13)
The natural end of an analysis is "yes, do that". The premove system already provides the machinery.
**The line becomes: move 1 committed live, moves 2..N queued as Sequential premoves.** This is not a
workaround — in a real game opponents move between your turns, so anything past move 1 _is_ a premove
by definition.
There is no move-count cap: submit the full valid prefix, with the first move played immediately
when it is the player's turn and all remaining moves queued.
Hard constraints:
- **Only an affordable prefix may be committed.** Track per-entry feasibility during replay; if the
line went negative at entry 3, only entries 1-2 are committable. A line that only worked because of
the sandbox grant must never be committable.
- Premoves are **hosted-only**. In self-contained/offline play, offer move 1 only.
- `{ kind: "adjust" }` entries are analysis-only fiction — they are never committed, and an entry
after one is only committable if it is still affordable without the assumed leech.
- Committing exits analysis mode and clears the line.
**It confirms first (added 2026-08-20, from an owner question).** Commit opens
`AnalysisCommitConfirm.vue` — a modal listing every move that is about to go out, marked `plays now`
or `premove N`, then every move being left behind with the one sentence saying why (the
`AnalysisCommitCut` returned alongside the prefix by `analysisCommitPrefix`, or the absence of
premoves in offline play). This does not contradict §12.4's "no confirmation press": that is about
composing a turn INSIDE the sandbox, where Undo covers a misclick and nothing is real. Commit is the
opposite case — it is the only control whose effect reaches the real game, where the sandbox's Undo
does not follow, and it discards whatever it could not commit. `planAnalysisCommit` is what both the
modal and `commitAnalysisLine` read, so the log shown and the moves played cannot drift apart.
---
## 7. Suggested phasing
Each phase should end green and be independently useful.
| Phase | Scope |
| ----- | ------------------------------------------------------------------------------------------------------- |
| **1** | Board takeover + line + replay. Enter/exit, `analysisMove`, undo, reset, persistence. No unlock yet. |
| **2** | The engine `analysis` flag (§3.4) + sandbox wallet + the diff counter. This is where it becomes useful. |
| **3** | Round flow: solo turn-order switch, pass, income/Gaia, the two-round cap, opponent auto-resolve. |
| **4** | Setup-phase play: pass-and-play setup, opponent mines, null sealed-bid backend. |
| **5** | Visual treatment (§5) and the counter surfaces. |
| **6** | Staleness handling (§3.5) and the leech adjustment (§4.4). |
| **7** | The commit path (§6). |
Phases 1-3 are the feature. 4-7 can each be cut without invalidating what is built.
---
## 8. Testing
Per `CLAUDE.md`'s testing table — **run only what the change can break**, and always append
`--reporter min`:
- Viewer work (most phases): the touched component specs, then the viewer suite **once**, at the end.
- The engine change in Phase 2: the affected engine specs, then the engine suite **minus `src/ai/**`\*\*.
- **Never the offline-AI suite.** It is unrelated to this feature, takes many minutes, and is
OOM-killed partway through in this container.
Specs worth adding:
- Engine: uncapped gain with the flag set; the flag not surviving a `toJSON` → `fromData` round trip.
- Solo round flow: pass with `turnOrder = [seat]` reaches the next round's `RoundMove` with income
applied.
- Line replay: undo, reset, truncation at a since-illegal entry, and the three staleness cases.
- Counter: a power action produces a **negative** net cost (this is the case §2.4's trap breaks).
- Isolation: an analysis move never dispatches `move`, and never reaches `onCommittedState`.
---
## 9. Before committing
- Run **`pnpm run prettier`** from the repo root. The `All` workflow gates `prettier --check` on every
push to every branch, and `master` is the production/Vercel target.
- Add the changelog entry through `node scripts/update-viewer-release.js`, never by hand-editing
`release.json`. This is user-facing, so it needs a `user:` entry as well as `dev:` ones.
- Update `PROGRESS.md`'s "Done so far" and this document's status header.
---
## 10. Out of scope
- Any AI, evaluation or move suggestion.
- Shared single-use resource contention (§4.5) — deliberate, decision #11.
- Opponent moves outside setup mine placement.
- Sharing or exporting a line (the `?state=` URL loader and game chat would make this natural later).
- Any database object, RPC, migration or Edge Function. **This feature is entirely client-side.**
---
## 11. Round 0: the faction seed (added 2026-08-17, viewer v5.68.0)
Decision #6 made round 0 playable, and decision #7 made you place everyone's starting mines. What
neither gave you was a say in **which faction you analyse as**: the line had to walk every seat's
pick, and in an auction game every seat's bid — after which the auction's own resolution decided your
faction for you. (Checked against the engine, not assumed: a Preference Split line that picked
terrans for seat 0 resolved to nevlas.) So the one question a round-0 analysis exists to answer —
"how does this faction's opening actually play?" — was the one it could not be asked.
### 11.1 The mechanism
A third entry kind beside `move` and `adjust` (§3.2), and like `adjust` it is analysis-only fiction
with no move string behind it:
```ts
{ kind: "faction"; lineup: Faction[] } // one faction per seat, indexed by seat
```
Applying it (`applyFactionSeed`, `viewer/src/logic/analysis.ts`) assigns the lineup and then calls
the engine's own `endSetupFactionPhase`, so faction boards load, Lost Fleet terraforming costs and
Moweyds' starting ship are dealt out, and the setup building turn order is built by the same code a
real game uses. **This is the one engine change**: that function is now exported
(`engine/src/move/phase.ts`, re-exported from `engine/index.ts` beside `leechPossible`) with its
behaviour untouched.
Three things the implementation must keep right, each of which breaks silently otherwise:
- **`engine.setup` has to keep matching the lineup.** `turnOrderAfterSetupAuction` is a getter that
reads player order back out of it by looking up who holds each faction, so a mismatch fills every
later turn order with -1. A seed that only permutes an already-complete pool (the auction case)
keeps its existing order — preserving the real table's turn order — and only a seed that changes
the pool itself rebuilds it in seat order.
- **`player.variant` must be cleared**, or `endSetupFactionPhase` loads the faction board of whatever
faction that seat held _before_ the seed.
- **`data.bid` is reset to 0.** A bid recorded against the old faction is meaningless against the new
one, and a bid only costs VP at final scoring (`finalScoringPhase`), which a two-round line never
reaches — so a seeded line has no auction price in it at all. Stated in the panel rather than
guessed at.
### 11.2 Which factions are offered, and what a swap means
The pool is everything the table already holds plus everything still on offer (the engine's own
`ChooseFaction` data, so bans, expansion membership and the same-planet-colour rule are respected
without re-deriving any of them). Both halves matter: mid-pick the available half carries the answer,
while in an auction's bid phase every faction is already claimed and nothing is on offer — that is
precisely the case this feature exists for.
Choosing a faction an opponent currently holds **swaps the two seats** rather than pulling an
unrelated faction in, which is what "what if the auction lands it on me" means. The lineup is built at
compose time and stored in the entry, never re-derived on replay: the pool shrinks and grows as the
line is edited, so re-deriving could hand a stored line a different table than the one it was set up
with.
### 11.3 Scope limits
- Only from a round-0 phase before the first starting mine (`SetupBoard` … `SetupPreferenceBid`).
From `SetupBuilding` onwards the table is settled and pass-and-play (§2.6) already covers it;
reseeding there would silently discard placements already made.
- A line holds at most one seed, always as its first entry. Choosing again replaces the line — that
is what "actually, show me Itars instead" means.
- **Nothing from a seeded line is ever committable** (§6). Every move in one was played on a table
this seat only imagined, possibly as a faction it does not hold.
---
## 12. The simplification pass (2026-08-17, viewer v5.69.0)
Owner instruction, after playing the feature: strip the UI back to what is genuinely needed, and stop
capping the sandbox seat's resources at a fake maximum. This turned out to be one change, not two.
### 12.1 No injected wallet - lifted affordability instead
Analysis mode used to make unaffordable moves clickable by **injecting resources** (30c/15o/15k/10q),
because the engine enforces affordability at command-GENERATION time (§2.3). Everything else was
compensation for that lie: `AnalysisWallet` recorded baseline vs grant, the counter showed
`displayed` (clone − grant) beside `net`, and `walletGrantedAt` existed only so pre-grant snapshots
were not judged against a grant that had not happened yet.
All of it is gone. `PlayerData.hasResource` now returns true for the analysis seat on the five
overdrawable resources (credits, ore, knowledge, QIC, power - `ANALYSIS_OVERDRAWABLE`), payment is
already plain arithmetic, and the seat simply goes negative. Consequences worth knowing:
- **The player board needed no change at all.** It reads `data.credits` and friends directly, so the
real number - negative when overdrawn - is what it was always going to render. `Resource.vue` marks
a negative count `.overdrawn` (red), which covers the board and the mobile sticky bar in one rule.
- **The gain clamps are correct again.** MAX_CREDIT/MAX_ORE/MAX_KNOWLEDGE used to be bypassed for the
analysis seat so the injected wallet survived; a real player's gains cap the same way, so clamping
is now the faithful behaviour and the bypass was deleted.
- **Everything that is not a spendable resource stays gated.** A Gaiaformer you do not own, or a token
outside the Gaia area, is a component or a board position rather than a balance to be in debt on.
- **Two traps.** `Player.maxPayRange` is a `for(;;)` that only ends when `hasResource` says no, so it
needs its own ceiling (real capacity + a fixed slack) or free-action conversions hang the browser.
And `spendPower` moves tokens area3 → area1 with no floor, so an unpayable power cost would leave a
NEGATIVE bowl - see §12.2.
- The counter is now `AnalysisStatus`: an overdraft summary plus assumed power. Nothing per-resource,
no snapshots, no feasibility scan.
### 12.2 Power is topped up, never negative
Power bowls hold tokens, not a balance, so "just let it go negative" produces a nonsense state that
every later charge compounds. `assumePowerForAnalysis` charges the shortfall up first through the
engine's own `chargePower`, one step at a time, and only fabricates tokens when there is genuinely
nothing left below to lift. Either way the total lands in `analysisAssumedPower`, which the header
shows as `+N power` - so the assumption is visible, and a line that needed it is not committable.
This **replaces the manual leech stepper** (§4.4/decision #12): "assume I leech N power" was answering
the same question by hand. `adjust` entries still replay, so lines saved before this still load.
### 12.3 One bar, no panel
The yellow container is deleted. Its controls live in the hazard-striped header, which already existed,
already said "not live", and is the one thing still on screen on a phone once the map scrolls away:
`ANALYSIS · N moves · [−7c] · [+2 power] · Undo · Reset · Commit · ⓘ`
- `AnalysisHeaderControls.vue` is rendered by BOTH headers (desktop `#move-title`, mobile sticky bar).
The info modal therefore lives **outside** it (`AnalysisModeInfo.vue`, rendered once by Commands.vue):
two copies of one `b-modal` id make the button open whichever Bootstrap-Vue registered first, the
trap SetupStatus.vue's own comment warns about.
- Every explanatory sentence moved into that modal, behind the ⓘ button.
- `AnalysisPanel.vue` survives only for what cannot live in a one-line bar: staleness notices, the
saved-line prompt (both must be readable when analysis mode is NOT active, when there is no header),
and round 0's faction picker.
- **The enter banner and the Exit button are gone**, and so is tap-to-exit on the header - it now hosts
buttons, so a press meant for Undo must never be read as "leave". The map's corner button is the only
way in and out.
### 12.4 No confirmation press
A sandbox turn fires the moment it is composed: Undo already covers a misclick, and a round-0 line
otherwise spends a press per seat confirming placements the player has to make for everybody.
`checkAutoClick` auto-clicks a lone `needConfirm` button when `controller.analysisMode` is set -
warnings still block it, and ordinary single-option buttons still obey the player's own auto-click
preference, so opening a menu never fires a move by itself.
### 12.5 An opponent's leech can never strand you
Reported bug: building within leech range paused the engine on `Phase.RoundLeech`, and because
analysis mode forces `canPlay` true (§2.6, for setup pass-and-play), `Commands.vue` rendered **the
opponent's** accept/decline prompt - with the player unable to continue their own line. Three changes,
each of which would have been enough on its own, because this must not come back:
1. `resolveOpponentDecisions` **declines first and deterministically** rather than trying
`engine.autoMove()` first, whose answer depended on the opponent's own auto-charge settings and
returned "ask" (i.e. no answer) above their comfort threshold. An opponent's leech is worth nothing
in a sandbox where they never build.
2. It answers **every** offer, not just `offers[0]`, and **never throws** - it runs outside
`replayAnalysisLine`'s try/catch, so an exception there killed the whole click.
3. `canPlay` gates on the analysis seat's own turn from round 1 on (round 0 keeps pass-and-play). An
unresolved pause now shows nothing to press instead of somebody else's decision.
### 12.6 Also worth knowing
`markAnalysisSeat` must be applied to `analysisOrigin` **before** `applySoloRoundFlow`, and
`replayAnalysisLine` regenerates available commands on the initial clone: `Engine.fromData` carries
over the command list the origin was serialized with, and that list was built while affordability
still applied to this seat.
---
## 13. Several lines at once (owner request, 2026-08-20)
> Status: **done** (viewer v5.74.0). Tabs across the top of the striped header, one per line, with
> `+` to start another. No database object, no RPC, no Edge Function — localStorage only, same as
> decision #4 has always required.
### 13.1 What was asked for, and what it turned into
The request was "a Save button that saves the current line as a tab, so I can work out several lines
and compare them". Two things came out of talking it through, and the shipped feature is the second
one:
- **There is no Save button.** The line already persisted on every completed turn
(`setAnalysisEntries` → storage, from Phase 3 onwards), so nothing was ever unsaved. A Save button
would have created a second meaning of "saved" and, with it, the question of whether unsaved work
could be lost. Instead **Line 1 exists from the moment the sandbox opens**, `+` adds the next one,
and every line autosaves exactly as the single line always did. Owner instruction, verbatim:
_"Autosave. So there is already a line 1 from the get go and you can simply create a new one if
you want which is also autosaved."_
- **Tabs are numbered, never named.** Owner instruction: _"No naming the tabs just line 1 line 2 and
so on."_ Naming is a thing to do before you can get on with the question, and the tab already
carries the label that matters for comparing — its own result.
### 13.2 `+` forks (owner instruction, same day)
Pressing `+` copies the line you are on into the new tab, rather than opening an empty one. That is
the whole of "forking a line": play the shared opening once, press `+`, and carry on differently.
Reset is still one press away when starting over was what was wanted — which is why the copy can be
the default without taking anything away.
Deep-copied, not a second reference to the same entry objects. Nothing edits an entry in place today
(every path replaces the whole array), but two lines pointing at one object is a trap waiting for the
first path that does.
### 13.3 The one thing tabs alone do not do
A strip that only lets you _switch_ between lines does not let you _compare_ them. Switching replaces
the whole board, so line A has to be held in your head while line B is on screen — which is precisely
what the sandbox exists to stop you doing, and the same failure the charged-power readout was added
to fix (PROGRESS #188).
So **each tab carries its own outcome**: the VP it ends on relative to where the sandbox started, a
red `!` when the line spends more than the seat has, and a `~` when the board has moved on and part
of that line no longer applies. The answer for every line is on screen at once, and switching becomes
something you do to _continue_ a line rather than to read it. `summarizeAnalysisLine` computes it,
and it works for a line that is not open because every line shares one origin (§13.4).
### 13.4 Why lines are cheap
`AnalysisLineSet` puts `baseRound`/`baseMoveCount` on the **set**, not on each line: the sandbox
clones the board once on entry and every line is a different sequence of turns from that one point.
Three things fall out for free:
- Switching lines is a replay, not a second board takeover.
- Staleness (§3.5) stays **one** decision for the whole set rather than a per-line one.
- Any line's end state can be computed without leaving the line you are on — which is what §13.3
needs.
### 13.5 Decisions
| Question | Decision |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Does `+` copy the current line? | **Yes — `+` forks.** It shipped as an empty new line and was changed the same day on owner instruction. The comparison you actually want is nearly always "three moves in, X or Y?", and an empty tab makes you re-click the shared prefix by hand for every alternative — tedious, and worse, one misclick while re-entering it compares two lines that do not share the prefix you think they do. Reset already blanks a line in one press, so making the fork the default costs nothing. |
| How many lines? | `MAX_ANALYSIS_LINES` = 5. The cap is the header's width, not localStorage's quota — past this the tabs stop fitting one row on a phone. |
| Deleting | An `✕` inside the **open** tab only, never on the last line. An `✕` on every tab is five ways to lose work one mis-tap from the control used to switch between them. |
| What does Commit clear? | **Every line.** The others were alternatives to the move just played for real, worked out from a board the game has left. `AnalysisCommitConfirm.vue`'s footer says so rather than implying "this line" only. |
| Which line is open on re-entry? | The one that was open on exit — `active` is stored with the set. |
| What happens to the other lines on a re-anchor? | They keep their entries and are trimmed the first time each is opened. Re-anchoring all of them up front would silently edit lines that are not on screen, and cost one replay per tab. Their tabs stay honest in the meantime because `summarizeAnalysisLine` replays against the new origin. |
| A half-composed turn when switching? | Discarded, silently. It is not a line entry until it completes (`applyAnalysisMove`), so it belongs to the line being left. |
### 13.6 Migration — read before touching the storage shape
The pre-tabs value is a bare `AnalysisLine` under the **same** key, and `master` deploys straight to
production, so real in-progress games are carrying one right now. `loadAnalysisLines` tells the two
shapes apart by which field they carry (`entries` vs `lines`) and reads a single stored line back as
Line 1. A second key would only have left the old one behind for a later version to trip over.
### 13.7 File map
| File | What it holds |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `viewer/src/logic/analysis.ts` | `AnalysisLineSet`, `loadAnalysisLines`/`saveAnalysisLines` (+ the v1 migration), `normalizeAnalysisLineSet`, `MAX_ANALYSIS_LINES`, `analysisLineLabel`, `summarizeAnalysisLine` |
| `viewer/src/components/AnalysisLineTabs.vue` | The strip. Owns no state — Game.vue holds the lines, this reports presses |
| `viewer/src/components/Game.vue` | `analysisLines`/`analysisActiveLine`/`analysisLineSummaries`, `selectAnalysisLine`/`addAnalysisLine`/`closeAnalysisLine`, and `analysisEntries` as a getter over the open line |
| `viewer/src/components/Commands.vue` | Renders the strip in BOTH headers, and the `flex-wrap` that gives it its own row |
### 13.8 Where the strip sits, and why that took two goes
The tabs are a **sibling just before** each header, pulled down so their square bottoms overlap the
banner's top edge by 3px — browser tabs resting on a toolbar. They started as the header's own first
row (via `flex-wrap` on a `d-flex align-items-center` container), which put a band of stripes above
them and read, correctly, as tabs floating in the middle of the banner rather than on top of it.
Owner report: _"Why is the tab sitting on the middle of the sandbox banner. It should sit on the top
of it!"_
Three consequences to keep in mind if this moves again:
- **The mobile band's grab handle is suppressed in analysis mode** (`&--analysis::before`). It draws
along the same few pixels of the same edge the tabs now rest on.
- **The strip takes over the mobile band's negative top margin.** `.sticky-bar-title` full-bleeds
itself over the sheet's top padding with `calc(-0.7rem)`; the strip is the first thing in the sheet
now, so it carries that pull-up and the band's own is zeroed. Leaving both makes the band ride up
through the tabs.
- **The strip's row is transparent, and on mobile that took work.** Only the tabs may show above the
banner (owner instruction). On desktop it is free: the strip sits on the page and the page shows
through. Inside the mobile sheet it is not — the sheet paints a gradient, a rounded top and a drop
shadow across its whole box, including the band the tabs stick up into, which reads as a solid bar
behind them. While the strip is up the sheet therefore stops painting itself and hands that job to
a `::before` starting at the striped banner's top edge (`--sandbox-tabs-height`, measured by the
existing `stickyBarObserver` off the banner rather than off the tabs — the tabs overlap the banner
deliberately, so measuring them leaves a hairline of map across its top). Moving the strip out of
the sheet instead does not work: the sheet is `overflow-y: auto`, so anything above its top edge is
clipped, and `position: fixed` to escape that would decouple the strip from the sheet during the
pinch-zoom counter-transform `zoom-compensation.ts` exists to prevent.
Switching off the sheet's background was not enough on its own: its lift shadow is
`0 -12px 28px`, and **a negative y-offset paints above the edge it belongs to**, so it went on
bleeding a dozen pixels of blur straight up into the strip's row — measured near-black at the
row's lower edge, fading to the map colour at its top, which is what "not actually transparent"
looked like. The pseudo keeps only the 1px divider highlight. The sheet loses nothing by it: in
sandbox mode its top edge is a yellow/black hazard banner, a far harder separator from the map
than any drop shadow. Verified by sampling the rendered pixels rather than by eye — the row now
reads one uniform colour top to bottom, the map's own.
- **Each copy needs its own show/hide rule.** The strip used to be a child of whichever header it
belonged to and inherited that header's visibility for free. As a sibling it does not:
`#move-title.hide-on-mobile-sticky` no longer reaches the desktop copy, and the sticky copy is not
covered by `.sticky-bar-title`'s own `display: none` outside the media query. Both rules are
spelled out explicitly — without the second one a desktop viewport renders **two** strips, because
`showStickyMobileBar` is phase-gated in JS, not viewport-gated.
### 13.9 Two traps
- **The striped header is click-to-exit** (§5.4). The strip's root carries `@click.stop` for exactly
that reason: without it every press on a tab would also close the sandbox, and would land as
"exit" rather than "switch line" — the worst available reading of that press.
- **`analysisLineSummaries` is a refreshed field, not a computed getter.** `analysisOrigin` is a live
`Engine` in a component field, so a getter touching it re-runs on any reactive change in that
object graph, and each run replays EVERY line — multiplying the sandbox's per-move engine work by
the number of open tabs (`PERFORMANCE.md`). A memo keyed on the origin's move count plus the line's
contents keeps a refresh to just the line that changed.
Verified in a real browser (Playwright, both the desktop `#move-title` layout and the mobile sticky
band) as well as by unit tests — §11 and §12 both turned up bugs that only a real browser found.

535
docs/lost-fleet/BACKEND.md Normal file
View file

@ -0,0 +1,535 @@
# Lost Fleet — Supabase Multiplayer Backend: Design (PROPOSED, awaiting owner confirmation)
> Status: **DESIGN ONLY — no implementation code yet**, per the working agreement (plan first,
> confirm, then code). Grounded in the actual code paths listed below, not assumptions.
> Locked decisions honored: §A2 (undo within own turn only), §A3 (no Automa/solo),
> §J1 (only completed turns persist + broadcast), §J2 (derive "who can act" from the engine,
> not round-robin), §J3 (seed fixed at creation), §J4 (email turn notifications baseline).
> Date: 2026-07-01.
## 0. Code facts this design is built on (traced, with refs)
| Fact | Where |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| The viewer app is wrapped in an `EventEmitter`; an external host drives it via `"state"`, `"player"`, `"preferences"` events and observes `"move"` | `viewer/src/launcher.ts:26-90` |
| `"player"` event → `store.commit("player", data)` → `state.player = { index }` | `launcher.ts:41`, `store.ts:205-207` |
| Turn locking already exists: `canPlay = !ended && (!state.player \|\| sessionPlayer === engine.players[currentPlayer(engine)])` — it just never gets a non-null `state.player` today | `Game.vue:272-274`, `Game.vue:307-313` |
| `currentPlayer(engine)` = `engine.playerToMove` | `engine/wrapper.ts:201-203` |
| `engine.playerToMove` returns `tempCurrentPlayer` when set — i.e. **mid-turn leech/charge interrupts already resolve to the interrupting seat**. Exactly one seat can act at any moment. | `engine/src/engine.ts:588-594` |
| Commit rule: clone engine, apply the move line, keep it **only if `copy.newTurn`** (turn completed); otherwise the clone is discarded and only rendered | `viewer/src/self-contained.ts:127-141`, mirrored by `engine/wrapper.ts:205-210` (`toSave`) |
| The `"move"` payload is the **whole turn line so far** (the UI accumulates commands with `". "` into `currentMove` and re-emits the full line each time) — so one committed turn = one string | `Game.vue:143,353-391` |
| `engine.moveHistory[0]` is the `init <players> <seed>` line; committed turns are indexes 1.. | `self-contained.ts:104`, `engine.ts:319,421` |
| Replay is total: `new Engine(["init N seed", ...moves], options)` deterministically rebuilds any state (§J3) | `self-contained.ts:104`, whole engine test suite |
| At this design's 2026-07-01 snapshot, no local persistence existed. A separate `?offline=1` hot-seat mode with local recovery was added on 2026-07-17; ordinary self-contained test URLs remain ephemeral. | `viewer/src/offline-game.ts`, `viewer/src/self-contained.ts`, PROGRESS.md #102 |
| Game options shape to persist = `SelfContainedSetup["options"]` | `self-contained.ts:12-26` |
| Engine `Player` has a display `name` field, restorable via `fromData` | `engine/src/player.ts:123,171,223` |
Conclusion baked into everything below: **the engine is the sole authority on legality and
turn order; Supabase stores `seed + options + append-only committed turn lines` and fans them
out.** The backend never interprets game rules. No `engine/` changes are needed anywhere in
this plan (everything uses the existing public surface: `fromData`, `move`, `newTurn`,
`playerToMove`, `moveHistory`, `phase`).
## 1. Schema (one SQL migration, checked into `supabase/migrations/`)
```sql
create table games (
id uuid primary key default gen_random_uuid(),
created_at timestamptz not null default now(),
created_by uuid not null references auth.users (id),
name text not null default '',
seed text not null, -- fixed at creation, never regenerated (§J3)
player_count int not null check (player_count between 2 and 5),
options jsonb not null, -- exact SelfContainedSetup["options"] shape
status text not null default 'active' check (status in ('active', 'finished')),
current_seat int, -- engine.playerToMove after last commit; null when finished
move_count int not null default 0, -- = max(moves.seq); maintained only by commit_turn()
last_committed_by uuid, -- who committed last (notify skips self-notifications)
-- Phase 2 (optional fast-boot cache, see §8) — columns exist but stay null in v1:
cached_state jsonb,
cached_state_moves int
);
create table players (
game_id uuid not null references games (id) on delete cascade,
seat int not null check (seat >= 0), -- = engine player index 0..player_count-1
invited_email text not null, -- stored lowercased
user_id uuid references auth.users (id), -- null until the invitee claims the seat
display_name text not null default '',
primary key (game_id, seat),
unique (game_id, invited_email)
);
create table moves (
game_id uuid not null references games (id) on delete cascade,
seq int not null, -- 1-based; equals the line's index in engine.moveHistory
-- (the init line is index 0 and is NEVER stored — it is
-- reconstructed from games.seed/player_count)
seat int not null, -- engine player index that committed this turn
move text not null, -- the full committed turn line (may contain ". "-joined commands)
committed_at timestamptz not null default now(),
committed_by uuid not null references auth.users (id),
primary key (game_id, seq) -- append-only + race-safe: a stale double-commit is a PK conflict
);
-- §6 (push notifications, post-amendment):
create table push_subscriptions (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users (id) on delete cascade,
endpoint text not null unique, -- browser push service URL
p256dh text not null, -- client public key
auth text not null, -- client auth secret
user_agent text,
created_at timestamptz not null default now()
);
-- Service-role-only config (RLS on, zero policies): VAPID keypair + notify function URL/key,
-- seeded directly into the live DB, never committed to the repo.
create table app_config (
key text primary key,
value jsonb not null
);
```
Why the move list (not a state blob) is the source of truth: locked §A decision — the engine
is deterministic from `seed + moves`, so `games` + `moves` reconstruct everything, the log is
auditable, and no server code ever has to understand game state. `current_seat` / `move_count`
/ `status` on `games` are **denormalized copies for the lobby and the notification trigger
only** — the client never uses them for enforcement (the replayed engine is authoritative;
see §4).
### Write path: RPCs only (this is what makes the log append-only)
No direct `insert/update` policies exist on `games`/`players`/`moves`. All writes go through
three `security definer` functions, so append-only isn't a convention — it's the only door:
- `create_game(name, seed, player_count, options, invites jsonb)` — inserts the `games` row +
one `players` row per invite `{email, seat, display_name}`. Asserts the caller's own email
is among the invites (the host always plays; no spectator-only role in v1) and that seats
are exactly `0..player_count-1`.
- `claim_my_seats()` — `update players set user_id = auth.uid() where user_id is null and
invited_email = lower(auth.email())`. Called by the client after every sign-in; this is the
entire "accept invite" step.
- `commit_turn(game_id, seq, seat, move, next_seat, finished)` — the only way a move row is
born. Asserts: caller's `auth.uid()` owns `seat` in this game; `games.status = 'active'`;
`seq = games.move_count + 1`. Then, atomically: insert the `moves` row and update
`games.move_count / current_seat / status`. A concurrent/stale commit fails the `seq`
assertion (or the PK), and the client resyncs — no lost or reordered turns possible.
## 2. Invite flow & auth
- **Auth = Google sign-in (primary) + Supabase magic links (fallback).** `SignIn.vue` shows a
"Sign in with Google" button (`signInWithOAuth({ provider: "google" })`) with the magic-link
form (`signInWithOtp`) underneath for anyone whose invite email isn't a Google account. Both
identify the player by their verified email, so everything downstream is unchanged. The
Supabase client persists the session (localStorage) and auto-refreshes tokens, so it really is
**sign in once per device** — see §13.5 for the one-time Google OAuth setup the owner does.
- Host fills in the create-game form: game name, options (incl. `lostFleet`), and the friends'
emails in **seat order** (UI offers a shuffle button; seed is generated once client-side and
stored — §J3). Seat index = engine player index; everything downstream (faction pick order,
auction, in-game turn order) is the engine's business via normal committed moves.
- **Invitees must already have an account** (§12): `create_game` rejects any invited email that
isn't in `auth.users`, so a typo can't orphan a seat that nobody can ever claim. Friends sign
in once (Google or magic link), then the host can seat them. Opening the game link →
`claim_my_seats()` matches their email to their seat(s) → the game loads with their seat locked.
- Invite-only enforcement is RLS (§5): a stranger who signs in sees zero rows. No public
matchmaking, no anonymous play (locked decision).
## 3. Turn order & locking (the §J2 case)
- **Client-side (enforcement):** after loading, the hosted entry point finds the caller's
`players` row and emits `emitter.emit("player", { index: seat })` — the one thing
`self-contained.ts` never does. From there the _existing_ chain does all the work:
`launcher.ts:41` → `store.state.player` → `Game.vue:272` `canPlay` compares the session
seat against `engine.playerToMove`. Because `playerToMove` returns `tempCurrentPlayer`
during pending leech/charge decisions (`engine.ts:588-594`), a mid-turn interrupt
automatically unlocks the interrupting player's browser and locks everyone else's —
**zero new turn-order logic is written; §J2 is satisfied by the engine itself.**
- **Server-side (display + notifications):** `commit_turn`'s `next_seat` parameter is
`copy.playerToMove` computed by the committing client from the post-move engine (null +
`finished=true` when `copy.phase === EndGame`). It feeds the lobby's "whose turn" column and
the email trigger. Trust model: clients are trusted to report it honestly (friends group;
the engine replay is always the real authority, so a wrong `current_seat` can misdirect an
email at worst, never corrupt a game).
## 4. Realtime sync & catch-up
- **Boot (fresh load / reconnect):** fetch the `games` row + `players` + all `moves` ordered
by `seq`, then `new Engine(["init ${player_count} ${seed}", ...moves.map(m => m.move)],
games.options)` + `generateAvailableCommandsIfNeeded()` — the same construction as
`self-contained.ts:104`, just fed from the database. Stamp `engine.players[seat].name =
display_name` for display, then emit `"state"`.
- **Live:** one Supabase Realtime channel per game, `postgres_changes` INSERT on `moves`
filtered by `game_id` (RLS-authorized via the user's JWT). Handler:
- `row.seq <= localCount` → skip (it's our own commit echoing back, or already applied).
- `row.seq === localCount + 1` → clone engine (`Engine.fromData`), `copy.move(row.move)`,
emit `"state"`.
- gap (`row.seq > localCount + 1`) or any apply error → **full resync** (refetch all moves,
rebuild). Resync also runs on channel rejoin after disconnect and on tab re-focus, so a
laptop waking from sleep catches up without a reload.
- **Commit (replaces `self-contained.ts`'s `emitter.on("move")` body, same skeleton):**
```ts
emitter.on("move", async (move: string) => {
const copy = Engine.fromData(JSON.parse(JSON.stringify(engine)));
if (move) {
copy.move(move);
copy.generateAvailableCommandsIfNeeded();
if (copy.newTurn) { // §J1/§A2: only a completed turn leaves the browser
await rpc("commit_turn", { game_id, seq: localCount + 1, seat: mySeat, move,
next_seat: ..., finished: ... });
// success → engine = copy; seq-conflict/failure → full resync + error toast
}
}
emitter.emit("state", JSON.parse(JSON.stringify(copy))); // partial moves render locally only
});
```
Incomplete turn lines never reach the network, so **undo within your own turn stays free
and invisible to others** (§A2), exactly as today. Undo of an already-committed turn is not
supported in v1 (matches §A2's definition of commitment).
## 5. Row-level security
RLS enabled on all three tables. One membership predicate, used everywhere
(as a `security definer` helper `is_member(game_id)` to avoid recursive-policy issues):
> the caller has a `players` row in this game with `user_id = auth.uid()` > **or** `invited_email = lower(auth.email())` (so invitees can see the game pre-claim).
- `games`: SELECT for members. No INSERT/UPDATE/DELETE policies (writes only via the RPCs).
- `players`: SELECT for members of the same game. No direct writes.
- `moves`: SELECT for members. No direct writes — append-only is structural (§1).
- Realtime `postgres_changes` respects these SELECT policies, so move broadcasts only reach
seated players. `moves` is added to the `supabase_realtime` publication in the migration.
## 6. Turn notifications — Web Push (§J4 as AMENDED by owner ruling 2026-07-01)
> Original plan was email-first per the old §J4; the owner overruled it on review: **push
> notifications only, no turn-change emails** (owner doesn't check email / doesn't want spam).
> §J4 in RULES_CLARIFICATIONS.md carries the amendment. The only emails left in the system are
> Supabase Auth's built-in magic-link sign-in emails. Upside: no third-party email provider,
> no domain verification — Web Push is free and provider-less (browser push services + VAPID).
- **Subscriptions:** a `push_subscriptions` table (user_id, endpoint unique, `p256dh`/`auth`
keys, plus `user_agent`). The viewer registers a service worker and, on an explicit "Enable
notifications" button (permission prompts require a user gesture), calls
`pushManager.subscribe()` with the VAPID public key and upserts the subscription. Per-user,
multi-device.
- **Trigger:** Postgres trigger (`pg_net`) on `games` INSERT (invites) and UPDATE of
`current_seat`/`status` → HTTP POST `{game_id, type}` to Edge Function `notify`. The
function URL + anon key live in an `app_config` table (RLS on, no policies → service-role
only), so nothing project-specific is hardcoded in the committed migration.
- **`notify` Edge Function** (`supabase/functions/notify/`): service-role reads of
`games`/`players`/`push_subscriptions` + the VAPID keypair from `app_config`; sends
**"Your turn in <game>"** push (deep link `?game=<id>`) to every subscription of the seat
now on turn, skipping when that user _is_ the committer (`games.last_committed_by`); on
`finished`, pushes final-scores to everyone; on game creation, pushes an invite notice to
invitees who already have accounts+subscriptions. Dead subscriptions (HTTP 404/410 from the
push service) are deleted. It never runs the engine — everything it needs is denormalized
on `games`.
- **Accepted caveats (owner acknowledged):** iOS needs the viewer installed to the home screen
as a PWA (iOS 16.4+) before push works; each device grants permission once; a player with no
subscribed device gets no notification (game unaffected). First-time invitees can't receive
an invite push (no account yet) — the host shares the game link out-of-band once. Turn pushes
now stay aggressive on desktop subscriptions even when that player already has the game open,
while mobile/PWA subscriptions are suppressed **only by that phone's own report** that it has this
very game open (see per-device presence below).
- **Per-device presence** (migration `20260808121000_per_device_push_presence`): the "already open"
suppression used to read `players.last_active_at`, which is **one row per seat**, shared by every
device that user is signed in on — so leaving the game open in a desktop tab kept it fresh forever
and silenced their **phone** as well, a device that was in a pocket with the screen off
(owner-reported). Presence is now recorded on the subscription instead:
`push_subscriptions.active_game_id` (the game this device has open right now, null = none) and
`active_at` (when it last reported **either way**), written by `mark_device_viewing()` from the
same ~20s heartbeat tick as `mark_seat_active` — but also while the tab is _hidden_, since that
report is exactly what re-enables pushes. `notify/logic.ts::shouldSkipTurnPushForSubscription` then
withholds a mobile push only when that subscription itself says this game is open and the report is
fresh; a device that has **never** reported (a client older than the migration) still falls back to
the old per-player signal, so it can't start double-alerting the person actually playing on it, and
self-corrects the first time that device loads a game. Desktop is never withheld, unchanged.
- **Auction bid-phase pushes** (migration `20260808120000_auction_bid_notifications`): the Preference
Split Auction bids simultaneously, into `auction_sealed_bids` rather than `public.moves`, so
`current_seat` never moves and the trigger above fired for exactly one of the four players. An
announcement (`announce_sealed_bid_auction()` → `games.sealed_bid_announced_at` →
`games_notify_sealed_bid_auction` → `{type:'auction_bid'}`) pushes to everyone who still owes a
bid, and the sweep re-nudges them per **seat** (`auction_bid_reminders`) rather than per game.
Full write-up in `PREFERENCE_SPLIT_AUCTION.md`'s "Notifications during the auction".
- Known cosmetic wart, accepted for v1: a leech chain produces a couple of rapid turn-change
pushes. Fine for a friend group; debounce later if it annoys.
- **Recurring turn reminders** (migration `20260721000000_turn_reminders`): the one-shot "Your turn"
push only fires the instant the seat changes. A separate hourly `pg_cron` job re-invokes `notify`
with `{type:'reminder_sweep'}` (same `app_config['notify']` URL/key pattern as the trigger, so
still no hardcoded secrets and still a no-op until seeded). The sweep finds every active game whose
current player has let their turn sit idle past **12h** and re-sends **"Still your turn in
<game>"** (same `turn-<id>` tag so the OS replaces rather than stacks). It re-nudges every 12h,
**capped at 3 per turn**, and never during the recipient's **local night** (only while their local
hour is in `[8, 22)`; a nudge due at night is deferred to the next daytime sweep). Per-turn state
lives in new `games.last_turn_reminder_at` / `games.turn_reminder_count` columns; the count resets
implicitly once the player moves (any reminder stamped before `latest_move_committed_at` is treated
as belonging to the previous turn — no `commit_turn` change needed). Quiet hours use a new
per-device `push_subscriptions.tz` (IANA zone captured at subscribe time); a player with no known
timezone is never suppressed, and a player with no subscribed device is skipped entirely (never
stamped). The pure per-game decision is `notify/logic.ts::planTurnReminder`; `index.ts` does the IO.
- **Global notification preferences** (migration `20260721010000_notification_prefs`): a per-user
`notification_prefs` row (RLS own-row; the notify function reads it with the service role) is the
single, account-wide control set — applied to every game and every device, edited from the bell
button's settings modal (`NotificationSettings.vue`). A **missing row = defaults**
(`DEFAULT_NOTIFICATION_PREFS`): every category on, and **`reminders_enabled` defaults true** — the
recurring 12h reminder is on by default and users opt out. Fields: per-category toggles (`turn`/`chat`/`invite`/`finished`),
`reminders_enabled` + `reminder_interval_hours` (12/24/48) + `reminder_max_count`, `quiet_hours_enabled`
- `quiet_start_hour`/`quiet_end_hour` (a midnight-wrapping window, replacing the old fixed 8am–10pm),
and `snooze_until` (suppresses **all** pushes until it passes). The trigger path gates each one-shot
push by category + snooze (`isNotificationAllowed`); the sweep passes prefs into `planTurnReminder`
(interval/cap/quiet/snooze). Whether a _device_ is subscribed at all stays per-device
(`push_subscriptions`) — that's the modal's top switch; everything else is global.
## 7. Viewer integration
- **New files** (nothing existing is removed; `self-contained.ts` keeps working untouched):
- `viewer/src/hosted.ts` — the Supabase-backed counterpart of `self-contained.ts`: auth →
`claim_my_seats()` → load game → emit `"player"` + `"state"` → the `"move"` handler from
§4 → realtime subscription. Also answers `"fetchState"` by re-emitting current state
(launcher.ts:35-38 expects that).
- `viewer/src/hosted/` — thin supabase client wrapper (reads `VUE_APP_SUPABASE_URL` /
`VUE_APP_SUPABASE_ANON_KEY`), sign-in form, and a minimal bootstrap-vue lobby: list my
games (name / status / whose turn / my seat), create-game form (§2).
- **Mode selection** in `main.ts`: `?game=<uuid>` or `?lobby=1` → hosted mode; anything else →
the existing self-contained launcher. One static Vercel build, all existing demo/scenario
URLs keep working; the only deploy change is two env vars on Vercel.
- **Events used, all pre-existing:** `"player"` (seat lock), `"state"` (full load — launcher
already derives `replaceLog`/gamelog from it at `launcher.ts:30-34`, so the separate
`"gamelog"` hook needs no new wiring), `"move"` (commit path), `"fetchState"` (re-serve).
- **Toolchain risk, known up front:** `@supabase/supabase-js` v2's `.d.ts` wants TS ≥ 4.x;
the viewer pins TS 3.9. The production build already runs ts-loader `transpileOnly`
(`vue.config.js`), so builds are unaffected; if `tsc` complains, add `skipLibCheck` to
`viewer/tsconfig.json` (which also silences the pre-existing `@types/lodash` noise
documented in PROGRESS.md "Done so far" #3). Fallback if that somehow isn't enough:
isolate all supabase imports behind one wrapper module.
- **Tests** (per the standing testing agreement): unit tests for the hosted move handler with
a mocked supabase client — commits on `newTurn` only, never commits partial lines, resyncs
on seq conflict, applies realtime rows in order, full-resyncs on gaps. Same style as
`self-contained.spec.ts`.
## 8. Snapshot cache — deliberately Phase 2, and how it stays honest
Skipped in v1: the engine replays entire recorded games in the test suite in well under a
second, so a few hundred moves at boot is a non-problem at this scale. If load ever feels
slow, the reserved `games.cached_state` / `cached_state_moves` columns activate as follows:
`commit_turn` gains an optional serialized-engine param (best-effort, written by the
committing client); boot becomes `Engine.fromData(cached_state)` + apply moves with
`seq > cached_state_moves`. **Honesty rules:** the cache is never authoritative — the move
log always wins; any `fromData` error, or `cached_state.moveHistory.length !==
cached_state_moves + 1`, or `cached_state_moves > move_count` → discard cache, full replay;
`?replay=1` forces full replay for debugging. The cache can be nulled at any time with zero
data loss.
## 9. Delivery plan (each step = own tested commit on this branch, per repo convention)
1. Supabase project + migration (`supabase/migrations/0001_multiplayer.sql`: tables, RPCs,
RLS, realtime publication) + `docs` update.
2. `hosted.ts` boot path: auth, claim, load-and-replay, `"player"`/`"state"` emit, seat lock
verified end-to-end (two browsers, one game).
3. Commit path + realtime fan-out + resync (+ the unit tests from §7).
4. Lobby (create game / invites / list games).
5. `notify` Edge Function + trigger (turn emails + invite emails + finished emails).
6. PROGRESS.md updates as each piece lands.
## 10. Open questions — RESOLVED (owner, 2026-07-01: "whatever you recommend is fine", plus
the push-over-email override)
- **Q1 — Notifications:** owner overrode the email plan → **Web Push only** (see §6 and the
§J4 amendment). No email provider, no domain needed.
- **Q2 — Supabase project:** created fresh free-tier project **`gaia-lost-fleet`**
(ref `mitawjpdxkheascdiffz`, region `eu-west-1`, same org/region as the owner's existing
unrelated project, which was left untouched).
- **Q3 — Lobby scope:** minimal lobby (sign-in, list, create) confirmed for v1.
- **Q4 — Display names:** host types friends' names at invite time.
- **Q5 — Post-commit undo:** out of scope for v1.
- Design is **settled**; implementation proceeds in the §9 steps (with §6 swapped to push).
## 11. Deployment status (2026-07-01) & the two remaining owner actions
**Live right now:**
- Supabase project `gaia-lost-fleet` (ref `mitawjpdxkheascdiffz`, eu-west-1, free tier).
- Both migrations applied (schema, RPCs, RLS, realtime publication, notify trigger); security
advisors clean apart from the intentionally-callable RPCs.
- `app_config` seeded with the VAPID keypair (subject `mailto:kim.pham.nguyen2@gmail.com`,
`site_url` `https://gaia-lost-fleet.vercel.app`) and the notify URL/key. The private VAPID key
exists ONLY there.
- Viewer hosted mode on branch `claude/backend-state-multiplayer-sbhf6c-bov526` — deliberately
NOT merged to `master` (auto-deploys to production) pending owner review.
**Owner actions (~5 minutes total):**
1. **Deploy the `notify` Edge Function** (the session's MCP deploy call was approval-gated).
Either from the repo root:
`npx supabase login && npx supabase functions deploy notify --project-ref mitawjpdxkheascdiffz`
or paste `supabase/functions/notify/index.ts` into Dashboard → Edge Functions → Deploy new
function, named exactly `notify`, with "Verify JWT" **enabled**. Until deployed, games are
fully playable — the trigger's async HTTP call 404s harmlessly; no push arrives, nothing else
is affected. (`deno check` passes on the file; the seeded VAPID keys were verified to import
and to match the viewer's committed public key.)
2. **Supabase Auth URL configuration** (Dashboard → Authentication → URL Configuration):
set Site URL to the real production domain (assumed `https://gaia-lost-fleet.vercel.app` —
verify in Vercel) and add redirect URLs `https://gaia-lost-fleet.vercel.app/*` and, for local
dev, `http://localhost:8080/*`. Without this, magic-link emails redirect to the default
`http://localhost:3000`.
**If the production domain differs** from `https://gaia-lost-fleet.vercel.app`, fix the deep-link
base once in SQL:
`update app_config set value = jsonb_set(value, '{site_url}', '"https://REAL-DOMAIN"') where key = 'vapid';`
**Key rotation note:** the anon key and VAPID public key are committed in
`viewer/src/hosted/config.ts` (public by design). Rotating VAPID keys = regenerate a P-256 JWK
pair, update `app_config['vapid']` and the viewer config, and every device must re-enable
notifications.
## 12. End-to-end verification harness (2026-07-01)
`viewer/e2e/hosted-multiplayer.e2e.js` drives **two real Chromium browsers against the live
production deployment and the real Supabase project**: lobby boot with a stored session,
game creation through the real form, seat locking on both sides, faction picks through the
real Commands UI, realtime fan-out to the other browser without a reload, and reload-resume
from the stored move log. Run instructions are in the file header. Supporting pieces:
- **Test accounts:** two throwaway password users exist in the project's auth
(`e2e-alice@lostfleet.test` / `e2e-bob@lostfleet.test`), created via SQL insert into
`auth.users`/`auth.identities` specifically so the harness can sign in WITHOUT the
magic-link flow (sessions are minted via `POST /auth/v1/token?grant_type=password` and
seeded into the browsers' localStorage). They see only their own games under RLS. Delete
them (and any `E2E %`-named games first) if you ever want them gone.
- **`viewer/e2e/proxy-network.js`:** optional network adapter (`E2E_NETWORK=intercept`) for
sandboxes whose TLS-intercepting egress proxy kills Chromium's post-quantum ClientHello
(X25519MLKEM768 — not disableable in the Playwright headless shell). It fulfills every
HTTP(S) request via Playwright's Node-side request API and bridges WebSockets (Supabase
Realtime) over a manual CONNECT tunnel, so the browser never performs TLS itself.
- **First catch:** the harness immediately found a real production bug — the Engine mutates
the options object it's given (stamping the generated `map` into it), Lobby persisted that
mutated object, and `moveInit` rejects `map.sectors` + `lostFleet` on replay, bricking the
game. Fixed in `buildCreateGameParams` (`viewer/src/hosted/new-game.ts`) + option-cloning
in `HostedGameHost.buildEngine`, with unit regression tests.
## 13. Test mode, player counts & registered-only invites (2026-07-02)
Three related changes, migration `supabase/migrations/0003_test_mode_and_player_counts.sql`
(applied live to project `mitawjpdxkheascdiffz`) plus viewer wiring. All verified end-to-end
against the live backend (create → enter → play both seats → reload → persistence in `moves`).
### 13.1 Player counts are 2-4, not 2-5
Gaia Project — base game or Lost Fleet — has no 5-player board (the Lost Fleet sector layouts
and Interspace tile sets stop at 4p). The original `check (player_count between 2 and 5)` and the
lobby's `[2,3,4,5]` select were wrong. Migration tightens the `games` check to `between 2 and 4`
and `create_game` to reject >4; `Lobby.vue` offers `[2,3,4]`.
### 13.2 Test mode = one account holding every seat (hot-seat)
For solo testing of the _hosted_ path (commits, realtime, resync, persistence) without waiting
on friends. Rather than a client flag that bypasses seat locks — which would skip the very
backend machinery worth testing — a "test game" is a **real** game where the creator's email
occupies all seats:
- Migration drops `unique (game_id, invited_email)` and relaxes `create_game`'s "each seat needs
a distinct email" to "each seat needs an email" (duplicates allowed). `commit_turn` already
checks seat ownership per seat and `claim_my_seats` claims every matching seat, so nothing else
changed server-side.
- `Lobby.vue`: a "Test game — I control all seats" checkbox fills every seat with the creator's
own email; such games are tagged "test game" in the list (`isTestGame` = every seat owned by me).
- Seat locking (`host.ts` `seatToLock`, applied in `hosted.ts` `onState`): owning **all** seats →
no lock (hot-seat, `canPlay` stays true for whoever the engine says must act); owning **some**
seats → locked to whichever owned seat must act now, driven by `playerToMove` so leech
interrupts (§J2) unlock the right seat; owning **none** → no lock needed (RLS + `commit_turn`
re-check ownership, so an unlocked spectator UI still can't commit).
- Bonus: the `notify` function already skips pushing to the last committer, so a solo game won't
spam "your turn" pushes.
The general case (one person legitimately holding 2 of 4 seats among friends) now works too.
### 13.3 Invites restricted to registered users (§2 amendment)
`create_game` now rejects any invited email not present in `auth.users`, with a message naming
the offending address(es). This closes the silent-orphan-seat failure (a typo'd invite created a
seat nobody could claim, blocking the game). `Lobby.vue` warns up front that friends must sign in
once before they can be seated. This is why §2 auth matters: get everyone signed in first.
### 13.4 Stored-options map bug (fixed, was blocking game entry)
The lobby's create-game probe Engine **mutates the options object** it's given — the engine
writes the generated map into `options.map`. `create_game` persisted that mutated object, and the
engine's `init` **rejects a preset `map` combined with `lostFleet`** ("A custom map configuration
cannot be combined with the Lost Fleet expansion"), so every Lost Fleet game created this way was
unopenable. Fixes:
- `Lobby.vue` deletes `options.map` after probing, before the `create_game` RPC.
- `host.ts` `engineOptions()` strips `map` defensively on every boot (the seed regenerates it
deterministically), so already-stored legacy rows open too. Regression-tested in `host.spec.ts`.
- The one pre-existing broken row on the live DB was repaired in place (`options - 'map'`).
## 14. Delete games, pick-from-registered-users invites, dedicated create screen (2026-07-03)
Migrations `0006_delete_game.sql` and `0007_registered_user_invites.sql` — **written but NOT yet
applied to the live project** (this session had no Supabase MCP access; run them via the
Supabase CLI/dashboard, or a future session with `mcp__Supabase__apply_migration`, before relying
on any of this in production). All viewer-side changes are unit-tested (`Lobby.spec.ts`,
`CreateGame.spec.ts`, updated `new-game.spec.ts`) and the full `npm test` + `vue-cli-service
build` pass, but the actual Supabase RPCs could not be exercised end-to-end live in this session.
- **`delete_game(p_game_id)`** — new security-definer RPC, creator-only (`created_by = auth.uid()`
check), plain `delete from games` (players/moves cascade via existing FKs). `Lobby.vue` shows a
"Delete" button per game row only when `game.created_by === session.user.id`, gated by
`window.confirm`.
- **Invites are now "pick from registered users," not "type an email"** (§13.3 amendment):
- New **`list_registered_users()`** RPC (security definer, `authenticated`-only) returns
`(id, email, display_name)` from `auth.users`, `display_name` derived from Google's
`raw_user_meta_data.full_name`/`.name`, falling back to the email's local part.
- `create_game`'s `p_invites` shape changed from `{email, seat, display_name}` to
`{user_id, seat, display_name}` — same 7-argument signature (`text,text,int,jsonb,jsonb,int,
text`), so this is a straight `create or replace`, not a new overload (unlike §J4's cautionary
tale — no argument _types_ changed, only the jsonb keys inside one of them).
`invited_email` is still populated (resolved server-side from the matched `auth.users` row) so
`host.ts`'s `mySeats()`/`is_game_member`'s email-fallback matching, and `claim_my_seats()`,
keep working unchanged for both old and new rows. Duplicate `user_id`s across seats are still
allowed (test games — see §13.2).
- `CreateGame.vue` (new component, see below) queries `list_registered_users()` on mount and
renders the _other_ registered users (host excluded) as a capped checkbox list — check up to
`playerCount - 1`, further checkboxes disable once the cap is hit. No manual seat-by-seat
email typing anymore; "Shuffle seat order" still exists, now shuffling the picked-user-id list.
- **Create-game is now its own screen, not an inline section of the lobby.** `Lobby.vue` was split:
it now only renders the game list + delete + a `<a href="?create=1">+ New game</a>` link; the
old inline form (player count, test-game toggle, invites, `SetupPreview`, submit) moved to a new
`viewer/src/hosted/CreateGame.vue`. Routing stays consistent with the rest of this app (no Vue
Router in use, see §2/§9's query-string branching): `main.ts` now also treats `?create=1` as a
hosted-mode URL, and `hosted.ts`'s `launchHosted()` branches on it to mount `CreateGame` instead
of `Lobby`. **This intentionally is NOT a literal `window.open()` new browser window** — that's
unreliable on iOS Safari (popup blocking) and breaks PWA continuity; "a whole new window to do
your setup stuff" was implemented as a dedicated full-screen view instead, consistent with how
every other screen in this app already works (full navigations via `href`/`window.location`, no
in-page modals). Revisit if a literal new window/tab is still wanted.
- The game-name text field was dropped entirely per owner request — `buildCreateGameParams`
always sends `p_name: ""` now; the lobby already falls back to "Unnamed game".
- Player count is 3 buttons (`2`/`3`/`4`) instead of a `<select>`.
- **No-zoom on Lobby + CreateGame only.** There's one shared `index.html`/`<meta name="viewport">`
for the whole SPA (§ above, no per-route HTML). New `viewer/src/hosted/viewport.ts` exports
`setViewportZoomLocked(locked)`, which mutates that meta tag's `content` in place.
`hosted.ts`'s `launchHosted()` calls it with `true` right before mounting `Lobby`/`CreateGame`,
and `false` right before `launchGame()` — so the actual game board keeps normal pinch-zoom
(useful for the map), only these two screens lock it. Since every "navigation" in this app is a
full page load (`href`/`window.location.search`), there's no stale-state risk between screens.
### 13.5 Google OAuth — the owner's one-time setup (~10 min)
Needed once for the "Sign in with Google" button; magic link works without it.
1. **Google Cloud Console** → create/select a project → _APIs & Services → OAuth consent screen_:
External, add your email as a test user (or publish). Then _Credentials → Create OAuth client
ID → Web application_. Authorized redirect URI:
`https://mitawjpdxkheascdiffz.supabase.co/auth/v1/callback`. Copy the Client ID + secret.
2. **Supabase Dashboard** → _Authentication → Providers → Google_: enable, paste the Client ID +
secret, save.
3. Confirm _Authentication → URL Configuration_ has the site + redirect URLs from §11.2
(`https://gaia-lost-fleet.vercel.app/*` and `http://localhost:8080/*`).
Until step 1-2 are done the Google button returns a provider error; the magic-link fallback is
unaffected.

View file

@ -0,0 +1,106 @@
# Codex Handoff
This note exists so Codex can resume work quickly without re-reading the whole repo history.
The user switches between Claude Code and Codex on this project, so keep this current whenever a
session ends — it's the fastest on-ramp for whichever tool picks up next.
## Working Assumptions
- The user switches between Claude Code and Codex; treat the repo as shared with another session
unless `git status --short --branch` is clean.
- **Do active code work on `master`.** As of 2026-06-29 there is no separate long-lived feature
branch — `claude/lost-fleet-viewer-support-95lled` was fully absorbed into `master` and is kept
only as a historical ref.
- **If your local clone is missing files this doc references** (itself, `PERFORMANCE.md`,
`AGENTS.md`, or `viewer/src/components/SpaceMap.spec.ts`), your local `master` is stale — run
`git fetch origin && git pull origin master` before reading anything else. `master` was
deliberately left untouched for most of this project's history (all work happened on feature
branches), so an old local clone of `master` can predate huge amounts of work that's been on
`origin` for a long time. This has already bitten one handoff — see `PROGRESS.md` #37/#38.
- `master` is also the Vercel production deploy target, so every push goes live immediately. This
is an accepted tradeoff for a single-branch, single-contributor workflow, not a bug to fix.
- 7 superseded branches still exist on `origin` (`claude/lost-fleet-advtech-tiles-c2fo8w`,
`claude/lost-fleet-engine-work-l3bzsk`, `claude/spaceship-boards-gameplay-opnt1p-t991fv`,
`codex/continue-lost-fleet-work`, `claude/lost-fleet-expansion-gedyrk`,
`claude/quirky-thompson-gt0n0h`, `claude/spaceship-boards-gameplay-opnt1p`). They have no unique
content left to cherry-pick but `git push origin --delete` fails with `HTTP 403` for this
session's credentials — deletion needs the user's own GitHub access. Don't pull work from them.
## Resume Checklist
1. Run `git status --short --branch` and confirm you're on `master`. If your local `master` is
stale, `git fetch origin && git pull origin master` before editing.
2. Read `docs/lost-fleet/PROGRESS.md` in full — start with its **Working agreements** section
(standing instruction, not optional), then the "Done so far" list and "Next actions".
3. Read `docs/lost-fleet/RULES_CLARIFICATIONS.md` and `COMPONENTS.md` if the task touches Lost
Fleet rules or implementation.
4. Read `docs/lost-fleet/PERFORMANCE.md` before touching viewer rendering.
5. Confirm the next unit of work against `PROGRESS.md`'s "Next actions" before editing — it asks
to confirm with the user first.
## Current Snapshot (as of 2026-06-30)
- Lost Fleet chunks 1-7b, Darkanians' Planetary Institute, the full Explore/federation/Standard-Tech
claim hooks, all 12 Spaceship Board actions (live gameplay wiring complete), claimed-ship
Federation token gold-side execution + rescoring, Space Giants' Exploration special action, the
Scoring Board Extension's alternate Advanced Tech gate, the 6 Lost Fleet Advanced Tech tiles, and
Examine Artifact + Artifact-token seeding are implemented and tested.
- Tinkeroids and Moweyds are now fully wired in the engine: setup-stage PI/mine placement, the
shared Terraforming-board 3-step color assignment, Tinkeroids' round-start Tinkering tile choice,
Moweyds' pre-seeded T F Mars shuttle, Moweyds' Power Ring action, and the home-Protoplanet
0-VP correction for Moweyds / Space Giants are all coded and covered.
- Engine: **490/490** tests passing (`cd engine && npm test`). Viewer: **168/168** tests passing
(`cd viewer && npx vue-cli-service test:unit --timeout 4000 'src/**/*.spec.ts'
'src/logic/**/*.spec.ts'`).
- "Viewer Step Zero" is done: the viewer builds and type-checks clean against the Lost Fleet engine
(the 6 `Object.values(Faction)` call sites and related gaps are all fixed).
- Lost Fleet map rendering has started: `SpaceMap.vue` now renders Interspace / Deep Space hexes
directly from `engine.map.grid`, `SpaceHex.vue` distinguishes Lost Fleet sector types and spaceship
tiles visually, and `SpaceMap.spec.ts` has a real Lost Fleet smoke test alongside the base-game one.
- Lost Fleet self-contained viewer links now work: `self-contained.ts` accepts `lostFleet=1`, and
`FactionWheel.vue` now surfaces Asteroid / Protoplanet when Lost Fleet is active. Concrete demo
seed: `?players=2&seed=lost-fleet-space-map&lostFleet=1`.
- Darkanians and Space Giants now correctly get only 1 setup placement in Lost Fleet's expansion-
faction stage (after base-game factions finish their normal setup, before Ivits), and the viewer
now uses Asteroid=pink / Protoplanet=turquoise.
- Lost Fleet viewer ship actions now render in a compact horizontal strip that reuses the base
board-action tile footprint, grouped by ship with faction-colored access markers; the separate
Lost Fleet rewards board now only carries the seeded tech / federation / artifact state.
- Lost Fleet player pieces now render with the correct Asteroid / Protoplanet faction pairing
independently of the underlying hex colors: Tinkeroids + Darkanians use the Asteroid-side player
color, while Moweyds + Space Giants use the Protoplanet-side player color. The shared `Planet.vue`
paths also now have real Asteroid / Protoplanet SVG class coverage, and `SpaceMap.spec.ts` locks
the split with a real render case.
- Lost Fleet map polish has advanced one more slice: Interspace and Deep Space hexes now render
explicit `IS` / `DS` map badges, spaceship hexes have clearer orbit-ring ship markers, and
`SpaceMap.vue` carries a lightweight Lost Fleet legend so those map-only semantics are readable
without hovering each hex.
- The adjacent Lost Fleet UI now reuses the same ship-marker language as the map: the compact ship
action row and the separate ship rewards cards both show the same T/R/M/E markers in their
headers, and the render tests lock that shared treatment in place.
- The viewer no longer stalls on the last setup confirmation when Lost Fleet Tinkeroids are in the
game: `commands.ts` now renders `ChooseTinkeringTile`, `buttons/tinkering.ts` maps the 6 tile
choices into viewer buttons, and `Commands.spec.ts` covers the round-1 chooser regression.
- The Lost Fleet faction-picker now shows the correct faction colors during setup too: Tinkeroids +
Darkanians render the Asteroid pink dot, while Moweyds + Space Giants render the Protoplanet
turquoise dot, and `Commands.spec.ts` covers that chooser regression.
- The viewer is deployed to Vercel with Git integration; `master` auto-deploys on push and is the
production target.
- `CLAUDE.md` and `AGENTS.md` at the repo root both mirror this file's read order and current state
— they were rewritten from scratch on 2026-06-29 after being found stale (wrong branch name, dead
Windows path, old test counts). Keep all three in sync going forward.
## Next Likely Work
Per `PROGRESS.md`'s "Next actions", in priority order:
1. **Continue the new Lost Fleet UI work** — the map-rendering slice and the first compact
spaceship-action/rewards-board slice are done, the turquoise/pink player-piece treatment is done,
and the first richer map-polish pass is now done too; remaining viewer work is any further map
polish or panel/UI refinement beyond the current badges, legend, and ship-marker treatment.
2. **Revised Space Sector tiles 05/06/07** (§H4) — the one remaining art-only TODO; needs a photo
of the physical component.
3. Or a different unit of work entirely (viewer, Supabase).
Confirm with the user before starting any of the above — this is a standing instruction in
`PROGRESS.md`, not specific to this handoff.

View file

@ -0,0 +1,186 @@
# Lost Fleet — Components Inventory
> **Purpose:** Complete checklist of every physical component in _Gaia Project: The Lost Fleet_
> that must be represented in code. Seeded from the rulebook component list (p.2) plus components
> that only appear later as graphics. Track implementation status here.
>
> **Rulebook version referenced:** 1.0 (printed on p.11 of the rulebook PDF).
> **Errata status:** ☑ Checked 2026-06-25 — **no official errata/FAQ exists**; v1.0 rulebook is
> authoritative. See `RULES_CLARIFICATIONS.md` §K. Community forum threads still need human review.
> See https://boardgamegeek.com/boardgame/396802/gaia-project-the-lost-fleet (Files & Forums).
## Status legend
- `☐ TODO` — not started
- `◐ SPEC` — values captured in RULES_CLARIFICATIONS.md, not yet coded
- `● DONE` — implemented + base-game tests still green
- `[NEED FROM BOARD]` — value must be read off the physical component (not in rulebook text)
`◐ SPEC` for any tile/token/board means all three of: effect text, source, AND a planned digital
depiction are filled in over in `RULES_CLARIFICATIONS.md` (see "How to use this file" → "Art
policy" there) — not just the effect text alone.
---
## 1. New Factions (4)
| Faction | Start planet | Maps to | Status |
| ------------ | ------------ | ------------------------------------------------- | ------ |
| Tinkeroids | Asteroid | `Faction` enum + `faction-boards/tinkeroids.ts` | ● DONE |
| Darkanians | Asteroid | `Faction` enum + `faction-boards/darkanians.ts` | ● DONE |
| Moweyds | Protoplanet | `Faction` enum + `faction-boards/moweyds.ts` | ● DONE |
| Space Giants | Protoplanet | `Faction` enum + `faction-boards/space-giants.ts` | ● DONE |
Each new faction needs (see RULES_CLARIFICATIONS for values):
- Starting income row(s) `[NEED FROM BOARD]`
- Starting resources + starting power Area I/II distribution `[NEED FROM BOARD]`
- Standard-planet terraform cost layout `[NEED FROM BOARD]`
- Passive ability (text in rulebook p.13)
- Planetary Institute ability (text in rulebook p.13)
- Note: opposite-faction/home-planet pairing logic — these factions have NO home planet,
which breaks the base `oppositeFaction()` assumption in `factions.ts`. Flag in clarifications.
## 2. New Planet Types (2)
| Planet | Rule | Maps to | Status |
| ----------- | ---------------------------------------------------------- | ------------- | ------ |
| Protoplanet | 3 terraform steps; +6 VP on mine (0 VP if starting planet) | `Planet` enum | ● DONE |
| Asteroid | requires sacrificing a Gaiaformer; no build cost | `Planet` enum | ● DONE |
- New "11 planet types" symbol replaces the base "different planet types" symbol — affects
the `PlanetType` final-scoring and any planet-type counting logic.
- The 11th type in that symbol is the EXISTING base-game "Lost Planet" (gained at Navigation Level 5)
— not a new physical token, just newly counted. Confirmed via rulebook text + the randomizer's
`lostplanet.png` asset. See RULES_CLARIFICATIONS.md §G4b.
## 3. Lost Fleet Spaceship Boards (4)
> These are the board-game "Spaceship Boards", NOT the single-hex spaceship tiles on the map.
| Spaceship | Special note | Status |
| -------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Twilight (Nautilaks) | Holds Artifacts; "Examine Artifact" action | ● Board data + setup ● DONE (`spaceships.ts`, `setup.ts`); core Explore action/state ● DONE; federation-claim ownership hook ● DONE; claimed-token gold-side execution ● DONE; QIC action (re-score owned Federation token) ● DONE; Knowledge action (1k → +3 range for Build a Mine/Gaiaforming/Exploring) ● DONE; Power action (3pw,2o → upgrade a Trading Station into a Research Lab) ● DONE; Artifact-token seeding + Examine Artifact action ● DONE |
| Rebellion (Vo'Kron) | NOT used in 2-player games | ◐ Board data + setup ● DONE (`spaceships.ts`, `setup.ts`); core Explore action/state ● DONE; federation-claim ownership hook ● DONE; claimed-token gold-side execution ● DONE; Standard-Tech claim hook ● DONE; QIC action (claim Tech tile) ● DONE; Knowledge action (2k → 2c+1q) ● DONE; Power action (3pw,1o → upgrade a Mine into a Trading Station, ignoring isolation) ● DONE |
| T F Mars (Gaia Federation) | Moweyds start with a shuttle here | ◐ Board data + setup ● DONE; core Explore action/state ● DONE; federation-claim ownership hook ● DONE; claimed-token gold-side execution ● DONE; Standard-Tech claim hook ● DONE; QIC action (VP scaled by owned Tech tiles) ● DONE; Power action / Instant-Gaiaforming (2pw → convert a Transdim planet in range, QIC-for-extra-range, into Gaia, no building placed) ● DONE; Credit action (3c → terraform + build a Mine in range, ore for steps beyond the first) ● DONE |
| Eclipse (Eridani Empire) | — | ◐ Board data + setup ● DONE; core Explore action/state ● DONE; federation-claim ownership hook ● DONE; claimed-token gold-side execution ● DONE; Standard-Tech claim hook ● DONE; QIC action (VP scaled by colonized planet types) ● DONE; Power action (3pw,2k → free research upgrade) ● DONE; Credit action (6c → free Mine on an Asteroid in range) ● DONE |
Each spaceship needs:
- Every action space on the board: type (Q.I.C. / Power / Knowledge / Credit), cost, effect, position
— ● DONE, see `engine/src/spaceships.ts` (`spaceshipBoards`). Live availability/execution wiring
(`available/spaceship-actions.ts`, `move/spaceship-actions.ts`, `engine.spaceshipActions` per-round
lock) is ● DONE for all 12 of 12 actions (Twilight QIC + Knowledge + Power, Rebellion QIC + Knowledge
- Power, T F Mars QIC + Power + Credit, Eclipse QIC + Power + Credit). Separately, and not
counted in the 12, claimed ship Federation tokens' gold-side execution is now ● DONE for all 8
tokens (`player.ts` direct rewards for 6, `available/federations.ts` +
`move/federation.ts`'s `SubPhase.FederationTokenBuildMine` chain for Range/Terraform's bonus Build a
Mine). Rescoring (QIC2 board action) is also ● DONE for ship-claimed tokens — they're offered in the
rescore list alongside pool-drawn tokens and re-trigger their gold-side effect uniformly, same as
pool tokens (`available/federations.ts`, `move/federation.ts`'s `rescoreSpaceshipFederationToken`).
Twilight's Examine Artifact action (`Command.ExamineArtifact`/`ChooseArtifactToken`, `move/artifacts.ts`)
and the Artifact-token setup seeding are now also ● DONE, so every Spaceship-Boards-adjacent action
is live (kept as 2 separate commands rather than a 4th `SpaceshipActionType`, since `spaceships.spec.ts`
hard-asserts exactly 3 actions per ship).
- Number of standard-tech slots — ● DONE: 0 (Twilight, has no Standard Tech slot at all), 1 each for
Rebellion/T F Mars/Eclipse. Confirmed via owner board photos, see RULES_CLARIFICATIONS.md §C1/§C4.
- Which new federation token + standard tech is seeded onto it at setup — ● DONE, random
setup-time assignment implemented in `engine/src/setup.ts` (`shipAssignmentFactory`); only the
_seeding_ was the first slice; redemption hooks are now live for seeded Standard Tech tiles and
Federation tokens, while the ships' own action-space execution is still TODO.
- Core Explore action/state — ● DONE in engine (`exploration.ts`, `available/exploration.ts`,
`move/exploration.ts`): range from colonized planets only, Q.I.C. extension, 2-player vs. 3/4-player
shuttle limits, one shuttle per ship, lowest free slot, slot charge rewards `0/2/2/3`, Taklons /
Nevlas / Itars / Bal T'aks deploy adjustments, and serialization of per-player explored ships.
Remaining ship-board action execution / redemption hooks are still TODO.
- Federation-token claim hook — ● DONE in engine: when a player forms any federation, eligible
ship-seeded Federation tokens from explored ships are added to the selectable federation-token
choices, without requiring the ship to be adjacent to the formed federation. Claimed ship tokens are
persisted as owned federation tokens for count / green-side consumption; their special gold-side
action execution is now ● DONE too — Credit/Knowledge/OreQic/Tech/Vp/PowerTokens grant their reward
immediately on claim (`pl.gainSpaceshipFederationToken()`), Range/Terraform chain into a one-time
bonus Build a Mine action (`SubPhase.FederationTokenBuildMine`).
- Standard-Tech claim hook — ● DONE in engine: explored ships add their seeded Standard Tech tile to
the normal `Command.ChooseTechTile` options, claiming the tile removes it from the ship and stores it
as a normal coverable Standard Tech, and the normal follow-up free research advance still applies.
The 3 Lost Fleet Standard Tech tiles' own gameplay effects remain a later live-effect slice.
## 4. Exploration Boards (per faction, all 18 factions get one)
Core Explore action/status: ● DONE in engine for currently coded factions, including Moweyds' pre-seeded
T F Mars shuttle and Space Giants' once-per-round 2-step special action.
Each faction's Exploration board needs `[NEED FROM BOARD]`:
- Shuttle deployment cost (usually 5 VP; Bal T'aks 7 VP) — ● DONE in engine
- Faction-specific deploy adjustment (Taklons: Brainstone→Gaia; Nevlas/Itars: discard 1 power) — ● DONE in engine
- Number of shuttles (3 normally, 2 in 2-player) — ● DONE in engine
- Charge-power value at each numbered shuttle space (1–4) on the SPACESHIP board (see §3) — ● DONE in engine (`0/2/2/3`)
## 5. Exploration Shuttles
- 27 shuttles total (3 × 9 colors). Per-player-color piece. Status: ☐ TODO
## 6. Map Components
| Component | Count | Detail needed | Status |
| ----------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------- |
| Deep Space Sector tiles | 8 (double-sided) | Planet layout per side — CONFIRMED for all 16 faces, see RULES_CLARIFICATIONS.md §H2 (the 3rd hex motif on 12a/13a/17a is Transdim, resolved 2026-06-27). **Data CODED** in `engine/src/lost-fleet-map.ts` `DEEP_SPACE_TILES` (Chunk 5); **placement onto the board CODED** in `lost-fleet-board.ts` `placeDeepSpaceTiles()` (Chunk 6, incl. the 2p 11-16 restriction and the 3p adjacent-notch "larger gap" rule, which needs no special-casing — see §H1 note 4) | ● CODED |
| Interspace tiles | 30, in 4 player-count sets | per-set composition (asteroid/protoplanet/spaceship/blank counts) CONFIRMED, see RULES_CLARIFICATIONS.md §H3; exact tile-by-tile identity not needed (random placement). **Data CODED** in `lost-fleet-map.ts` `INTERSPACE_SETS`/`interspaceSet()` (Chunk 5); **placement onto the board CODED** in `lost-fleet-board.ts` `placeInterspaceTiles()` (Chunk 6, incl. ship identities via `shipsInPlay()` and the §H1 spaceship-spacing constraint via rejection sampling) | ● CODED |
| Revised Space Sector tiles | replaces base "different planet types" components | which planets on revised sides `[NEED FROM BOARD]` — §H4. Stubbed/flagged in `lost-fleet-map.ts` `REVISED_SECTOR_FACES_TODO` (`available: false`, falls back to base-game face); `lost-fleet-board.ts` uses the base game's matching per-count face (B-side 2p/3p, A-side 4p) as that fallback | ☐ TODO (stubbed) |
| Shifted-sector setup geometry | per player count (2/3/4) | encode the offset-placement layout (rulebook p.4-5). **CODED & verified** in `lost-fleet-map.ts` `lostFleetSectorCenters()` + `findInterspaceHoles()` + `findDeepSpaceNotches()` (Chunk 5): 6/8/10 single-hex Interspace holes, 6/8/8 Deep Space triangle notches, 0 overlap. **Full `Grid<GaiaHex>` assembly CODED** in `lost-fleet-board.ts` `generateLostFleetBoard()` (Chunk 6, plus a German-rules-adjacency reroll loop added in a later session) — sector tiles + Interspace + Deep Space all placed, seed-deterministic. The `GaiaHex` addressing bug that blocked wiring this into `SpaceMap` is now **FIXED** (Chunk 7a, `sectorCenter` stamped in `Sector.create()`). **Wired into the real `SpaceMap`/`moveInit` (Chunk 7b):** `SpaceMap`'s constructor takes a `lostFleet` flag and calls `generateLostFleetBoard()` directly when set, bypassing the base game's tile-shuffle/`isValid()`-reroll machinery; `configuration()`/`parse()` got Lost-Fleet-aware branches (real sector centers for `rotateSector()`, a fallback for `IS<n>`/`DS<tileId>_<n>` coordinate strings); `moveInit()` threads `engine.options.lostFleet` through and rejects combining it with a custom `map.sectors` configuration or `customBoardSetup`; `Engine.fromData()` restores `map.lostFleet` on deserialization. Covered by `map.spec.ts`'s "Lost Fleet" test block. | ● CODED |
## 7. Tiles & Tokens
| Component | Count | Detail | Status |
| ------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Standard Tech tiles (new) | 3 distinct types (1 in play per ship; rulebook's "4 each" is spare reprints) | exact effect of each type — CONFIRMED, see RULES_CLARIFICATIONS.md §G1 | ◐ SPEC |
| Advanced Tech tiles (new) | 6 | exact effects CONFIRMED for all 6 — RULES_CLARIFICATIONS.md §G2 (corrected 2026-06-27: "big" is PI/Academy-only, 6VP each max 18; the Deep Space clause belongs to the separate "deep" tile). **CODED & TESTED** (done 2026-06-29): `AdvTechTile.AsteroidPass`/`Big`/`Deep`/`DeepPass`/`QAction`/`Terra` in `enums.ts`, gated by `hasExpansion(.., LostFleet)` in `.values(expansions)`; effects wired via `tiles/techs.ts` DSL entries + new `Condition.Asteroid`/`DeepSpaceSector`/`SpaceshipQicAction` cases in `player.ts`; `qaction` additionally hooked into `move/spaceship-actions.ts`'s Q.I.C. ship action. `terra` separately audited (done 2026-06-29, PROGRESS.md "Done so far" #31) against every engine source of free terraforming steps (normal builds, Federation tokens' bonus Build-a-Mine, Space Giants' special action) — confirmed it fires on discounted/free steps too, not just paid ones, no bug found | ● CODED |
| Round Boosters (new) | 4 | income + pass bonus — CONFIRMED, see RULES_CLARIFICATIONS.md §G3 | ◐ SPEC |
| Round Scoring tiles (new) | 3 | text p.14 — CONFIRMED verbatim, see RULES_CLARIFICATIONS.md §G4 | ◐ SPEC |
| Final Scoring tiles (new) | 3 | "most asteroids", "PI–Academy distance", "most deep space sectors" — CONFIRMED verbatim, see RULES_CLARIFICATIONS.md §G4 | ◐ SPEC |
| Federation tokens (new) | 8 (gold outline) | exact effects CONFIRMED for all 8, see RULES_CLARIFICATIONS.md §G5; ALL 8 have a green side (standard base-game mechanic — only the base game's original 12-VP token lacks one), resolved 2026-06-27 | ◐ SPEC |
| Artifact tokens | 13 | effect CONFIRMED for all 13, see RULES_CLARIFICATIONS.md §G6; count of each type among the 13 inferred as 1-each, VERIFY `[NEED FROM BOARD]`. **All 13 effects CODED & TESTED** (`tiles/artifacts.ts`, `move/artifacts.ts`, `available/artifacts.ts`; setup seeding via `setup.ts`'s `scoringFactory`) — ⚠️VERIFY: the `ResearchLevel` token's Research Area (assumed `ResearchField.Science`) was never confirmed, the owner's rules-text comment was cut off mid-sentence | ● CODED |
| Gaia Planet tokens | 4 | additive to base supply | ☐ TODO |
| Action tokens | 12 | mark used spaceship action spaces | ☐ TODO |
| Tinkering tiles | 6 (Tinkeroids only) | effect of each CONFIRMED, see RULES_CLARIFICATIONS.md §B1 (rounds 1-3: terra 1 / charge 4pw / 1 Q.I.C.; rounds 4-6: terra 3 / 3 knowledge / 2 Q.I.C.) | ● DONE |
| Power Rings | 6 (Moweyds only) | +2 power value to a structure (text p.13) | ● DONE |
## 8. Revised / Adjusted Base Components
| Component | Detail | Status |
| --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Adjusted Economy Research tile (double-sided) | levels 3 & 4 rewards, BOTH sides — CONFIRMED, see RULES_CLARIFICATIONS.md §F1 | ◐ SPEC |
| Adjusted Lantids PI tile (double-sided) | solo/2p side AND 3p side — CONFIRMED verbatim (RULES_CLARIFICATIONS.md §I2); NOT rendered by the uiqoo.kr randomizer tool at all, text-only | ◐ SPEC |
| Colonization overlay | covers Q.I.C. actions on Research board; defines protoplanet/asteroid terraform | ◐ the Q.I.C.-actions-covering half is **CODED & TESTED** (done 2026-06-29): `BoardAction.values(expansions)` excludes `Qic1-3` under Lost Fleet, so they're never offered alongside the spaceship boards' own Q.I.C. actions; the protoplanet/asteroid terraform-cost half was already done in Chunk 2 (flat early-returns in `planets.ts`) |
| Scoring Board Extension (double-sided) | 25-VP side / 3-shuttle side; +1 advanced tech slot — CONFIRMED (was previously mislabeled "Adjusted Lantids PI tile" in early review passes; see RULES_CLARIFICATIONS.md §E6) | ● DONE for the gating mechanic (`AdvTechTilePos.ScoringExtension`, `Engine.scoringExtensionSide`, `canTakeAdvancedTechTile()`); the physical board's own visual (no dedicated UI component yet) is a separate viewer-side TODO |
## 9. Existing-Faction Changes — AUDIT CLOSED 2026-06-27
> p.16's full 18-faction comparison graphic was screenshotted by the owner and transcribed in full
> into RULES_CLARIFICATIONS.md §I7. Result: only 3 existing factions get a genuinely new Lost-Fleet
> ability (Xenos, Gleens, Space Giants — all already captured); every other existing faction's
> deviation from the table's baseline is pre-existing vanilla personality, not a Lost Fleet change.
- Ivits — CLOSED, no delta found beyond power 2/2 (matches pre-existing vanilla value). §I1/§I7.
- Xenos — free action: spend 1 ore → 1 power Area III (text p.11). CONFIRMED, cross-validated by p.16. §I4.
- Gleens — special action incl. Explore +2 range (text p.11). CONFIRMED, cross-validated by p.16. §I5.
- Bescods — CLOSED, no delta found; "start with 3 knowledge" (p.8) just restates their existing
vanilla baseline, not a deviation. §I3/§I7.
- Lantids — adjusted PI tile (§8) + income 1 power Area I (text p.8). CONFIRMED. §I2.
- Taklons / Nevlas / Itars / Bal T'aks — exploration-cost adjustments (text p.9, captured). §D5.
- ALL OTHER FACTIONS (Ambas, Hadsch Hallas, Geodens, Firaks) — diffed against p.16 art, no silent
change found. §I6/§I7. Implementation note: when coding each faction's Lost Fleet config, diff
§I7's table row against the existing `engine/src/faction-boards/*.ts` definition to be certain no
non-ability income/PI/AC delta was missed — the table itself doesn't distinguish "changed by LF"
from "always been true," only the engine's existing correct vanilla numbers can confirm that.
## 10. Player Pieces (new colors: turquoise, pink)
Per new color: 8 mines, 4 trading stations, 3 research labs, 2 academies, 1 PI,
3 gaiaformers, 25 satellites, 7 player tokens. → `color-codes.ts` + viewer SVG. Status: ☐ TODO
## 11. Explicitly OUT OF SCOPE
- ☒ Automa / solo-bot (all components: Automa Spaceship tiles, Automa Terraforming board, etc.)
- ☒ Frontiers expansion exposure (code kept as reference; not offered alongside Lost Fleet)

View file

@ -0,0 +1,236 @@
# Lost Fleet — Full-Game Playout Fuzzer: Implementation Plan
> Status: **DONE (2026-07-03).** All 5 phases implemented, tested, and landed (`engine/src/fuzz/`);
> see §8 for the campaign report and findings table. Owner asked for this plan 2026-07-02 after the
> multiplayer E2E (PROGRESS #48). Grounded in traced engine code (§0), per the standing
> working agreement. The defining requirement, stated by the owner: the fuzzer must
> **compare engine behavior against the actual Lost Fleet rules along the way** — it is a
> rules-conformance tool, not just a crash finder. That requirement is baked in as the
> oracle-traceability rule (§3) and the triage protocol (§5): every oracle cites its rule
> source, and no engine change happens without a CONFIRMED rules basis.
## 0. Code facts this plan is built on (traced 2026-07-02)
| Fact | Where |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `engine.autoMove()` only auto-plays FORCED decisions (faction default, power charge via `decideChargeRequest`, income order, brainstone, optional auto-pass). There is **no general move generator** anywhere in the engine — that is the core thing to build. | `engine/src/move/auto.ts:8-60`, `engine/src/engine.ts:615` |
| `engine.generateAvailableCommands()` returns a **typed discriminated union** `AvailableCommand` per `Command`, with concrete data payloads (hexes, tiles, costs, federations…) — everything a generator needs to synthesize legal move strings. | `engine/src/available/types.ts:84-110`, `engine/src/available/*.ts` |
| The `Command` enum has ~30 members incl. the LF ones (`Explore`, `SpaceshipAction`, `ExamineArtifact`, `ChooseArtifactToken`, `ChooseTinkeringTile`, `PlacePowerRing`). Each needs a generator arm (many are trivial). | `engine/src/enums.ts:342-376` |
| `engine.advancedLog: LogEntry[]` records per-player, per-source resource/VP deltas — the substrate for conservation and VP-reconciliation oracles. The viewer's chart resource-counter already replays whole games off this log (prior art). | `engine/src/engine.ts:138,321`, `viewer/src/logic/charts/resource-counter*` |
| Determinism oracles are nearly free: `new Engine(moveHistory, options)` replay and `Engine.fromData(JSON)` round-trip both exist and are spec-tested in places; the fuzzer generalizes them to every generated game. | `engine/src/engine.ts` (`fromData`, `loadMoves`), `engine/wrapper.spec.ts` |
| Engine mutates the options object it is given (stamps `map`, `factionVariantVersion`) — the fuzzer must clone options per game, same lesson as PROGRESS #48. | PROGRESS #48; `viewer/src/hosted/new-game.ts` |
| Engine test convention: mocha specs in `engine/src/**/*.spec.ts`, run via `cd engine && npm test`; 490/490 green today and must stay green. | `engine/package.json`, PROGRESS "Testing" |
| Rules sources of truth, in trust order: `RULES_CLARIFICATIONS.md` (the §-ledger, values CONFIRMED with sources) → `rulebook-v1.0.txt` (searchable authoritative prose; no official errata exists, §K1) → PROGRESS.md integration flags / known gaps. | `docs/lost-fleet/` |
## 1. Goal and shape
Auto-play **hundreds of seeded, fully-random-but-legal Lost Fleet games to completion**
(plus base-game control seeds), checking three tiers of oracles on every move, minimizing
any failure to a small deterministic regression spec, and triaging each finding **against
the written rules** before anything is changed. The 490 unit tests cover mechanics in
isolation; this covers the interaction space (artifacts × ship federations × new factions ×
boosters × final scoring × leech chains) where game-night bugs live.
Engine-only: no viewer changes, no `engine/` public-API changes expected — the fuzzer sits
beside the engine (`engine/src/fuzz/`) and consumes its existing surface. If a fuzzer need
seems to require changing non-fuzz engine code for any reason OTHER than a confirmed rules
bug, stop and flag it.
## 2. Architecture
```
engine/src/fuzz/
random-player.ts AvailableCommand -> concrete move string (seeded RNG)
driver.ts game loop: init -> loop(generate, move, oracles) -> EndGame
oracles/
structural.ts tier 1 (crash/termination/determinism/commitment)
conservation.ts tier 2 (resources, power tokens, VP-vs-log, tile pools)
lost-fleet.ts tier 3 (rules oracles, each with a source citation)
shrink.ts failure minimizer (greedy turn-prefix/segment removal + replay)
corpus.ts seed corpus definition (counts, player counts, LF/base mix)
regressions/ minimized failure fixtures (committed; replayed by a fast spec)
fuzz.spec.ts SMALL smoke corpus, part of `npm test` (seconds, fixed seeds)
run.ts CLI campaign runner: `npm run fuzz -- --games 300 --seed-base X`
```
- **`random-player.ts`** is the main construction effort: one arm per `Command` member,
choosing uniformly (with tuned weights) among the command's offered `data` options and
emitting the exact move-string grammar the engine parses (the grammar is documented by
existing specs' fixtures, e.g. `engine/src/engine.spec.ts`, and by `Commands.vue`'s
string-building for the interactive path). Design rules:
- Consume ONLY `AvailableCommand.data` — never re-derive legality — so the generator
cannot mask availability bugs (if the engine offers it, the fuzzer may play it; if
playing an offered command throws, that is itself a tier-1 finding).
- Forced sub-decisions (charge/income/brainstone) can either reuse `autoMove`'s deciders
or be randomized; randomize them (with the auto-decider as one weighted option) — leech
interrupts are §J2-critical territory.
- Guard against free-action loops (`Spend`, `BurnPower`): cap conversions per turn, then
force progress (build/pass weighting grows as the round ages).
- v1 scope: `factionVariant: "standard"`, no auction, no `customBoardSetup`, players 2-4,
faction choice randomized by the generator. Auction/variants later if wanted.
- **`driver.ts`**: per game — clone options (see §0), `new Engine([init n seed], options)`,
loop `generateAvailableCommandsIfNeeded()` → generator → `move()` → run oracles; hard cap
on total moves (~1500) so a stuck game is a termination failure, not a hang. Every game
records `{seed, options, moveHistory}` so ANY failure replays exactly.
- **`shrink.ts`**: on failure, greedily drop/trim turns from the tail-back and replay until
minimal (replay-based shrinking is sound because the engine is deterministic from
seed+moves — §J3). Output: a fixture in `regressions/` + auto-generated spec assertion.
- **Runtime placement**: the big campaign is a separate script (`npm run fuzz`), NOT part of
`npm test`. What IS in `npm test`: `fuzz.spec.ts` (a handful of fixed seeds end-to-end,
seconds) + the `regressions/` replayer, so every found bug stays fixed forever.
## 3. Oracles — with the rules-traceability rule
**The rule that implements "compare with the actual Lost Fleet rules along the way":**
every tier-3 oracle carries, in code, a citation to its rule source
(`RULES_CLARIFICATIONS.md §x` and/or `rulebook-v1.0.txt` section), and the oracle's
assertion text repeats the rule in one sentence. An oracle without a citation does not get
merged. When an oracle fires, the triage protocol (§5) starts from that citation.
### Tier 1 — structural (no rules knowledge)
- Every non-`EndGame` state offers ≥1 available command that is not `DeadEnd`; playing an
offered command never throws; games terminate within the move cap.
- Determinism: at game end (and at N random mid-points), `new Engine(moveHistory, options)`
replay produces JSON-identical state; `Engine.fromData(JSON(engine))` round-trips
identically (generalizes existing spot specs).
- Commitment: `newTurn` is true after every completed line (the multiplayer stack depends
on this — §J1).
- `playerToMove` is always a seated player; leech interrupts resolve (no stuck
`tempCurrentPlayer`).
### Tier 2 — conservation / accounting (rules-adjacent, base+LF)
- No resource ever negative (ore/credits/knowledge/QIC/VP where applicable/power in bowls).
- Power-token conservation across bowls modulo documented sources/sinks (gains, burn,
Itars' gaia-area consumption, brainstone) — the exception list itself cites rules.
- **VP reconciliation**: each player's VP equals the sum of their `advancedLog` VP deltas
(catches "state changed without a logged cause" — the class of bug that silently breaks
the viewer's charts and score trust).
- Tile-pool conservation: boosters, tech/adv-tech tiles, federation tokens, LF artifact
tokens — nothing duplicated or leaked between pool/players/ships.
- Base-game **control corpus**: the same tier-1/2 oracles run on non-LF seeds. The mature
base engine should be near-silent; noise there means the ORACLE is wrong (calibration
step before trusting LF findings).
### Tier 3 — Lost Fleet rules oracles (each row = one oracle + citation)
| Rule (one line) | Source |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| Protoplanet mine: exactly 3 terraform steps, +6 VP on build | §Chunk-2 ledger; rulebook "Changes to the Base Game Actions" |
| Asteroid mine: permanently consumes a Gaiaformer; zero ore/credit build cost | same |
| Darkanians: flat 1 terraform step to any color; Space Giants: flat 2 | §B2/§B4 |
| Darkanians & Space Giants pay 2 QIC to build on Gaia; Tinkeroids/Moweyds pay the normal 1 | §B2/§B4 vs §B1/§B5 |
| Tinkeroids/Moweyds cost-3 color set = other players' home colors first, topped up to exactly 3 | §B5 (revised) |
| Exploration charge track costs 0/2/2/3 across its 4 spaces | §C5 |
| Ship standard-tech slots: 0 on Twilight, 1 on each other ship; Twilight artifact slots = player count | §C |
| A ship's seeded Federation token is claimable once; claiming executes its gold side (incl. the 2 chained Build-a-Mine tokens; Asteroid hexes eligible given a spare Gaiaformer) | PROGRESS #24/#26 + BGG designer ruling |
| Each of the 12 ship board-actions is usable once per round (per-round lock) | PROGRESS #18-#23, §C1-C4 |
| Research-board QIC actions (Qic1-3) never available under LF; ship QIC "VP per planet type" has base 2 | §E4/§K3 |
| 7th Advanced Tech slot gate: 2p always ≥25 VP; 3-4p per-game random side (≥25 VP or 3 explored ships) | §E6 (owner ruling 2026-06-27) |
| Examine Artifact: all 13 token effects produce exactly their documented rewards | §G4/§G6, PROGRESS #32 |
| Same-color faction exclusivity incl. Tinkeroids↔Darkanians, Moweyds↔Space Giants | §A4 |
| LF-only tiles (boosters/scoring/adv-tech/federations/final tiles) never appear in base seeds, and vice versa | Integration flag 5; the #48 chart leak is the cautionary tale |
| Final scoring: recompute each final tile's ranking from end-state and match awarded VP | rulebook final scoring + §E6 |
### Pre-declared known gaps (report if hit, do NOT "fix" silently, do NOT count as new finds)
- Protoplanet "+6 VP unless it's your starting planet" carve-out is **deliberately not
coded** (no coded faction could hit it when Chunk 2 landed — PROGRESS "Done" #10). If the
fuzzer proves a coded faction CAN hit it now, that's a real, known-shape finding.
- §H4: LF-specific faces of sectors 05/06/07 still use base-game fallbacks (art blocked).
- §K2: four BGG community threads remain human-unread; rulings there may adjust oracles.
## 4. Seed corpus & campaign
- Committed corpus definition: e.g. 300 LF seeds × {2,3,4} players + 100 base-game control
seeds, all derived from a fixed base seed so campaigns are reproducible and diffable.
- Campaign output: a findings table — seed, minimized fixture path, oracle fired, **rule
citation**, triage class, resolution — appended to this file per campaign.
## 5. Triage protocol (hard constraint, the other half of "compare with the rules")
For every oracle failure, in order:
1. **Minimize** with `shrink.ts`; commit the fixture to `regressions/` FIRST (red test).
2. **Read the rule**: the oracle's citation → `RULES_CLARIFICATIONS.md` entry → the exact
`rulebook-v1.0.txt` passage. Quote the passage in the finding.
3. **Classify**:
- **Engine bug** — engine contradicts a CONFIRMED rule: fix the engine, regression spec
goes green, note in PROGRESS.
- **Oracle bug** — the oracle mis-encodes the rule: fix the oracle, document the
misreading in the oracle's comment (so it isn't re-introduced).
- **Rules ambiguity** — rulebook text genuinely unclear/silent: record in
`RULES_CLARIFICATIONS.md` as an open question (Source `OUR-RULING`-pending, Confidence
`INFERRED`), pick the conservative interpretation for the oracle, and **ask the owner**
— never resolve ambiguity unilaterally.
4. **Never** weaken an oracle just to make a campaign pass, and **never** change engine
code without step 2's confirmed basis. (An unexplained fix is worse than a known bug —
it corrupts the ruleset silently.)
## 6. Delivery phases (each = own tested commit; all 490 base tests stay green throughout)
1. **Generator core + driver**: play seeded 2p BASE games to completion; tier-1 oracles
only. Deliverable: `fuzz.spec.ts` smoke seeds green in `npm test`.
2. **Tier-2 oracles + base-game control campaign** (calibration: silence expected; noise =
fix oracles). LF seeds switched on for tier-1/2 once base is quiet.
3. **Tier-3 oracles, first half** (planets/factions/costs/VP rows of the table) + LF
campaign; triage per §5.
4. **Tier-3 oracles, second half** (ships/artifacts/adv-tech gate/QIC overlay/final
scoring) + full campaign.
5. **Campaign report**: findings table appended here; PROGRESS.md "Done so far" entry;
regression corpus committed; any §5.3 ambiguities queued for the owner.
## 7. Execution notes
- Runtime budget: engine replays full games in milliseconds; a 400-game campaign should be
minutes, not hours — if it isn't, profile the oracle layer, not the engine.
- Clone options per game (see §0). Use a tiny seeded PRNG (e.g. mulberry32) — no deps.
- The fuzzer must also run `generateAvailableCommandsIfNeeded()` exactly like real hosts do,
so availability-generation itself is inside the tested surface.
- Model guidance (owner asked): build phases 1-4 and all §5 triage with a **high-judgment
model (Fable)** — encoding rules into oracles and classifying findings against rulebook
prose is exactly where misjudgment silently corrupts the ruleset. Re-running campaigns,
adding seeds, and mechanical regression upkeep after the oracles are stable is fine work
for a smaller model (Sonnet).
## 8. Campaign report (2026-07-03)
**Status: DONE.** All 5 phases implemented and landed as separate tested commits (`engine/src/fuzz/`);
490 base engine tests were the starting baseline and the suite grew to **564/564** (the merge with
another concurrent session's engine work raised the baseline to 520 before this work started — see
PROGRESS.md #49). Emphasis, per the owner's explicit 2026-07-03 instruction: prioritize the Lost
Fleet rules surface (changes to base-game actions, new mechanics) over base-game archaeology — the
base `boardgamers/gaia-project` implementation is trusted/working, so base-only findings are
recorded and NOT fixed here (see the last 2 rows).
Total campaign volume this session: 100 base-control seeds (tier-1/2 calibration, 2p/3p/4p, all
clean) + roughly 1,000 Lost Fleet seeds across targeted and mixed-player-count sweeps (phases 3-5),
plus the final two `npm run fuzz` campaigns below.
| # | Seed(s) | Fixture | Oracle | Rule citation | Classification | Resolution |
| -------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| LF-1 | `fuzz-lf-2p-0` (found), minimized `lf-b5-cost3-row` | `fuzz/regressions/lf-001-b5-cost3-row-nondeterministic.json` | `tier1.structural.determinism` | RULES_CLARIFICATIONS.md §J3 ("engine is deterministic from seed + moves"); §B5 (rulebook p.8, cost-3 row placed once at setup) | **Engine bug** — CONFIRMED | **Fixed** (commit `b8f34c4`): `engine.lostFleetTerraformingRow` computed once in `moveInit` and persisted, instead of being recomputed lazily from `map.seed` (which `SpaceMap.toJSON()` never serializes, so every host-style fromData clone shuffled from seed `undefined`). Regression fixture red-then-green verified (constructor vs. `Engine.slowMotion` host-style replay). |
| LF-2 | n/a (structural — any Examine Artifact / Twilight Q.I.C. action with 0 owned Federation tokens) | none (deliberately not forced into the corpus; hit incidentally during phase-2 sweeps) | generator robustness (`fuzz/random-player.ts` `pickOrNull`) | RULES_CLARIFICATIONS.md §G6 (Federation-shaped Artifact), §C1 (Twilight Q.I.C. "same mechanic as the base game's federation re-scoring") | **Rules ambiguity → RESOLVED** | **Fixed** (owner ruling 2026-07-03, recorded in `RULES_CLARIFICATIONS.md` **Open Question #8**, revised same session): unlike the base game's QIC2 (which hides the action entirely without an owned token), both LF surfaces stay offered/choosable with zero owned Federation tokens and simply have no effect. `engine.ts`'s shared `gain-${Resource.RescoreFederation}` listener is no longer `required`; `available/federations.ts`'s rescore branch returns no command (not one with an empty `tiles` list) when nothing is owned, so it resolves as a genuine no-op instead of an unanswerable forced choice. New `BuildWarning.noOwnedFederationToRescore` / `ChooseArtifactToken.noEffectTokens` surface the condition as data for a future UI. 5 new/updated regression tests; 170-seed validation campaign clean. |
| LF-3 | `fuzz-lf-2p-2` | `move/spaceship-actions.spec.ts` + `engine.spec.ts` regression tests (2 new, not a JSON fixture — the finding was a unit-level cost-attribution bug, more naturally expressed as focused tests) | `tier2.conservation.non-negative` | RULES_CLARIFICATIONS.md §E2 (rulebook p.10, Asteroid mine "needs an available Gaiaformer; Gaiaformer is consumed"); §C4 (Eclipse Credit action, "the mine itself is free... distinct from the standard Asteroid-mine route in E2, which instead requires consuming a Gaiaformer"); §G3 (rulebook Appendix III, "former" booster: "3 VP per Gaiaformer... none for Gaiaformers already used to colonize an asteroid") | **Engine bug** — CONFIRMED | **Fixed** (commit `1eb9aa4`): `player.build()` unconditionally consumed a Gaiaformer on any new Asteroid colonization, including starting-building setup placement (§B1/§B2 factions own 0 Gaiaformers at setup — this permanently cost Tinkeroids/Darkanians one Gaiaformer of capacity) and Eclipse's Credit action (§C4 explicitly waives it). Symptom: the §G3 "former" booster paid **−3 VP on pass** once the negative-capacity bug accumulated. New `AvailableBuilding.consumesAsteroidGaiaformer` flag (default true; false at the 2 non-consuming sites). 2 red-then-green regression tests. |
| oracle-1 | `fuzz-lf-2p-6`, `-17`, `-21`, `-23`, `-24`, `-29`; Ivory Beacon | `engine.spec.ts` + `player.spec.ts` regressions | `tier3.lf.build-offers` | RULES_CLARIFICATIONS.md §E1 (rulebook p.10, "+6 VP on mine (0 if it's your start planet)") | **Engine bug — CONFIRMED** | **Corrected 2026-08-21:** the earlier triage incorrectly treated every Moweyds/Space Giants Protoplanet as "your start planet." The carve-out applies only to the free Phase.SetupBuilding placement. Every later Build-a-Mine action receives +6 VP, regardless of faction. Removed the engine's home-type suppression, restored the oracle's +6 expectation after setup, and locked both halves of the distinction with regressions. |
| oracle-2 | `fuzz-lf-mix-4p-95` | n/a (oracle-only) | `tier3.lf.artifact-effects` / `tier3.lf.ship-federation-gold-side` (phase-4) | RULES_CLARIFICATIONS.md §G6 (KnowledgeQic artifact, "gain 3 knowledge + 1 Q.I.C."); §G5 (OreQic ship Federation token) | **Oracle bug** | **Fixed in the oracle**: both oracles expected a flat "+1 Q.I.C." reward, missing the **pre-existing base-game Gleens rule** (`player.ts` `factionReward`: every Q.I.C. grant from any source becomes Ore for Gleens until Academy2 is built). Not Lost Fleet content, but the new LF reward paths correctly interact with it — the oracle's expectation was wrong, not the engine. Root-caused via a full instrumented trace of the reward pipeline. Fixed via a shared `applyGleensQicSubstitution()` helper. |
| oracle-3 | `fuzz-lf-2p-34` | n/a (oracle-only) | `tier3.lf.final-scoring-counts` (phase-4) | RULES_CLARIFICATIONS.md §H2/§G4 (Deep Space sector colonization counting) | **Oracle bug** | **Fixed in the oracle**: the independent Deep-Space-sector re-derivation counted any hex with `buildingOf(player) !== undefined`, which incorrectly includes a Lantids-style "additional mine" (guest, non-main-occupier) hex; the engine's own trusted `ownedPlanets`-based convention (main-occupier only) correctly excludes it. Oracle fixed to check `hex.isMainOccupier(player)`, matching the engine convention. |
| BASE-1 | `fuzz-lf-3p-33` (81 lines, minimal — every line load-bearing), `fuzz-lf-mix-4p-110` (shrunk 119→105 lines) | `fuzz/known-issues/base-001-*.json`, `base-002-*.json` (reference only — deliberately NOT in `fuzz/regressions/`, which `npm test` asserts green) | `tier1.structural.determinism` | **None** — base-game Taklons + Brainstone + RoundIncome/RoundLeech machinery; no `RULES_CLARIFICATIONS.md` entry exists for base Taklons behavior | **Engine bug (suspected), OUT OF SCOPE** | **Not fixed.** Two independent seeds (3p and 4p) show live incremental play requiring Taklons to resolve a Brainstone placement that a fresh sequential replay of the identical seed+moves does not, both during Taklons' Planetary-Institute-boosted leech/income interrupts (`available/leech.ts` `getTaklonsExtraLeechOffers`). Zero Lost Fleet content involved; per the owner's explicit 2026-07-03 instruction the base implementation is trusted and this session's effort stays on Lost Fleet rules — no rules basis exists to touch engine code regardless. Flagged for a future base-game-focused session. |
| BASE-2 | `lost-fleet-fuzz-v1-lf-2p-61` (shrunk 58→35 lines) | `fuzz/known-issues/base-003-federation-cache-staleness-nondeterminism.json` (reference only) | `tier1.structural.determinism` | **None** — base-game `Player.availableFederations()` caching; federations are vanilla Gaia Project content, no Lost Fleet ledger entry applies | **Engine bug (suspected), OUT OF SCOPE** | **Not fixed.** A fresh sequential replay ends up offering no `Command.FormFederation` at all where live/host-style play correctly does; root-caused (via a full instrumented trace) to `player.federationCache`'s early-return cache-hit path in `availableFederations()`, which is keyed only on `maxSatellites <= federationCache.availableSatellites` with no check that the underlying occupied-hex set changed since the cache was warmed. Surfaced by (not caused by) a Lost Fleet ship-federation claim move; the caching bug itself is pure base-game machinery. Flagged for a future base-game-focused session. |
**Oracle-calibration notes** (not findings — recorded so they aren't rediscovered): `fuzz/state.ts`'s
`normalizedEngineState()` intentionally excludes `players[*].data.tiles.booster`'s `undefined`-vs-`null`
representational difference (last-round pass) and `players[*].federationCache` from state-equality
comparisons. The `federationCache` exclusion does NOT mask BASE-2 above — that finding was caught by
the separate "replay must not throw" check, which is independent of state-field comparison, so the
exclusion remains safe for its original purpose (avoiding noise in the field-diff check specifically).
**Regression corpus**: `fuzz/regressions/lf-001-b5-cost3-row-nondeterministic.json` (auto-replayed,
asserted green, in `npm test`) plus 2 focused unit tests for LF-3. `fuzz/known-issues/` holds the 3
base-game reference reproducers (base-001/002/003), deliberately excluded from the `npm test`
regression loader so the suite stays green while the reproducers remain available for a future session.
**Queued for the owner**: none remaining — `RULES_CLARIFICATIONS.md` Open Question #8 (LF-2, the
rescore-with-no-owned-token gate) was resolved by owner ruling the same session; see the LF-2 row
above.

View file

@ -0,0 +1,47 @@
# Lantids rules audit — 2026-11-01
## Rules used
- [Base rules, Appendix I: Lantids](https://www.feuerland-spiele.de/fileadmin/game/Gaia_Project/GAIA_PROJECT_EN_rules_Web.pdf):
a shared mine functions normally except that it cannot be upgraded and does not contribute to
planet-type or Gaia conditions. Mine placement still pays the mine cost and range, but no
habitability cost. Shared mines retain their owner's income and building value.
- [Designer clarifications on shared mines](https://boardgamegeek.com/article/27462499):
sector/structure presence and navigation count; planet-specific effects do not.
- [Lost Fleet rules](https://capstone-games.com/cdn/shop/files/GP_Exp_Rule_EN_V1_Web.pdf?v=6134275372584409409),
pp. 8, 14–15: adjusted PI, Deep Space sector rewards, bonus mine actions.
- [Protoplanet/asteroid clarification](https://boardgamegeek.com/thread/3389868/lantids-plus-protoplanet):
a shared protoplanet grants no 6 VP and a shared asteroid does not count for asteroid scoring.
This thread relays the designer ruling; the existing implementation already follows it for
ordinary builds. The audit applies that same rule to bonus mine actions.
## Findings and coverage
| Area | Outcome |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Deep Space final goal, booster, immediate/pass Advanced Tech | Fixed: include shared mines; count each physical sector once. Gaiaformers, stations and off-map artifacts do not add sectors. |
| Bonus mine from Range/Terraform federation or Terraform tech | Fixed: sharing Gaia needs no habitability QIC; sharing an asteroid needs no Gaiaformer; sharing a protoplanet gives no 6 VP. Normal range rules still apply. |
| Solo/2-player PI on a shared Terra planet | Fixed: one 2-knowledge reward, not two. Shared mines already receive the base PI reward and do not also qualify for a planet-type reward. |
| Charts and scoring help | Fixed: include shared deep-sector mines, recognize own first colonization, track Lost Planet ownership, and isolate each chart's history state. Completed Gaia projects count when their mine is built. |
| Ordinary shared-mine costs and benefits | Verified: mine cost, range, mine income/scoring, PI knowledge, structure/federation count, own power value and leech. No Gaia/asteroid/planet-type scoring or protoplanet reward. |
| Build restrictions | Verified: no upgrade of a shared mine, no sharing an unfinished Gaia project, normal mine supply limit. Starting placement remains restricted to vacant home planets. |
| Lost Fleet adjustments | Existing tests cover +1 token income, own Terra PI bonus in solo/2p, extra PI charge in 3p, and unchanged 4p/base behavior. |
| Round sector/planet-type scoring | Existing tests and the protoplanet regression distinguish sector presence from planet-type colonization. |
The old fuzzer exclusion of shared Deep Space mines was based on the implementation rather than
the rules. Both the production count and independent map-scan oracle now include them.
The existing house ruling for the base game's **ordinary sector** goal remains separate from
Deep Space scoring (RULES_CLARIFICATIONS §G4c). This audit does not change that ruling.
Regression files: `engine/src/faction-boards/lantids-rules.spec.ts`, existing
`lantids.spec.ts` / `tiles/scoring.spec.ts`, and `viewer/src/logic/charts/lantids-charts.spec.ts`.
The existing all-families chart fixture now correctly credits Lantids with their starting Terra
planet type rather than zero planet types.
## Reported game
In Wicked-banana-8201 at move 201, Lantids have a shared mine on DS14_0: their Deep Space count
must be **1**, previously **0**. The mine's ordinary 3-VP new-sector reward is already present;
the earlier removal of its incorrect 6-VP protoplanet bonus remains valid. Deep Space progress is
computed from the board, so this correction does not require rewriting that game's moves.

View file

@ -0,0 +1,176 @@
# Viewer Performance — Investigation & Findings
> Read this before touching viewer rendering, `store.ts` reactivity, or `SpaceHex`/`SpaceMap`/
> `Sector` again. It records what was actually measured, not guessed, so the same profiling work
> doesn't get redone from scratch in a future session. Last updated: **2026-06-27**.
## Regression test
`viewer/src/components/SpaceMap.spec.ts` mounts the real `SpaceMap → Sector → SpaceHex` +
`Definitions`/`FederationGradients` tree (real `Engine` from `engine/fixtures/Beta-2.json`,
`makeStore()`) and asserts hex/sector counts and that `<defs>` stays flat instead of scaling
per-hex. This is the test that would have caught the `<defs>`-duplication bug fixed below if it
had existed first. **Extend this test (or add a sibling) whenever you touch viewer rendering** —
see `PROGRESS.md`'s "Testing — required going forward" section.
## Bottom line
The perceived "laggy buttons" (Build a Mine, Trade, Research, browser Back) are **not** caused by
the game engine and **will not** be fixed by switching the engine off the client, by a faster CPU,
or — see the Vue 3 section below — by a framework version bump alone. The cost is almost entirely
**Vue 2 re-rendering the SVG hex map**: deep reactivity walking a large state tree, and (until this
session's fix) ~4,500 duplicate `<defs>` SVG nodes re-created on every map re-render.
## Why the engine was ruled out first
Before touching the viewer, the engine itself was benchmarked in isolation (`engine/bench-perf.ts`,
written, run, then deleted — not committed, the result is what matters):
- `Engine.fromData()` + `generateAvailableCommandsIfNeeded()` for a single move replay: **~3.6 ms**.
- This runs purely in JS, client-side, with no network/server involved — confirmed this is the same
whether the engine is "client-side" or not. **Client-side execution is not the cause of lag** —
moving the engine to a server would not remove this cost, and the cost is tiny anyway.
So 100% of the budget for a slow click (measured up to ~148 ms before fixes, see below) was in the
viewer layer: Vue reactivity + DOM/SVG diffing, not in game logic.
## How the profiling was done (reproducible)
Tools: Playwright driving the **pre-installed** headless Chromium
(`PLAYWRIGHT_BROWSERS_PATH=/opt/pw-browsers`, `executablePath: '/opt/pw-browsers/chromium-1194/chrome-linux/chrome'`),
Chrome DevTools Protocol `Profiler.enable/setSamplingInterval/start/stop`, self-time aggregated by
`functionName + file:line` from the returned `.profile` (nodes/samples/timeDeltas).
1. **Get a mid-game state to click around in.** `engine/fixtures/Beta-2.json` is a _finished_ game
(`ended: true`, round 6) — useless for profiling action buttons, since none are enabled. A
mid-game snapshot was generated by replaying prefixes of its `moveHistory` with
`Engine.fromData()` until a round-1 state came up with Build/Research/etc. available, then
dumped to JSON. That JSON is **not in the repo** (scratchpad-only, this session); regenerate the
same way if needed again — it's a few lines of script against `engine/fixtures/Beta-2.json`.
2. **Load the app, paste the state via the debug Load/Export modal** (`Wrapper.vue`'s Load button →
textarea → OK), wait for `#move-buttons .move-button` to appear.
3. **Path A — cold load+render cost**: start the CDP profiler right before clicking "OK" on the
Load modal, stop it once the move buttons have rendered + one settle frame. This captures
`store.commit("receiveData", …)` → Vue reactivity setup → full SVG map render.
4. **Path B — per-click cost**: with the map already rendered, repeatedly click the top-row
`#move-buttons .move-button` elements in sequence (re-querying the DOM each iteration, no page
reloads — reload loops were a source of flaky `strict mode violation` Playwright errors because
multiple "OK" buttons exist on screen at once), timing each click to two `requestAnimationFrame`
callbacks (`raf2()` helper) so the timing covers the actual re-render, not just the JS handler.
5. Aggregate profiler self-time per function across all clicks combined; also record per-click wall
time individually to catch the single worst click (Build was consistently the worst).
Gotchas hit and fixed along the way (so they aren't rediscovered):
- The Bash tool's sandbox interfered with binding local ports / backgrounding the headless browser —
needed `dangerouslyDisableSandbox: true` for these specific local-only, no-side-effect profiling
runs.
- `pkill <name>` returns nonzero when nothing matches, which aborts a `cmd1 && cmd2` chain — append
`|| true`.
## Root causes found
1. **Deep Vue 2 reactivity over the whole engine state.** `store.ts`'s `receiveData` mutation did
`state.data = data` where `data` is the entire `Engine` instance (players, map, all hexes,
buildings, history…). Vue 2 walks that whole object graph with `defineReactive`/`Dep` to make
every property reactive — and it's **replaced wholesale** on every move, so the deep observation
is redone every single time, for an object that is read-only/immutable from the UI's point of
view (nothing inside it is ever mutated in place by a Vue template/`v-model`).
2. **~4,500 duplicate static SVG `<defs>` nodes.** `SpaceHex.vue` (one instance per hex, ~90 hexes
on a standard board) used to render its own `<defs>` block of federation-line gradients/lines/arcs
— ~50 SVG nodes, **identical** content for every hex (only depends on the static planet→color
table, not on hex-specific data). That's ~4,500 redundant nodes created/diffed by Vue on every
map re-render, even though only `<use href="#...">` references were actually needed per hex.
3. Minor: a few `console.log` calls sat in hot paths (`store.ts`'s move emitter, `Commands.vue`'s
`handleCommand`/`subscribe`/`emitButtonCommand`, `self-contained.ts`'s move handler) — cheap
individually but on the critical path of every click.
Confirmed via the CDP profiles: before the fix, `insertBefore`/`createElementNS`/`setAttribute`/
`setAttributeNS` (raw SVG DOM construction) and Vue's reactivity/`_init`/`_render` internals
(`chunk-vendors...js`, minified names like `Dt`/`Li`/`Yi`/`Ln`/`$i`) dominated self-time — not
anything in the engine or in app-level business logic.
## Fixes applied this session
| # | File | Change |
| --- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | `viewer/src/store.ts` | `import Vue, { markRaw } from "vue"`; `receiveData` now does `state.data = markRaw(data)` — opts the whole engine instance out of Vue's deep-reactivity walk. Safe because nothing mutates `state.data` in place; it's always replaced wholesale. |
| 2 | `viewer/src/components/Game.vue` | `handleData()`: moved the `currentMove`/`newTurn`/`data.moveHistory.pop()` handling to run **before** `this.$store.commit("receiveData", data)` (previously after). Needed because that logic used to rely on Vue reactivity firing on `state.data` mutation timing, which no longer deep-observes after fix #1. |
| 3 | `viewer/src/self-contained.ts`, `viewer/src/components/Commands.vue` | Removed `console.log` calls from hot paths (move emitter handler; `handleCommand`, `subscribe()` callback, `emitButtonCommand()`). |
| 4 | `viewer/src/components/definitions/FederationGradients.vue` (new) | Hoisted the federation gradient/line/arc `<defs>` (per planet color) out of `SpaceHex.vue` into one global component, rendered once in `Definitions.vue`'s top-level `<defs>` instead of once per hex instance. |
| 5 | `viewer/src/components/definitions/Definitions.vue` | Registered and rendered `<FederationGradients />` once, globally. |
| 6 | `viewer/src/components/SpaceHex.vue` | Removed the per-hex duplicated `<defs>` block entirely (now reuses the global one via existing `<use>`/`url(#federation-gradient-...)` references, which already worked by id — no template logic changed, just deleted the duplicate definitions). Removed the now-unused `planetColors` data property and the `planets` default import (kept `planetNames`). |
These are **Tier 1** (#1–3: reactivity + dead weight) and **Tier 2** (#4–6: de-duplicate SVG defs)
from the scoping discussion — the user explicitly chose "Tier 1 + Tier 2" over a larger Tier 3
rework.
## Measured results
Same profiling harness, same mid-game state, before vs. after fixes 1–6:
| Scenario | Before | After | Change |
| ------------------------------------------------------------------- | ------- | ---------- | -------------------------------------------------------------------------- |
| Cold load → full map render (Path A wall clock) | 1185 ms | 993–995 ms | **-16%** |
| "Build a Mine" button click (worst single click, Path B) | 148 ms | 81 ms | **-45%** |
| Median action-button click (Path B, e.g. Pass/Research/Free action) | ~26 ms | ~26 ms | unchanged (these were already cheap; they don't re-render much of the map) |
Verified no regressions: visual screenshots before/after match; full build→move flow exercised
end-to-end with zero new console errors; deployed to the Vercel preview and confirmed green.
Committed as `f1aca63` ("perf(viewer): cut map render cost and skip deep reactivity"), pushed to
`claude/quirky-thompson-gt0n0h`, deployed to Vercel.
## Still open (not done — Tier 3, only if asked for)
- **Build a Mine is still 81 ms**, the single worst click. The remaining cost is the highlight/range
computation re-rendering `polygonClasses`/`planetClasses`/warnings across all ~90 `SpaceHex`
instances every time the selection/highlight set changes (each hex component re-evaluates several
getters that scan `highlightedHexes`, `mapModes`, federations, etc.). Reducing this further means
either memoizing per-hex highlight state more aggressively or restructuring `SpaceMap`/`SpaceHex`
to avoid re-touching every hex component when only a subset of hexes actually changed class —
this is a real component-architecture change, not a one-line fix, which is why it was scoped out
as Tier 3.
- No further `<defs>`-style duplication audit was done beyond `SpaceHex.vue`'s federation block;
`Buildings.vue`/`Filters.vue` (also rendered once globally via `Definitions.vue`) were not
re-audited for the same per-instance-duplication pattern, but a quick check found no second
instance of it.
## Vue 2 → Vue 3 migration: is it worth it for render speed?
Short answer: **no, not on its own — it would not fix the thing that was actually measured as the
bottleneck.** Don't do this as part of "getting the foundation right" for Lost Fleet; it's a
separate, large, mostly-orthogonal project.
Reasoning, grounded in what this session measured:
- Vue 3's reactivity (`Proxy`-based) is cheaper than Vue 2's `Object.defineProperty` walk **only**
for the case where you actually let Vue observe a big object. That cost is already eliminated here
via `markRaw()` (fix #1) — Vue 2.7 (what this app already runs, confirmed in `package.json`) ships
`markRaw` for exactly this purpose, so the "deep reactivity over a big state tree" problem is
already solved in Vue 2, not something only Vue 3 can solve.
- The dominant cost in the profiles — confirmed by `insertBefore`/`createElementNS`/`setAttribute`/
`setAttributeNS` dominating self-time — was **raw SVG DOM node count and diffing**: ~90 `SpaceHex`
components each rendering many child elements (`<use>`, `<text>`, `Building`/`Planet` subcomponents,
ships, customs posts, trade tokens), most of it redundant per-hex `<defs>` (now fixed) and
per-hex highlight recomputation (still open, Tier 3 above). Vue 3's compiler-informed diffing
(block tree / patch flags) helps with this _only if the components are rewritten with the Vue 3
compiler's optimizations in mind_ (e.g. `<script setup>`, avoiding `v-for` over large lists without
keys that change, hoisting static vnodes) — a like-for-like Options-API port of the same
`SpaceHex.vue` template to Vue 3 would see a modest gain at best, not a step-change, because the
problem is node _count_, not which framework is diffing the nodes.
- Cost side: this app is Vue 2.7 + `vue-class-component`/`vue-property-decorator` (class-based
components, used throughout `SpaceHex.vue` and friends) + Vuex 3 + `bootstrap-vue` + webpack 4 via
`vue-cli-service`. Vue 3 migration would require: rewriting every class-component to `defineComponent`
or `<script setup>` (every `.vue` file in `viewer/src/components`), Vuex 3 → 4 (or Pinia), dropping
or replacing `bootstrap-vue` (no Vue 3 release of the original package — would mean
`bootstrap-vue-next` or removing Bootstrap entirely), and likely the build tooling too (vue-cli is
unmaintained for Vue 3; would push toward Vite). That's a multi-week rewrite touching nearly every
file in the viewer, for a "modest gain at best" on the one metric (render speed) being optimized.
- If render speed for the hex map specifically becomes the priority again, the higher-leverage next
step is the Tier 3 item above (reduce per-hex highlight re-render) or restructuring the map to
render fewer/larger SVG primitives — both deliver more, for less risk, than a framework migration.
**Recommendation: skip the Vue 3 migration.** Treat the current foundation (Vue 2.7 + the Tier 1/2
fixes above) as good enough to build Lost Fleet features on. Revisit Tier 3 only if a specific
interaction is still reported as laggy after Lost Fleet adds more board state to render.

View file

@ -0,0 +1,246 @@
# Preference Split Auction
A faction-selection variant playable at **any player count the game supports (2–5)**, with one
picked faction per player. Selectable at game creation as `AuctionVariant.PreferenceSplit`
(`"preference-split"`), alongside Standard, Silent Auction, Choose-Then-Bid and Bid-While-Choosing.
> It was 4-players-only in its first version — an explicit requirement of the original brief — and
> generalized the same day (owner request, 2026-08-05). Nothing in the mechanism was ever
> count-specific: the price is a faction's total over the player count, and the pick round always
> produces exactly one faction per player.
It is deliberately **not** a first-price, second-price or ascending ("silent") auction: nobody
outbids anybody, nobody reacts to anybody else's numbers, and the price never comes from a single
opponent's bid.
## The rules, in plain language
1. Every player secretly distributes **exactly X bid points** among the picked factions (one per
player), all at the same time. Bids are whole numbers, 0 is allowed, and they must add up to
exactly X.
2. Nothing is revealed until every player has submitted. Then everything is revealed at once.
3. Factions are **ranked by the total** bid on them, highest first.
4. Going down that ranking, each faction is **awarded to the highest bidder who has not already
received a faction**. A player who wins one is out of the running for the rest.
5. The price is the **average of every bid** on that faction — including bids from players who
already won something else. It is never recalculated as players drop out.
6. That average is the price **whatever the winner bid themselves**. Your own bid decides _which_
faction you get, never what it costs — so you can end up paying more than you put on it, and a
player who bid 0 on the faction they receive still pays its average.
7. Any tie — two factions on the same total, or two eligible players on the same highest bid — is
resolved **automatically and at random**. Players are never asked to break a tie.
The payment is deducted from the winner's final score, the same way every other auction variant's
bid is (`player.data.bid`, cashed out in `finalScoringPhase`).
### Budget (X)
**Fixed by the player count: 20 points per player** (owner decision, 2026-08-05 — it was briefly a
number you typed at setup, and that was one dial too many for something with a single sensible
answer). `EngineOptions.auctionBudget` still exists and is still stored per game by `create_game`,
which pins a game's budget forever so changing the default can never rewrite what an in-progress
game's players were asked to split; there is simply no UI that lets you choose it. The engine
accepts any whole number 1–999 if one is supplied another way (`?auctionBudget=` in the
self-contained viewer, handy for testing).
**The scale is 20 points per player** — 40 at 2 players, 60 at 3, 80 at 4
(`defaultPreferenceSplitBudget`). That is because **X is the table's total bill, not one player's**:
every faction costs its own average (its total over N players) and there are N factions, so the
payments always add up to exactly X before rounding. Each player therefore pays X/N on average,
whoever ends up with what. A flat default would have made a 2-player auction twice as punishing as a
4-player one for the same number.
At 20 per player, a typical winning price lands in the 10–30 VP range next to a ~120 VP game.
The scale was 10 per player when the variant shipped (2026-08-05) and was doubled to 20 the next
day (owner decision) to give a split more resolution to express preferences with. Only the default
moved: `auctionBudget` is stamped into a game's options at creation, so the two games created on the
old scale still run on it, and the server-side fallback in `preference_split_budget` was moved in
lockstep (migration `20260806090000_preference_split_budget_20_per_player.sql`).
### What 2 players looks like
The mechanism is well defined at 2 players but much simpler than it looks: with two factions,
whoever bid more on one necessarily bid less on the other, so each player just gets the faction they
rated relatively higher and the ranking step cannot change the outcome. Pricing still works normally
(each pays half the combined bid on their faction). 3 players and up is fully non-degenerate.
### Why there is no cap at the winner's own bid (owner decision, 2026-08-05)
An earlier draft capped the payment at `min(average, own bid)`. It was removed: a cap sounds fairer
and is not. It lets a player take a faction the whole table rated highly for **nothing at all**,
simply by having bid 0 on it.
The owner's example: one player splits their budget almost evenly across two factions — say 20 and
19 — and another player rates those same two almost equally too. The first player's marginally
higher bid pulls them onto one of them, and under a cap the second player picks up the other for 0,
even though everyone at the table agreed it was worth about 20. Paying the average keeps a faction's
price tied to what it is actually worth to the table.
The accepted cost is that a winner can pay more VP than they personally bid. In exchange the rule is
one sentence long: **you pay what the table thought it was worth.**
### Rounding
`roundVictoryPoints()` in `engine/src/algorithms/preference-split-auction.ts` is the single place
this happens: conventional **half-up** (10.5 → 11, 10.49 → 10). Totals and averages stay exact until
the very end; only the final payment is rounded. The UI shows averages to two decimals.
## Flow
```
SetupBoard → [SetupFactionBan] → SetupFaction → SetupPreferenceBid → SetupBuilding → …
```
The ban round is the existing independent `EngineOptions.banPhase` and is orthogonal to this
variant. The pick round is the ordinary `Command.ChooseFaction` one: four players each nominate one
faction, which is where the factions up for auction come from. A pick is only a nomination —
the auction can and often does give it to somebody else.
Turn order after the auction is the existing rule for every auction variant: `engine.setup` (pick
order) mapped to each faction's final owner.
## Where the code lives
| Layer | File |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Resolution algorithm (pure, no engine) | `engine/src/algorithms/preference-split-auction.ts` |
| Variant + persisted result on the engine | `engine/src/engine.ts` (`AuctionVariant.PreferenceSplit`, `auctionBudget`, `preferenceSplitBids`, `preferenceSplitResult`, `preferenceSplitBudget`) |
| Phase + one-shot resolution | `engine/src/move/phase.ts` (`phaseSetupPreferenceBid`) |
| Move validation | `engine/src/move/setup.ts` (`movePreferenceBid`, plus the 4-player/budget preconditions in `moveInit`) |
| Available command | `engine/src/available/setup.ts` (`possiblePreferenceBids`) |
| Server-side sealed bidding | `supabase/migrations/20260805120000_preference_split_sealed_bids.sql` |
| Bid-phase notifications | `supabase/migrations/20260808120000_auction_bid_notifications.sql`, `supabase/functions/notify/logic.ts` (`buildSealedBidNotifications`, `planSealedBidReminder`) |
| Hosted orchestration | `viewer/src/hosted/host.ts` (`submitSealedBid`, `refreshSealedBids`) |
| Which round is sealed, and its command | `viewer/src/logic/sealed-bid.ts` (`sealedBidPhase`, `sealedBidMove`, `isLegacySequentialBidRound`) |
| Bid form (shared half / this variant) | `viewer/src/components/SealedBidPanel.ts`, `PreferenceSplitBid.vue` |
| Reveal / result | `viewer/src/components/PreferenceSplitLog.vue`, `PreferenceSplitSummary.vue` |
| In-app rules | `viewer/src/components/PreferenceSplitInfo.vue` |
| Setup | `viewer/src/hosted/new-game.ts`, `viewer/src/hosted/CreateGame.vue` |
## How secrecy is enforced
The engine is client-side and authoritative, and every committed move lands in `public.moves`,
which every seated player can read. That is fine for an ordinary turn, but not for a round where
every player bids simultaneously.
> **Shared with the Silent Auction since 2026-08-12 (PROGRESS #157).** Everything in this section
> is now the mechanism for both variants, not just this one: `auction_sealed_bids` is keyed by game
> and seat and holds an opaque `bids` payload, and `sealed_bid_variant(options)` decides which
> rules `submit_sealed_bid` enforces and which command (`preferenceBid` / `silentBid`)
> `reveal_sealed_bids` writes. On the client, `viewer/src/logic/sealed-bid.ts` is the single source
> of truth for "is this a simultaneous bid round", and `SealedBidPanel.ts` is the shared half of
> both bid forms.
So in hosted play, a `preferenceBid` move **does not exist** while the auction is open. Submissions
go to `public.auction_sealed_bids` through `submit_sealed_bid()`, behind an RLS policy that returns
a player only their own row until `sealed_bids_complete()` is true. There are no insert/update/
delete policies at all, so a submission can never be edited or withdrawn. The RPC — not the client —
enforces the budget, the whole-number/non-negative bids, one bid per faction and one submission per
seat.
When the last submission lands, any client may call `reveal_sealed_bids()`, which builds the
move lines **itself, from the stored rows**, appends them to `public.moves` in seat order and moves
the turn pointer, all in one transaction. It is exactly-once by construction: the caller names the
sequence number it expects, `games` is locked for the duration, and a loser of the race gets
`seq_conflict` — which the client already treats as "someone else landed it, resync". A second call
after a successful reveal returns 0.
The only thing the client contributes is `nextSeat`, which it works out by replaying the game
locally with the (now readable) bids applied — the same trust model as `commit_turn`'s own
client-computed `p_next_seat`.
While the auction is open, the only thing any player can learn is **which seats have submitted**
(`sealed_bid_status()` returns counts and seat numbers, never points). The bid panel polls it every
5s; Realtime cannot help here, precisely because the rows are invisible to everyone else.
That seat list is what the bid panel's **bid-status roster** renders: one line per player, named,
marked submitted or still choosing. It is shown _while the form is still open_, not only on the
waiting screen — knowing whether you are the last one the table is waiting on is most useful before
you submit. Own submissions are folded in locally so the roster never lags the 5s poll, and offline
/hot-seat play — which has no poll — derives the same roster from `preferenceSplitBids`, the engine's
own record of which seats have bid.
The same idea covers the other round-0 phase where every player owes exactly one thing — the pick
round — as a compact chip row in `SetupStatus.vue` (see PROGRESS #142). That row is deliberately
absent from **both** simultaneous bid rounds, because each variant's own panel already carries the
roster; and absent from `Phase.SetupAuction` (Choose-Then-Bid / Bid-While-Choosing), because a
player there bids repeatedly and can be outbid again, so "done" is not a state that exists.
**Offline / hot-seat play** has no server, so there is nothing to enforce: the bid form falls back
to an ordinary `preferenceBid` move for the seat on turn, and secrecy is pass-the-device — the same
model the Silent Auction uses offline.
## Notifications during the auction
Every other "it's your move" push in this app rides on `games.current_seat` changing
(`games_notify_update`, `0001_multiplayer.sql`). Simultaneous bidding is the one phase that signal
cannot describe: nothing is committed to `public.moves` while the auction is open, so `current_seat`
sits unchanged — on whichever single seat the engine nominally names — from the last faction pick
right through to `reveal_sealed_bids`. Until migration `20260808120000` that meant exactly **one**
player got told anything (their ordinary turn push, fired by the last pick), everybody else got
nothing, and the hourly reminder sweep could nudge none of them, because `planTurnReminder` only ever
looks at the current seat. A game could stall indefinitely on one person who was never told.
So the auction announces itself:
- `announce_sealed_bid_auction(game_id)` stamps `games.sealed_bid_announced_at`. Any client sitting
in `SetupPreferenceBid` calls it — the same "whoever notices first" shape as the reveal, and for
the same reason: the client that committed the final pick may already be gone. It is exactly-once
server-side (row locked, stamp written once, later callers get `false`), so calling it from every
client on every status refresh is correct, not merely tolerated.
- The null → not-null transition fires `games_notify_sealed_bid_auction`, which POSTs
`{type: 'auction_bid', game_id}` to the `notify` Edge Function. That function looks up who has **no**
row in `auction_sealed_bids` yet and pushes to each of them —
_"Faction auction in <game> — split your bid points."_
- The push is deliberately the ordinary `turn` kind on the ordinary `turn-<id>` tag: it **is** the
player's move, someone who turned turn pushes off does not want this either, and the shared tag
makes the announcement, its re-nudges and the real turn push after the reveal replace one another
instead of stacking banners.
- The sweep re-nudges per **seat**, not per game (`auction_bid_reminders`), because an open auction
has up to five people on turn at once, each with their own interval, cap, quiet hours and snooze.
`sealed_bid_announced_at` is the auction's equivalent of a turn's `latest_move_committed_at`.
- `reveal_sealed_bids` closes all of it out: it clears `sealed_bid_announced_at` (so a resolved
auction drops out of the sweep's candidate query for good), deletes the reminder rows, and — new
in the same migration — stamps `latest_move_committed_at`, which it previously left on the last
faction pick, making the turn that _follows_ the auction inherit however long the auction took.
## Randomness and determinism
The two tiebreaks are the only randomness, and they draw from the game's own **seeded** PRNG
(`engine.map.rng()`), exactly as the Silent Auction's do. Replaying the same move log therefore
always produces the same ranking and the same allocation.
On top of that, the whole outcome is **persisted** on the engine as `preferenceSplitResult` —
ranking, both kinds of tiebreak, every eligibility set, every price and every payment — and
`resolvePreferenceSplitPhase` is a no-op when it is already set. A reload cannot reroll a tie, and
a state restored from JSON never re-runs the auction at all.
The result object is also what the reveal screen renders, so what a player sees is literally the
stored decision, not a re-derivation of it.
## Tests
| File | Covers |
| ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `engine/src/algorithms/preference-split-auction.spec.ts` | rounding, submission validation, ranking, allocation, exclusion of assigned players, averages including assigned players' bids, paying **more** than your own bid, the 0-bid case, the owner's near-tie example, both tiebreaks, determinism, and both end-to-end fixtures (the four-way-tied one and a tie-free one with exact expected payments) |
| `engine/src/preference-split-variant.spec.ts` | the same through real move logs: full flow, the 4-player and budget preconditions, per-move validation, one submission per player, a configured budget, reload determinism (full replay and `fromData`), and that nothing is derived before the last submission |
| `viewer/src/hosted/host.spec.ts` | sealed submissions unreadable until the last one lands, resolution on the fourth, exactly-once reveal under two concurrent clients, identical result on reload, the abandoned-last-submitter fallback, server-side rejection of a wrong total / second submission, and the bid-phase announcement (from any client, exactly once, the moment the last pick opens the phase, never after the reveal) |
| `supabase/functions/notify/logic.spec.ts` | who the bid-phase push goes to and its wording, that it reuses the `turn` kind/tag, and the per-seat re-nudge's interval, cap, snooze and quiet-hours gates |
| `viewer/src/components/PreferenceSplitBid.spec.ts` | one input per faction, allocated/remaining, submit disabled off-budget, submits through the sealed backend (never as a move), renders for a seat that is not on turn, post-submission progress, the per-player bid-status roster (during the form, named seats, unnamed fallback, own submission before the next poll, offline derivation), and the offline move fallback |
| `viewer/src/components/PreferenceSplitLog.spec.ts` | every bid, totals, averages, the ranking, the step-by-step allocation timeline (arithmetic spelled out), and an over-own-bid payment explained as such |
| `viewer/src/components/PreferenceSplitSummary.spec.ts` | the result strip under the banner: what it announces, opening the full log from it, dismissing it per game per device, and staying hidden before the auction resolves |
| `viewer/src/hosted/new-game.spec.ts`, `CreateGame.spec.ts` | 4-player-only gating, the stored budget and its default, invalid-budget blocking, and dropping the variant on a player-count change |
## Adding another auction variant later
Nothing here is hardcoded to this mechanism, and the Silent Auction moving onto it (PROGRESS #157)
is the proof. A new variant needs: a value in `AuctionVariant`, a `Phase`/`Command` pair, a resolver
under `engine/src/algorithms/`, a branch in `phaseSetupFaction`, an entry in
`AUCTION_VARIANT_OPTIONS` (with `playerCounts` if it is restricted to certain player counts — no
variant uses that today, but the gating machinery is still there and tested), and — only if it needs
simultaneous secret input — reuse of the `auction_sealed_bids` table plus: a case in
`sealed_bid_variant()`/`sealed_bid_command()`, its own branch of `submit_sealed_bid`'s validation, a
case in `sealedBidPhase`, and a `SealedBidPanel` subclass supplying `variant`, `commandName` and
`submissionError`. The table itself is keyed by game and seat and holds an opaque `bids` JSON
payload, not anything specific to any variant.

View file

@ -0,0 +1,806 @@
> **Archived:** this plan describes the retired standalone Lost Fleet host. BGS uses the
> engine-owned queue documented in [BGS premoves](../bgs-premoves.md), with the sandbox as its
> only composer. The separate editor, cancellation triggers and Supabase transport were removed.
# Premove — Implementation Plan (consolidated, ready for handoff)
> Status: **design finalized + reviewed, nothing built yet.** Originally written 2026-07-04 and
> owner-approved; **revised 2026-07-04 after an Opus design-review pass** that folded in nine
> correctness fixes, the UX flow, and one scope change (see "What changed from the original design"
> below). This document is self-contained: a fresh session (Sonnet is fine) should be able to
> execute it end-to-end without re-deriving anything. Read `BACKEND.md` first if you haven't
> touched the hosted-mode Supabase backend — this plan builds directly on it. **Start at Phase 0.**
---
## 0. What this feature is
"Premove": while it is **not** your turn, queue the move you intend to make. When your turn actually
arrives it plays **automatically, server-side, even if you are offline** — set it and forget it.
Scope is **hosted (multiplayer) mode only**; self-contained hot-seat has no "away from my turn"
concept.
The offline guarantee is the whole point, which is why this needs genuine server-side execution (a
Supabase Edge Function that decides and commits a move no human confirmed at that moment), not the
best-effort "only runs if a browser tab is open" path that auto-leech shipped with.
---
## What changed from the original owner-approved design (read this first)
The original plan was sound. The review changed these things — one is a genuine scope decision you
should be aware of, the rest are correctness fixes that don't change intent:
1. **Offline auto-leech is now in-scope, not "optional later."** _(The one real scope change.)_
The original treated folding auto-leech into the same edge function as an optional Phase 4. But
without it, the offline promise doesn't actually hold: a power-leech / charge-power decision
(Gaia's `Phase.RoundLeech`) interrupts _before_ your normal turn, and if you're fully offline the
game stalls there — your premove never gets reached. So "premove that actually works offline" =
premove **plus** offline auto-leech resolution. It's now Phase 2 (required for the feature to
meet its goal), with multi-round queueing demoted to the genuinely-optional Phase 3. This reuses
the auto-charge preference the user already sets today; it only adds _persisting_ that preference
so the server can honor it. If you'd rather ship premove-only first and accept "offline works
only when no leech interrupts," that's a valid smaller cut — but say so explicitly, because it
makes the headline feature conditional.
2. **The execute-time gate must match the offer-time gate (this was an outright bug).** The original
edge-function logic attempted the queued premove whenever `engine.playerToMove === seat`. But a
leech decision makes `playerToMove === seat` while the engine is in `Phase.RoundLeech` expecting a
`charge`/`decline`, **not** a `RoundMove` build — so the premove would throw and be consumed as a
bogus failure, deleting it before the player's real turn ever arrived. Fix: the edge function only
attempts a premove when `engine.phase === Phase.RoundMove` (the same condition
`previewAvailableCommandsFor` uses to _offer_ it). See §4 step 3.
3. **A cheap trigger-level gate** so the edge function (and a full engine replay) only runs when
there's actually work for the seat now on turn, instead of on every turn of every game forever.
4. **`commit_automated_turn` must mirror the _post-0009_ `commit_turn`** (8 args incl.
`current_round` + `player_updates`), and must set `committed_by` to the **seat owner's user_id**
(there is no `auth.uid()` in the function).
5. **A premove is always a complete turn**, and the edge function has an explicit "applied but
didn't complete a turn" failure branch.
6. **The edge function's own `seq_conflict` is a silent no-op**, never a premove failure.
7. **Vendoring = bundle the engine to a single ESM file** (esbuild), not copy source — because the
engine imports bare specifiers (`lodash`, `hexagrid`, `seedrandom`, …) that Deno won't resolve
from copied source without a hand-maintained import map. The same bundle includes the tiny
`auto-decide.ts` helper so client and server run identical leech logic.
8. **A retained client-vs-server replay parity test** (not just the one-time Phase 0 spike) to catch
engine/bundle drift, which is the thing that would silently misplay a real game.
9. **Client fast-path is part of the MVP** (instant local execution when you're watching), with the
edge function as the offline backstop — so a watched turn doesn't wait for a trigger round-trip.
Plus the UX flow in §7.
---
## The trust boundary (stated plainly, unchanged from original)
Today every move that reaches the database was validated by the acting player's own browser before
submission — the server has never made a game decision. This plan adds a second path: a service-role
edge function that decides and commits a move no human confirmed at that moment. That's a real
increase in blast radius for a bug (a broken function could misplay a real, currently-running game
unattended). Two things keep it bounded:
- **The server never invents game logic** — it replays the exact same engine the client runs and
only _attempts_ a move the client already validated once when it was queued. The move log stays
the sole source of truth (`BACKEND.md §0`).
- **The engine that runs server-side must be byte-for-byte the same logic as the client's** — which
is why the bundle is built from _this fork's_ `engine/src` (not public npm) and why the parity
test (finding #8) is retained in CI, not one-shot.
---
## 1. Vendoring the engine into the edge function (resolves Phase 0's core question)
**Decision: bundle, don't copy.** `npm:@gaia-project/engine` on the public registry is upstream
(no Lost Fleet); this fork's engine only exists as the local workspace package. The engine's source
uses **bare** imports (`import _ from "lodash"`, `hexagrid`, `seedrandom`, `semver-compare`,
`shuffle-seed`, `eventemitter3`), so copying `engine/src` into the function would force a
hand-maintained Deno import map mapping every bare specifier to the exact `npm:` version — fragile,
and a silent drift vector.
Instead, a **predeploy build step bundles the engine + its deps into one ESM file** the function
imports directly:
- Tool: **esbuild** (`format=esm`, `platform=neutral` or `browser`, `bundle=true`), entry point a
tiny `supabase/functions/_shared/engine-entry.ts` that re-exports what the functions need:
```ts
export { default as Engine, Phase } from "../../../engine/src/engine";
export { autoDecideChargePower, parseAutoChargePreference } from "../../../viewer/src/logic/auto-decide";
```
(`auto-decide.ts` only depends on the engine, so it bundles cleanly and guarantees the server's
leech logic is identical to the client's.)
- Output: `supabase/functions/_shared/engine.bundle.js` — committed **or** rebuilt in the deploy
step; either way the rebuild is **wired into the function-deploy command**, never a manual copy
(finding #4/drift). A `package.json` script like
`"build:edge-engine": "esbuild supabase/functions/_shared/engine-entry.ts --bundle --format=esm --platform=neutral --outfile=supabase/functions/_shared/engine.bundle.js"`.
- Edge functions import from `_shared/engine.bundle.js`.
**Phase 0 verifies this actually runs under Deno** before anything is built on it. Specifically
confirm the deps that reach for host globals behave: `seedrandom`/`shuffle-seed` (may touch
`crypto`/`self`/`window`), and that no bare Node built-in (`assert`, `crypto`, …) sneaks in without
a `node:` prefix.
---
## 2. Engine method (client-side preview only — never on the offline path)
To show "what could I legally do if it were my turn right now" while queuing, add one engine query.
```ts
// engine/src/engine.ts
previewAvailableCommandsFor(seat: PlayerEnum): AvailableCommand[] | null
```
Returns `null` (premove not offered) when **any** of:
- `seat === this.playerToMove` — it's already their turn; show the real buttons.
- the seat has already passed this round (verify the exact field during impl — `passedPlayers`
or equivalent) — nothing to premove into _this_ round.
- `this.phase !== Phase.RoundMove` — setup, income, gaia, leech, scoring, endgame, auction: "my
normal next turn" isn't well-defined.
Otherwise: clone (`Engine.fromData(JSON.parse(JSON.stringify(this)))`), set `currentPlayer = seat`,
`tempCurrentPlayer = undefined`, call the normal `generateAvailableCommands()` path, return the
result. Self-contained, unit-testable with plain engine tests, no viewer/backend involved.
**Fidelity caveat (verify in Phase 1):** `generateAvailableCommands` may read `turnOrder`/position,
not only `currentPlayer`. This is _fine for a preview_ — worst case a queued move fails cleanly later
and the player is notified — but add a test that the previewed commands for a seat match what that
seat actually gets when its turn genuinely arrives, on a couple of real mid-round board states.
**Execution never uses this method.** Playing a stored premove is just "wait until `playerToMove`
naturally is that seat and `phase === RoundMove`, then `engine.move(storedMove)`, catch failure" —
the same path every move already goes through.
---
## 3. Data model
```sql
-- One queued premove line per (seat, seq). seq = that seat's own queue order (1 = next to attempt).
create table public.premoves (
game_id uuid not null references public.games(id) on delete cascade,
seat int not null,
seq int not null,
move text not null, -- exact complete turn line, e.g. "terrans build m -1x2"
queued_move_count int not null, -- games.move_count when queued (staleness display, finding #9)
created_at timestamptz not null default now(),
primary key (game_id, seat, seq)
);
alter table public.premoves enable row level security;
-- Deliberately NARROWER than moves_select: a queued premove is private strategic intent, not public
-- history. Only the owning seat's own user sees their own queue.
create policy premoves_select on public.premoves
for select to authenticated
using (exists (select 1 from public.players
where game_id = premoves.game_id and seat = premoves.seat and user_id = auth.uid()));
-- Durable failure inbox (NOT a one-shot broadcast — a broadcast only reaches a client connected at
-- the instant it fires, i.e. the one moment the premove-setter is least likely to be watching).
create table public.premove_failures (
id uuid primary key default gen_random_uuid(),
game_id uuid not null references public.games(id) on delete cascade,
seat int not null,
move text not null,
reason text not null,
created_at timestamptz not null default now(),
read_at timestamptz
);
alter table public.premove_failures enable row level security;
create policy premove_failures_select on public.premove_failures
for select to authenticated
using (exists (select 1 from public.players
where game_id = premove_failures.game_id and seat = premove_failures.seat
and user_id = auth.uid()));
-- Phase 2 (offline auto-leech): persist the user's existing auto-charge preference per seat so the
-- server can honor it. 'ask' (default) = never auto-decide, same as today's online behavior.
alter table public.players add column if not exists auto_charge text not null default 'ask';
```
**Do NOT add `premoves`/`premove_failures` to the realtime publication.** DELETE events + RLS on old
rows are awkward, and the client already has a natural refresh point: **refetch the caller's own
`premoves` + unread `premove_failures` whenever a `moves` row arrives** (and on load). That covers
"my premove was consumed" and "it failed" without a second realtime channel.
---
## 4. Write paths (RPCs) and the edge function
### 4a. RPCs (mirror the existing "no direct writes, security-definer only" pattern)
- **`queue_premove(p_game_id uuid, p_seat int, p_move text) returns int`** — `security definer`.
Assert the caller owns `p_seat` (`players.user_id = auth.uid()`). Compute `seq = coalesce(max(seq),0)+1`
for that seat. Insert with `queued_move_count = games.move_count`. Returns the new `seq`. Does
**not** re-validate game legality (same trust model as `commit_turn`; the client only offers the
button after building it from `previewAvailableCommandsFor`, so it's been validated once already).
`p_seat` is explicit (not inferred) so a multi-seat owner is never ambiguous.
- **`cancel_premove(p_game_id uuid, p_seat int, p_seq int) returns void`** — `security definer`,
deletes one of the caller's own queued entries (assert seat ownership).
- **`mark_premove_failure_read(p_id uuid) returns void`** — `security definer`, sets `read_at = now()`
on one of the caller's own failure rows (assert seat ownership via the row's game/seat).
- **`set_auto_charge(p_game_id uuid, p_seat int, p_pref text) returns void`** _(Phase 2)_ —
`security definer`, sets `players.auto_charge` for a seat the caller owns. The client calls this
when the user changes their auto-charge preference while in that game (so the server copy tracks
the local one).
- **`commit_automated_turn(...)`** _(the offline commit path)_ — **identical to the post-0009
`commit_turn`** (same 8 inputs: `p_game_id, p_seq, p_seat, p_move, p_next_seat, p_finished,
p_current_round, p_player_updates`; same atomic `select … for update` + `seq = move_count+1` check;
same `games`/`players` cache-column updates) with two differences:
- **No `auth.uid()`/seat-ownership check** (there is no authenticated user here).
- **`committed_by` / `last_committed_by` = the seat owner's `user_id`**, looked up from `players`
(fall back to `games.created_by` if somehow null). This keeps `notify`'s "skip the last
committer" logic correct — the _next_ seat gets the push, the automated seat's owner doesn't.
- Grants: `revoke execute … from public, anon, authenticated; grant execute … to service_role;`.
All new RPCs get the same `revoke from public, anon` + `grant to authenticated` treatment as the
existing ones (except `commit_automated_turn`, which is `service_role` only). Follow the exact
grant/`drop function` discipline in `0009` (widening args via `create or replace` creates a second
overload — always `drop function` the old signature first).
### 4b. Trigger (fires the edge function only when there's work)
```sql
create or replace function public.notify_resolve_automation()
returns trigger language plpgsql security definer set search_path = public, pg_temp as $$
declare v_cfg jsonb;
begin
-- Cheap gate (finding #3): only invoke when the seat now on turn actually has a premove queued.
-- Phase 2 widens this to: premove exists OR that seat's players.auto_charge <> 'ask'.
if new.current_seat is null then return null; end if;
if not exists (select 1 from public.premoves
where game_id = new.id and seat = new.current_seat) then
return null;
end if;
select value into v_cfg from public.app_config where key = 'resolve_automation';
if v_cfg is null then return null; end if; -- unseeded = silent no-op, same as notify
perform net.http_post(
url := v_cfg ->> 'url',
headers := jsonb_build_object('Content-Type','application/json',
'Authorization','Bearer ' || (v_cfg ->> 'key')),
body := jsonb_build_object('game_id', new.id, 'seat', new.current_seat));
return null;
end; $$;
create trigger games_resolve_automation
after update on public.games
for each row when (old.current_seat is distinct from new.current_seat)
execute function public.notify_resolve_automation();
```
Seed `app_config['resolve_automation']` = `{"url": …, "key": …}` out-of-band (same pattern as the
`notify` config; never committed). Until seeded, the trigger is a harmless no-op.
### 4c. The `resolve-automation` edge function
`supabase/functions/resolve-automation/index.ts`. Service-role client (like `notify`). Payload
`{game_id, seat}`. **Resolves exactly ONE committed turn per invocation, then returns** — the
commit's own `current_seat` change re-fires the trigger for the next seat/decision. No internal
loop (mirrors the client's recursion via repeated trigger firings).
Per invocation:
1. Load `games` row + full `moves` log (service role). Build the engine exactly as `host.ts`
`buildEngine` does: `new Engine(["init <player_count> <seed>", ...moves], engineOptions(game))`
then `generateAvailableCommandsIfNeeded()`. (Reuse `engineOptions`'s `map`-stripping — see
`host.ts` / `BACKEND.md §13.4`.)
2. **Stale-trigger guard:** if `engine.playerToMove !== seat`, no-op return (the game moved on).
3. **Branch on phase (the symmetric gate, finding #2):**
- **`engine.phase === Phase.RoundLeech`** (a pending charge/leech decision for `seat`)
_(Phase 2)_: read `players.auto_charge` for `seat`. If `'ask'` → **no-op return** (wait for the
human; leaves any queued premove untouched behind the leech). Else resolve **one** auto-charge
turn: on a clone, set `engine.player(seat).settings.autoChargePower = parseAutoChargePreference(pref)`
and call `engine.autoMove()` **once**; if it produced a completed turn, `commit_automated_turn`
it and return. _(Resolve one turn only — do NOT commit a multi-turn ". "-joined string as one
`moves` row; that breaks the one-row-per-turn / `seq` invariant. Let the trigger re-fire for any
further leech. Verify `autoMove()`'s single-call behavior against the engine during impl.)_
- **`engine.phase === Phase.RoundMove`:** find this seat's lowest-`seq` `premoves` row. None →
no-op return. Otherwise, on a clone, `engine.move(premove.move)`: - **throws** → delete _only that_ premove row, insert a `premove_failures` row
(`reason` = the error message), return. **Do not** fall through to `seq+1` — a failed premove
usually means the situation changed enough to make the rest of the queue suspect; stop and let
the player look at fresh state. - **applies but `!copy.newTurn`** (incomplete turn — shouldn't happen if queuing enforced
completeness, defensive) → delete the premove, insert a `premove_failures` row
(`reason: "premove did not complete a turn"`), return. - **applies and `copy.newTurn`** → `commit_automated_turn(seat, move, next_seat = finished ? null
: copy.playerToMove, finished = copy.phase === Phase.EndGame, current_round = copy.round,
player_updates = playerUpdates(copy))`, then delete the consumed premove row, return.
- **any other phase** (setup, income, gaia, scoring, endgame) → no-op return.
4. **`seq_conflict` from the commit is a silent no-op** (finding #6): if `commit_automated_turn`
raises `seq_conflict`, another path (the player's own fast-path, or a duplicate trigger delivery)
already committed — just return, do **not** write a `premove_failures` row and do **not** delete
the premove (the winning path already consumed it).
Because each successful commit changes `current_seat`, the trigger re-fires and the next
seat's/decision's premove or leech gets its own fresh invocation automatically.
---
## 5. Client fast-path + the `seq_conflict` bug fix (both part of the MVP)
- **Fast-path (finding #9):** when the premove-setter has the game open and their turn arrives, run
the queued premove locally _immediately_ through the existing `applyAndCommit` path (wired the
same way auto-leech's `resolveAutoDecisions` is in `host.ts`) instead of waiting for the
trigger→edge→commit→realtime round-trip. The edge function stays the offline backstop.
- **Race safety** is already handled by `commit_turn`/`commit_automated_turn`'s atomic
`p_seq is distinct from v_game.move_count + 1` check: whichever of {fast-path, edge function}
lands first wins; the loser gets `seq_conflict` and does nothing.
- **The `seq_conflict`-should-be-silent bug (real, pre-existing, affects auto-leech too):**
`host.ts`'s `applyAndCommit` currently treats _any_ `commitTurn` failure as alarming
(`onError` → user-facing message, then resync). A `seq_conflict` specifically means "someone else
already handled this" and should **silently resync** (no error toast). Fix this in `host.ts` as
part of the MVP — it's needed the moment any second automated committer exists. (Detect by the
`seq_conflict:` prefix the RPC raises.)
---
## 6. RLS / realtime summary
- `premoves`, `premove_failures`: SELECT scoped to the owning seat's own user (§3). No direct
writes — all writes via the RPCs. **Not** in the realtime publication; the client refetches them on
load and on every incoming `moves` row.
- `commit_automated_turn` is `service_role`-only; everything else `authenticated`-only, `anon`/`public`
revoked (match `0001`/`0009`).
---
## 7. Client UI / UX flow
The hard part isn't the buttons — it's the new mental model ("the game moves for me while I'm
away"). Everything below serves making that legible and trustworthy. Assume **mobile / PWA** is the
primary surface (push is the primary channel; screens are small).
1. **Premove is an explicit opt-in, not always-on.** During an opponent's turn the board is today's
read-only spectator view. Add a single **"Plan my move ▸"** affordance (shown only when
`previewAvailableCommandsFor(mySeat)` is non-null). Toggling it in puts the board into a visually
distinct **premove mode**: a persistent banner ("PREMOVE — plays automatically on your turn") and
action buttons styled as _queue_ affordances (e.g. dashed outline), never looking like "play now."
This is the #1 footgun to avoid — the user must never confuse queuing with moving.
2. **A premove is a complete turn.** Reuse the existing partial-move accumulation (Game.vue's ". "
command joining) but against the **preview clone**, and only enable **"Queue this move"** once the
previewed turn reaches `newTurn` on the clone (ties to finding #5 — a half-turn premove can never
validly execute). Show the assembled turn in plain language before queuing:
_"Build mine at 3x2, then charge 2 power."_ Queuing calls `queue_premove` (not the normal
move-submit path).
3. **Queue panel.** Compact, collapsible. Per entry: _"Queued: Build mine at 3x2 [✕]"_ (✕ =
`cancel_premove`). For multi-round (Phase 3), number by rank and mark entries beyond the first
_"may be skipped — depends on your earlier move landing."_ Optionally surface staleness from
`queued_move_count` vs current `move_count` ("queued 18 moves ago").
4. **Failure banner.** Unread `premove_failures` rows shown as a dismissible banner on next open
(dismiss = `mark_premove_failure_read`), plus the push (see below). Actionable copy:
_"Your premove couldn't be played in <game> — open to take your turn."_
5. **Success feedback / trust.** On a successful offline play the board just silently advanced.
Early on users won't trust the automation, so tag auto-played moves in the game log
(_"Played automatically from your queue"_). Cheap, and it's what makes people rely on it.
6. **First-run explainer (the single most important UX element).** One-time:
_"Premoves play automatically when your turn comes, even if you're offline. If the board changed
and your move is no longer legal, it's skipped and we'll notify you."_ If Phase 2 ships, add:
_"Leech/charge decisions before your turn are auto-resolved using your auto-charge setting."_
7. **Suppress where it makes no sense.** When the user owns **all** seats (no-lock hot-seat / test
games, `mySeats.length >= playerCount`), hide the premove UI entirely — there's no offline
scenario, and `previewAvailableCommandsFor` would otherwise offer premoves for your _other_ seats.
8. **Cancel-vs-executed feedback.** Rare but real: you open intending to cancel, but your turn
arrived and the edge function already played it. Realtime resync fixes the state; make `cancel`
give clear feedback when the entry is already gone/played ("that move already played") rather than
silently doing nothing.
### Notification tie-in
`premove_failures` composes with the existing push infra. Add a sibling trigger that calls the same
notify path (or a tiny variant) on `insert into premove_failures`, so "your premove couldn't be
played" is a real push, not in-app-only. Reuse the `notify` function / `app_config` VAPID plumbing
(`BACKEND.md §6`).
**Known cosmetic interaction (accept or decide):** `notify` and `resolve-automation` both fire on the
same `current_seat` change, so a premove that plays instantly can produce a spurious "your turn" push
a beat before it auto-plays. The §3 trigger gate reduces the surface; if it annoys, have `notify`
skip a seat that has a queued premove. Owner already accepted a similar leech-chain wart in
`BACKEND.md §6`, so this is a decision, not a blocker.
---
## 8. Phasing
- **Phase 0 — Spike (de-risk only, no schema, no user-facing change).** ✅ **DONE 2026-07-05** — see
"Phase 0 result" below. Prove the fork's engine runs in a real deployed edge function via the
bundle. Read-only. See the checklist below. **Gate: pass Phase 0 and check in with the owner
before Phase 1.**
- **Phase 1 — Premove MVP.** ✅ **DONE (code/schema/tests) 2026-07-05, `resolve-automation` NOT YET
DEPLOYED** — see PROGRESS.md #66. Single premove per seat (no queue depth). `premoves` +
`premove_failures` tables, `queue_premove`/`cancel_premove`/`mark_premove_failure_read`/
`commit_automated_turn` RPCs, the gated trigger, the `resolve-automation` function (with the
`RoundMove`-only gate and `seq_conflict` no-op — but **without** the leech branch yet),
`previewAvailableCommandsFor`, the Premove button + queue/cancel UI + failure banner, the client
fast-path, and the `host.ts` `seq_conflict`-silent fix. **Limitation to document loudly:** offline
progress works _as long as no leech decision intervenes_ before your turn; if one does, the premove
stays safely queued (not consumed) but the game waits at the leech until you're online. Phase 2
closes that gap.
- **Phase 2 — Offline auto-leech (required for the full offline promise).** ✅ **DONE (code/schema/
tests) 2026-07-05, same caveat as Phase 1 — `resolve-automation` not yet deployed** — see
PROGRESS.md #67. Added `players.auto_charge` + `set_auto_charge`, persisted the client's existing
auto-charge preference to it, widened the trigger gate to `premove exists OR auto_charge <>
'ask'`, added the `RoundLeech` branch to `resolve-automation` (a single `engine.autoMove()` call
per invocation, never looped server-side), bundled `auto-decide.ts`'s `parseAutoChargePreference`
into the engine bundle (already wired in `engine-entry.ts` since Phase 0). Once `resolve-automation`
is actually deployed, a fully-offline player with auto-charge enabled will progress past leech
interrupts into their queued premove.
- **Phase 3 — Multi-slot queue: Sequential + Priority (design finalized 2026-07-05).** Not started
in code. Two mutually-exclusive per-seat queue modes, both up to depth 3, both available at every
player count. **The full design is the "Phase 3 design" section below (10.1–10.8)** — read it
instead of this bullet. Short version:
_Sequential_ = a chain of your next N turns (#2 previewed against a clone with #1 applied); _Priority_
= up to 3 ranked alternatives for the **one** upcoming turn, first legal one wins. `seq`-ordered
either way, disambiguated by a new `mode` column.
**Deploying `resolve-automation` is now the single remaining blocker** for the whole feature's
offline promise (Phases 1 and 2 are both otherwise complete) — see PROGRESS.md #66's note on why
this session couldn't do it (no Supabase CLI access token) and what's needed (`supabase functions
deploy resolve-automation --project-ref mitawjpdxkheascdiffz`, then seed
`app_config['resolve_automation']` per BACKEND.md §11's pattern).
### Open decisions to confirm with the owner (don't block Phase 0)
- **Stale-queue on pass / round boundary (finding #9):** if you queue a move then _manually pass_
before your turn, should the queue auto-clear? Cleanly-illegal stale premoves fail safely; the risk
is a still-_legal_-but-unwanted move. Recommendation: clear a seat's premoves when it passes, and
keep `queued_move_count` for a staleness warning regardless. Confirm.
- **Spurious "your turn" push** (§7 notification tie-in): accept, or have `notify` skip
premove-queued seats? Recommendation: accept for MVP, revisit if annoying.
- **Ship Phase 1 alone, or Phase 1+2 together?** The feature's headline ("works offline") is only
fully true after Phase 2. Recommendation: ship them together, or ship Phase 1 with the limitation
stated in-product.
---
## Phase 3 design — Sequential + Priority premoves (finalized 2026-07-05)
> Owner-refined over two design passes (2026-07-05). This section supersedes the one-line Phase 3
> bullet in §8. **Nothing here is built yet** — it is the spec a Phase 3 implementation session
> executes. Read §2 (`previewAvailableCommandsFor`), §3 (data model), §4c (executor), §5 (fast-path)
> and §7 (UX) first; this section only states the _deltas_ from Phase 1/2, not the whole feature.
### 10.1 Two modes, never combined
A seat's queue is in exactly one mode at a time:
- **Sequential** — a script of your next _N_ turns. Premove #2's legal options are previewed against
a disposable clone with #1 **already applied**; #3 against a clone with #1+#2 applied (chain the
preview off the same clone, not fresh current state). It is a plan, not a wishlist.
- **Priority** — up to _N_ ranked **alternatives for the single upcoming turn**. All ranks are
previewed against the **same fresh current state** (one turn ahead only). At execution time the
lowest-rank _legal_ option fires; the rest are discarded.
Both are capped at **depth 3**. Both are available at **every player count** (owner decision
2026-07-05 — no player-count cap on sequential depth; a legal-but-suboptimal outcome from deep
premoving is explicitly the player's own risk to take, so we do **not** try to detect or block it).
**They are not combined** (no per-turn priority lists inside a multi-turn chain — that needs a
combinatorial preview against every possible winner of each earlier turn, and an illegible UI; see
the "Can they be combined?" analysis in the design thread). Switching a seat's mode **clears that
seat's queue** (with a confirm), because the two modes interpret `seq` and failure incompatibly.
### 10.2 Why the two modes are genuinely different (and both wanted)
- **Sequential = throughput** (advance more of _your_ turns while away); **Priority = insurance**
(guarantee _a_ good turn even if the board shifts). Orthogonal axes: depth vs. breadth.
- Sequential fails hard at the first broken link; Priority degrades gracefully (worst case: all
ranks illegal → one notification). Neither can catch "still legal but now suboptimal" — Priority
only falls through on _illegal_, not _bad_. That ceiling is accepted, not designed around (owner
decision): the info button states it honestly so an auto-played legal-but-bad move reads as the
opted-in tradeoff, not a misplay.
- Sequential is strongest in 2p (one opponent action between your turns) and increasingly
speculative at higher counts (~6 opponent actions before your 2nd turn in 4p) — but it stays
available everywhere; the staleness surfacing (§10.6) is how the risk is communicated rather than
prevented.
- Good Priority use cases that aren't obvious: **pass-and-take-booster** ("pass taking booster A > B
> C") and any contested claim (federation token, advanced tech, artifact) — exactly the scenarios
> the #69 race-condition audit enumerated.
### 10.3 Data model delta (extends §3)
```sql
-- Distinguish the two queue interpretations. All of a seat's rows share one mode.
alter table public.premoves
add column if not exists mode text not null default 'sequential'
check (mode in ('sequential','priority'));
```
`seq` keeps its meaning "1 = first to attempt": turn-order in Sequential, priority-rank in Priority.
No other schema change — `premove_failures`, RLS, and the realtime-exclusion all carry over.
### 10.4 RPC deltas (extend §4a)
- **`queue_premove` gains `p_mode text`.** Assert the seat's existing rows (if any) are the **same
mode**; reject a mismatch with a distinct error the client turns into "switch mode clears your
queue first." `seq = coalesce(max(seq),0)+1` as today.
- **`cancel_all_premoves(p_game_id, p_seat) returns void`** _(new)_ — clears a seat's whole queue in
one call (used by the mode toggle, and by §10.7 reconciliation). Security-definer, seat-ownership
asserted, same grant treatment as the other authenticated RPCs.
- **`reorder_premove(p_game_id, p_seat, p_seq, p_direction text) returns void`** _(new, Priority
only)_ — swaps a row's `seq` with its neighbour (up/down) so the user can re-rank without
cancel+rebuild. Reject on a sequential queue (order there is turn-order, not a preference).
- **`cancel_premove`** (single-row) keeps working; the **cascade** on a sequential cancel (§10.5) is
applied client-side by also cancelling the dependent higher-`seq` rows, or add a
`p_cascade boolean` — implementer's choice, but the _behaviour_ is mandatory.
### 10.5 Executor delta — the resolver branches on `mode` (extends §4c)
The single most important Phase 3 change: **factor the queue-resolution decision into one shared
helper** (`resolvePremoveQueue(engine, seat, rows, mode)` in a spot both the client fast-path in
`host.ts` and the `resolve-automation` edge function import — same pattern as `auto-decide.ts`), so
online and offline resolution are byte-identical. It still resolves **exactly one committed turn per
invocation** and commits **one `moves` row** (the one-row-per-turn / `seq` invariant is unchanged).
- **Sequential** (this is essentially today's Phase 1 behaviour + cascade cleanup):
- Take the lowest-`seq` row. `engine.move()` on a clone.
- **success + `newTurn`** → `commit_automated_turn`, delete that row. Remaining rows are untouched;
because the resolver always takes the lowest remaining `seq`, **#2 automatically becomes the next
to fire** (the UI renumbers for display — §10.6). No renumbering write needed.
- **throws** → delete that row **and cascade-delete every higher-`seq` row for the seat** (they
were previewed assuming this one landed), write **one** `premove_failures` row noting the cascade
("premove 1 failed; 2–3 discarded — they depended on it"). Do not attempt the rest.
- **applies but `!newTurn`** → same as Phase 1 (delete, failure row "did not complete a turn").
- **Priority**:
- Iterate rows in ascending `seq` (rank 1 first). For each, `engine.move()` on a **fresh clone**.
- First rank that **applies + `newTurn`** → `commit_automated_turn`, then **delete ALL of the
seat's premove rows** (the one turn is used). A success toast names the rank that fired and, if
it wasn't rank 1, that the higher choice was no longer possible.
- A rank that **throws** is silently skipped to the next rank (no failure row).
- **All ranks illegal** → write **one** `premove_failures` row ("none of your N ranked premoves
were legal") and delete all the seat's rows.
- Still one clone-`move()` per rank but only one `commit_automated_turn` — read-only clones for the
losers, so the one-row-per-turn invariant holds.
- **`seq_conflict` from the commit stays a silent no-op** (§4c finding #6) in both modes.
- **Stale-trigger guard and the `phase === RoundMove` gate are unchanged** (§4c steps 2–3); the
Phase 2 `RoundLeech` auto-charge branch is orthogonal and runs before either mode's `RoundMove`
resolution, exactly as today.
### 10.6 UI / UX (extends §7)
Board, **off-turn**, stays uncluttered — just two small affordances in the sticky command area:
1. **`Plan my move ▸`** — enters premove-compose mode on the board (the existing Phase 1 banner +
dashed "queue" affordances). Composing must happen on the board; "Queue this move" appends the
assembled complete turn to the current-mode list at the next `seq`.
2. **`⚡ Premoves (n) ▸`** pill (count badge) — opens the **overview modal**, which is the whole
management surface (moved off the board per owner decision 2026-07-05, to protect mobile
real-estate):
- **Mode toggle** `Sequential | Priority` (switching clears the queue, with a confirm).
- The **list**: numbered chain (Sequential) or ranked, **reorderable** up/down (Priority). Per row:
plain-language turn summary ("Build mine at 3x2, then charge 2"), **staleness** ("queued 12
moves ago" from `queued_move_count` vs current `move_count`), **live-legality** (re-run the
preview on each incoming `moves` row and grey out rows gone illegal — "no longer possible"),
and ✕ cancel (cascade in Sequential, promote-next in Priority).
- An **ⓘ info button** (Silent-Auction-style modal) explaining both modes, the legal-but-suboptimal
caveat, and that leech needs auto-charge for full offline.
3. **Inline "will fire" line** when you open about-to-be-your-turn ("Priority 1 will play: …" /
"Next: Build mine at 3x2") so the common case needs **zero taps** — the single best trust-builder,
and nearly free because the preview already re-runs on each `moves` row.
4. **`auto_charge = 'ask'` inline warning at queue time**: "a charge decision before your turn will
still pause until you're online — enable auto-charge to fully automate." Closes the #1 "why didn't
my premove run" confusion.
**Notifications:** **failures push** (existing infra, §7 tie-in). **Successes are quiet, in-app
only** — the log tag "played from your queue" plus a subtle toast on next open; **no push on
success** (a fast async game auto-plays many turns; a push each would be spam). Priority success
toast names the rank that fired; sequential failure toast notes the cascade.
### 10.7 Reconciliation rules (answers the "manual move / round advance" questions)
- A premove **fires instantly** when it becomes your turn (fast-path if the tab is open, edge
function if offline) — there is no "manually move instead of #1" step in the normal flow. To do
something different, cancel/edit during the opponents' turns.
- On fire / round advance: the consumed row is deleted; the resolver always plays the lowest
remaining `seq`, so **#2 becomes #1, #3 becomes #2**, and the modal renumbers. (Priority deletes
the whole set on fire, so there is nothing to renumber.)
- **Manual move while a queue exists** (rare — e.g. you moved on another device, or fast-path didn't
run): the seat's queue is now stale for a turn that already happened. On the next `moves` refetch,
reconcile: Sequential → pop the consumed head (or `cancel_all` if it can't be matched); Priority →
`cancel_all` (the list was for the turn you just took). A stale row that survives fails safely at
its next turn (illegal → notification), so this is a cleanliness measure, not a correctness
backstop.
- **Manual pass** clears the seat's queue (the round-boundary open-decision from §8, now resolved:
clear on pass).
### 10.8 Testing delta (extends §9)
- Engine/resolver unit tests for **Sequential**: chain preview (#2 built on #1's clone); success →
consume + next-becomes-head; first-link throw → cascade-delete + single failure row.
- Resolver unit tests for **Priority**: rank-1 legal → fires + clears all; rank-1 illegal, rank-2
legal → rank-2 fires (toast names it) + clears all; all illegal → single failure row + clears all.
- **Shared-resolver parity**: assert `host.ts` fast-path and the edge function produce identical
decisions for the same `(engine, seat, rows, mode)` (extends the finding-#8 parity discipline).
- Mode-guard tests: `queue_premove` rejects a mismatched `mode`; `reorder_premove` rejects on a
sequential queue; `cancel_all_premoves` clears both.
- E2E: queue a 2-deep sequential chain in one browser, advance from the other, assert both fire in
order and the overview renumbers; queue a 3-rank priority set where rank 1 is made illegal by the
other browser, assert rank 2 fires.
---
## 9. Testing strategy
- **Engine unit tests** for `previewAvailableCommandsFor` (the three null cases; a real RoundMove
case; the fidelity check in §2).
- **Host unit tests** for the `seq_conflict`-silent fix and the client fast-path (extend
`host.spec.ts` style — mocked backend, asserts silent resync on `seq_conflict`, commits premove on
own turn).
- **Edge-function tests** for `resolve-automation`: RoundMove premove success/commit; premove throws
→ failure row + premove deleted, no cascade; incomplete-turn → failure row; wrong-phase (RoundLeech)
→ no-op, premove untouched; stale trigger (`playerToMove !== seat`) → no-op; `seq_conflict` → silent
no-op. Phase 2: RoundLeech + `auto_charge` → one auto-charge turn committed; `auto_charge = 'ask'`
→ no-op.
- **Retained parity test (finding #8):** replay a recorded game's move log through the **bundled**
engine and through the client engine; assert identical `playerToMove / round / phase /
moveHistory.length` at every step. This is the drift guard — keep it in CI, don't delete it after
Phase 0.
- **E2E:** extend `viewer/e2e/hosted-multiplayer.e2e.js` (two real browsers vs. the live project) to
queue a premove in one browser, advance the game from the other until the premover's turn, and
assert the premove auto-plays and fans out.
---
## Phase 0 checklist (START HERE — read-only, no writes, no trigger, nothing autonomous)
> The live Supabase project is **`gaia-lost-fleet`** — find its ref via `list_projects` (do not
> assume). This is a **live project with real running games**; both steps below are strictly
> read-only (fetch + replay + compare). If you are ever unsure whether an action mutates anything,
> **stop and ask.**
- [ ] Confirm the live schema state first (`BACKEND.md §14` notes migrations `0006/0007` may not be
applied live) — read-only via MCP, so Phase 1 migrations stack on the right base.
- [ ] Set up the bundle: `engine-entry.ts` (§1), the esbuild `build:edge-engine` script, produce
`supabase/functions/_shared/engine.bundle.js`. Confirm it imports under Deno
(`deno check`) — watch `seedrandom`/`shuffle-seed`/host globals and bare Node built-ins (§1).
- [ ] Write `supabase/functions/_spike-engine-replay/index.ts`: given `{game_id}`, fetch
`games`/`moves` (service role), replay via the bundled engine, return
`{ playerToMove, round, phase, moveHistoryLength }` as JSON. **No writes.**
- [ ] Deploy it; invoke it (curl / dashboard test-invoke) against a **fresh scratch 2-player test
game** created for this purpose; confirm parity with what the running viewer computes for that
same game at the same move count.
- [ ] Invoke it against **one real existing game's** `game_id`; compare its output to what the viewer
shows for that game at the same move count (catches Lost Fleet ship actions, artifacts,
federations, auction — whatever a live history exercises that a clean game wouldn't).
- [ ] Record the result here (pass/fail; if fail, what broke and how the bundling approach needs to
change) **before** starting Phase 1.
- [ ] Delete/disable the spike function once confirmed (Phase 1 introduces the real
`resolve-automation` from scratch, informed by what Phase 0 learned).
- [ ] Turn the scratch-game replay into the **retained parity test** (§9, finding #8) rather than
throwing that harness away.
### Phase 0 result (filled in 2026-07-05)
- **Date:** 2026-07-05
- **Pass / fail: PASS.** The fork's actual engine (with Lost Fleet) bundles to a single ESM file via
esbuild and produces byte-identical replay results (`playerToMove`/`round`/`phase`/
`moveHistory.length`) to the plain TypeScript engine, for both a fresh scratch game and a real
live game exercising Lost Fleet ship actions, artifacts, and spaceship actions.
- **Live schema state (checklist item 1):** confirmed via `list_migrations` + a direct `pg_proc`
query. The _functions_ for migrations `0006_delete_game.sql` and `0007_registered_user_invites.sql`
**do exist live** (`delete_game`, `list_registered_users`, and `create_game` with the `user_id`-based
invite signature all present) — but `supabase_migrations.schema_migrations` jumps straight from
`drop_stale_create_game_overload` (0005) to `0008_admin_only_create_game`, skipping 0006/0007
entirely. Someone applied 0006/0007's SQL directly (dashboard SQL editor or similar), bypassing
migration tracking. **Net effect: the live schema is functionally at 0009** (confirmed: `games` has
`current_round`, `players` has `faction`/`score`, `commit_turn` has the full 8-arg signature) — so
Phase 1's new migration can safely build on top of everything through 0009. The only wrinkle: if
anyone ever runs the local `0006_delete_game.sql`/`0007_registered_user_invites.sql` files through a
strict sequential-migration tool, they'll "re-apply" — harmless since both are pure
`create or replace function` + idempotent grants, but worth knowing so it doesn't look like a
live/local drift bug.
- **Bundling approach that worked:** `esbuild --bundle --format=esm --platform=neutral`, entry point
`supabase/functions/_shared/engine-entry.ts` (re-exports `Engine` from `engine/src/engine` and
`Phase` from `engine/src/enums` — **not** from `engine/src/engine`, which imports `Phase` but never
re-exports it; the original plan snippet had this wrong). Two extra flags beyond the plan's original
spec, both required:
- `--alias:assert=node:assert --external:node:assert` — the engine uses bare `import assert from
"assert"` throughout (17+ files); Deno has no bare `"assert"` module, but does resolve `"node:
assert"` natively.
- `--banner:js="globalThis.seedrandom=globalThis.seedrandom;"` — see the surprise below. Everything
else (lodash, hexagrid, seedrandom, shuffle-seed, semver-compare, eventemitter3) bundles cleanly
with **no** import-map or externalization needed; tried externalizing all six to Deno's native
`npm:` specifiers to shrink the bundle, but both `lodash` and `eventemitter3`'s CJS exports aren't
statically analyzable for named imports (`import { set } from "npm:lodash@..."` fails under Deno
with "does not provide an export named 'set'"), so full self-contained bundling (the plan's
original recommendation) is correct, not just simpler.
- `npm run build:edge-engine` (added to root `package.json`) wraps this so it's a repeatable command,
not a hand-run one-off.
- **The single most surprising thing about running the engine in Deno:** `shuffle-seed@1.1.6`'s own
source (`shuffleSeed.shuffle`, used by `engine/src/setup.ts`/`map.ts`/`factions.ts`) relies on a
genuine **Node sloppy-mode quirk**, not just a missing global. Its `index.js` does
`require('seedrandom')` (which, as a side effect, sets `Math.seedrandom` unconditionally), then its
own `shuffle-seed.js` does `if (Math.seedrandom) seedrandom = Math.seedrandom;` — an assignment to
an **undeclared** bare identifier. In non-strict Node CommonJS this silently creates an implicit
global (`globalThis.seedrandom`) that the rest of the file then reads. **ES modules are always
strict mode**, and strict mode turns that same assignment into a hard `ReferenceError: seedrandom is
not defined` — so the bundle threw immediately on the very first shuffle, deep inside setup/map
generation, with a confusing stack trace pointing at `shuffle-seed`'s own vendored code. Fix: predeclare
a global binding with a `--banner:js` prelude (`globalThis.seedrandom=globalThis.seedrandom;`) so the
later assignment lands on an _existing_ global instead of an undeclared one (assigning to an
existing global property is legal in strict mode; only creating a new implicit one isn't). Confirmed
fixed by running the exact fixture from `viewer/src/logic/auto-decide.spec.ts` through the bundle
under `deno run` — shuffle/setup and a real leech auto-decide (`autoDecideChargePower`) both work.
Nothing else was surprising: `assert`/`node:assert` aliasing was the only other Deno-specific
adjustment needed, and there were no `crypto`/`self`/`window` issues from `seedrandom` itself (it
degrades gracefully without them; only `shuffle-seed`'s own global-patching trick needed the fix
above).
- **What was actually verified, and how (see "a practical constraint" below for why it's split this
way):**
1. **Full real engine, locally under `deno run`:** the committed `supabase/functions/_shared/
engine.bundle.js` (built from this fork's real `engine/src`, not npm) correctly replays a base-game
2p setup fixture and a Lost Fleet setup fixture, reaching the expected phase/player/round every
time, including a real leech auto-decide via the also-bundled `autoDecideChargePower`.
2. **Full real engine, parity against real Supabase data:** fetched (read-only, via
`mcp__Supabase__execute_sql`) the move logs for (a) a fresh scratch 2-player test game created for
this purpose (`00000000-0000-0000-0000-000000000001`, deleted again after use) and (b) one real,
currently-active 4-player Lost Fleet game (39-40 moves in, exercising ship builds, spaceship
actions, artifact examination, deep-space tiles). Replayed both move logs through the bundle
(`deno run`) **and** through the real TypeScript engine (`ts-node`), and the two outputs
(`playerToMove`/`round`/`phase`/`moveHistory.length`) were byte-identical in both cases.
3. **Bundling mechanism, live on the actual deployed Supabase Edge Runtime:** deployed a small
"canary" function (`spike-deno-canary`, since deleted/disabled — see below) built with the
identical esbuild flags/banner, bundling the same real npm deps the engine depends on for
randomness/shuffling (`seedrandom`, `shuffle-seed`, plus `eventemitter3`/`semver-compare`).
Invoked it live via `curl` against the real project (`https://mitawjpdxkheascdiffz.supabase.co/
functions/v1/spike-deno-canary`) and got HTTP 200 with output identical to the local `deno run`
result — confirming the exact bundling/banner-shim approach works on Supabase's actual Edge
Runtime, not only the local Deno CLI.
4. **A practical constraint that shaped the above:** the full self-contained bundle is 566KB
unminified / ~230KB minified. Getting that much text into (and back out of) a single tool-call
argument for `deploy_edge_function` is impractical in an assistant session (the minified form
collapses to a handful of 100–170KB _single lines_, which can't even be paginated in; a
line-wrapped/prettified form is readable but pushes total size past what's sensible to relay
twice through one session). Rather than force it, step 3 substitutes a much smaller
same-dependency canary to prove the live-Supabase-Deno-Runtime leg specifically, while steps 1-2
use the real, full, committed bundle for the actual replay-correctness proof (just executed via
local `deno run` instead of an HTTP round trip). **This is a real operational finding for Phase
1:** don't plan on deploying `resolve-automation` (which needs this same full bundle) by having an
assistant paste its content into a tool call each time engine/src changes — that doesn't scale
past this one spike. Phase 1 should deploy via the Supabase CLI (`supabase functions deploy`) from
a normal shell/CI context (e.g. a GitHub Action with a stored `SUPABASE_ACCESS_TOKEN`), which
reads the built file straight off disk with no such size ceiling.
5. **Retained parity test (finding #8, checklist's last item):** turned into
`engine/edge-bundle-parity.spec.ts` (runs as part of the normal `npm test` / mocha suite, no Deno
dependency needed since the bundle is plain ESM that Node can also `import()`) — replays the same
base-game and Lost Fleet fixtures through both the real engine and the dynamically-imported bundle
and asserts identical results; skips itself (doesn't fail) if the bundle hasn't been built yet.
Full suite: **585/585 passing** (583 previous + this file's 2 new tests) after adding it.
- **Anything that needs to change before Phase 1:**
1. Phase 1's actual `resolve-automation` deploy should go through the Supabase CLI /
CI, not manual MCP tool calls with inline content (see the practical constraint above).
2. Nothing about the schema needs to change — Phase 1's migration can assume 0001-0009 are all live
(see the schema-state finding above), but should apply cleanly via `mcp__Supabase__apply_migration`
(this session's tool) to keep migration tracking consistent going forward, rather than raw
`execute_sql`.
3. Nothing about the vendoring/bundling approach needs to change — `engine-entry.ts` + `npm run
build:edge-engine` + the seedrandom banner are ready to reuse as-is for the real
`resolve-automation` function (which will also need `auto-decide.ts`'s exports for Phase 2, already
included in `engine-entry.ts`).

9034
docs/lost-fleet/PROGRESS.md Normal file

File diff suppressed because it is too large Load diff

42
docs/lost-fleet/README.md Normal file
View file

@ -0,0 +1,42 @@
# Lost Fleet — project working notes
This folder is the **source of truth** for adding the official _Gaia Project: The Lost Fleet_
expansion to this fork of the open-source `boardgamers/gaia-project` engine + viewer, plus a thin
private Supabase multiplayer backend for invite-only async play among friends who own the game.
> 🟢 **New session / "what do I do next?" → read [`PROGRESS.md`](PROGRESS.md) first.** It's the
> running state + prioritized next actions, kept current each session.
## Canonical documents (read in this order)
1. **`rulebook-v1.0.pdf`** — the official rulebook (v1.0). The PDF holds the component artwork.
2. **`rulebook-v1.0.txt`** — searchable text layer extracted from the PDF (`pdftotext -layout`).
Prose is complete here; **numeric values that live only as artwork are NOT in the text** (faction
income strings, terraform layouts, spaceship action spaces, tile counts, the p.16 faction-summary
deltas — p.16 extracts as just a list of faction names).
3. **`COMPONENTS.md`** — full physical-component inventory + implementation status tracker.
4. **`RULES_CLARIFICATIONS.md`** — the authoritative ledger for every value/rule not stated plainly
in prose. Trust this file over re-deriving. Architecture decisions are in §A; the locked
`Expansion` enum shape is §A1; the errata-check result is §K.
## Status (as of 2026-06-29 — superseded almost entirely by PROGRESS.md; this section is
historical context only, not a current tracker)
- ☑ Rulebook + planning docs imported and version-controlled.
- ☑ Errata check done: **no official errata exists**; v1.0 is authoritative (§K).
- ☑ `Expansion` enum restructure (A1) decided and locked, verified against `engine/src/enums.ts`.
- ☑ Engine implementation behind the `Expansion.LostFleet` flag is essentially complete: 467/467
engine tests pass, all 12 Spaceship Board actions, Explore/federation/Standard-Tech claim hooks,
both faction specials, and the 6 Advanced Tech tiles are implemented and tested. See
`PROGRESS.md`'s "Done so far" list for the full numbered history.
- ☐ Viewer-side Lost Fleet UI (map rendering, spaceship board panels, player-color pieces) — not
started yet; see `PROGRESS.md`'s "Next actions".
## Repo setup
- Cloned from upstream `boardgamers/gaia-project`; that remote was originally named **`upstream`**.
- `origin` is now `kimphamnguyen/gaia-lost-fleet` on GitHub (private). The active branch is
`claude/lost-fleet-viewer-support-95lled`; `master` is kept fast-forwarded to match it and is the
Vercel production deploy target.
- Monorepo (pnpm workspaces): `engine/`, `viewer/`, `old-ui/`. Engine tests: `engine/` → `npm test`.

View file

@ -0,0 +1,847 @@
# Lost Fleet — Rules Clarifications & Derived Values
> **Purpose:** The single source of truth for every rule/value that is NOT stated plainly in the
> rulebook prose — values read off component artwork, inferred interactions, errata corrections,
> and judgment calls. A future Claude Code session should trust THIS file over re-deriving.
>
> **Rulebook version:** 1.0. **Errata checked against BGG:** ☑ CHECKED 2026-06-25 — see §K below.
> **Result: no official errata/FAQ document exists for Lost Fleet.** The v1.0 rulebook is authoritative.
## How to use this file
Every entry has:
- **Value/Rule** — the actual answer (the effect text)
- **Source** — one of: `RULEBOOK-TEXT p.N` | `BOARD-ART <component>` | `ERRATA <link>` | `COMMUNITY <link>` | `OUR-RULING`
- **Confidence** — `CONFIRMED` (read directly / official) | `INFERRED` (reasoned, unverified) | `TODO` (placeholder, needs filling)
- **Depiction** — how the viewer will render this component, in our own SVG style (see below).
Required for every component-type entry (tiles, tokens, boards); not needed for pure numeric/
text rules that have no physical card.
When you read a value off a physical/rendered component, replace the placeholder, set Source =
`BOARD-ART <component name/seed>` (a text pointer to _where_ it was confirmed, never the image
file itself — see "Art policy" below), and Confidence = `CONFIRMED`.
### Art policy: original image vs. our depiction
We never commit official Lost Fleet artwork (scans, randomizer screenshots, photos) into this
repo — copyrighted third-party game art, and the project already keeps everything else
text-only (see `PROGRESS.md` "Done so far" #1: "no third-party art committed"). Source images are
a _reference used once to derive the rule and the depiction_, then discarded — only the derived
text (effect + depiction plan) is kept here. Concretely, each component-type entry has three parts:
1. **Original component** — identified by name (Source line), not stored as a file.
2. **Depiction** — how it's drawn in the viewer, reusing existing house style/components instead of
replicating scanned art (already the stated viewer principle for Lost Fleet — see `PROGRESS.md`
"Build order" #2). E.g. "icon row like `ResearchTile.vue`'s tech-content slot, new federation-gold
border" rather than a redrawn version of the physical tile's background art.
3. **Value/Rule** — the actual game-mechanical effect, in engine-implementable terms.
---
## A. ARCHITECTURE DECISIONS (locked)
- **A1. Expansion model.** Lost Fleet is its own expansion, NOT combinable with Frontiers.
Keep Frontiers code in the repo as reference/reuse (ships, exploration, range helpers overlap).
Source: `OUR-RULING`. Confidence: CONFIRMED.
**LOCKED enum shape (approved 2026-06-25, repo-verified against `engine/src/enums.ts`):**
```ts
export enum Expansion {
// 1 was the old spaceships expansion
None = 0,
Frontiers = 2, // value UNCHANGED — keeps recorded-game fixtures (serialize "2") valid
LostFleet = 4, // new, a distinct bit so it can never collide with a Frontiers check
All = Frontiers | LostFleet, // = 6 — "all content" sentinel for `.values()` enumeration ONLY,
// never a valid game-config selection
}
```
Verified facts that shaped this:
- Current real enum is `None=0, Frontiers=2, All=2` (NOT `All=2` as additive — `All` aliases Frontiers).
- **`Expansion.All` is used in 8 sites** (`player-data.ts`, `faction-boards/types.ts`, viewer charts,
`available/ships.ts`, old-ui) as a "give me every value incl. expansion content" argument to the
`Xxx.values(expansions)` filter helpers. It therefore **cannot be dropped**; it is redefined as
`Frontiers | LostFleet = 6` so it means "all content" once LostFleet content is added.
- The `.values()` filter helpers and game-config checks currently use **strict equality**
(`expansions === Expansion.Frontiers`) — ~12 such sites (9 in `enums.ts`, plus `research-tracks.ts`,
`available/buildings.ts`, viewer `ResearchTile.vue`, `Rules.vue`). To make `All=6` include BOTH
expansions' content, **migrate these to bitwise** `(expansions & Expansion.Frontiers) !== 0`, and add
parallel `(expansions & Expansion.LostFleet)` branches for new content. Because values are
bit-disjoint (2 vs 4), a real single-selection game config (`expansions = Frontiers` only) still
behaves correctly under bitwise checks, and `LostFleet & Frontiers === 0` (no false matches).
- Add a `hasExpansion(expansions, exp)` helper = `(expansions & exp) !== 0` to centralize the bitwise
test (makes the find-replace migration clean and keeps intent readable). Now justified (not optional).
- **Mutual exclusivity** is enforced at game init: the selected `expansions` config must be exactly one
of `None` / `Frontiers` / `LostFleet`; `All` is rejected as a config value (it is enumeration-only).
- Total migration surface: ~20 files touch `Expansion.*`; most are harmless `Expansion.All` enumeration
sites that keep working; the strict-equality config checks are the ones to convert to bitwise.
Source: `OUR-RULING` + repo verification. Confidence: CONFIRMED.
- **A2. Undo.** Players may undo freely WITHIN their own turn. A turn is committed (and synced to
others) only when the full turn completes — mirrors existing `self-contained.ts` "save only if a
full turn was done." Source: `OUR-RULING`. Confidence: CONFIRMED.
- **A3. No Automa / no solo.** Source: `OUR-RULING`. Confidence: CONFIRMED.
- **A4. No-home-planet factions.** The 4 new factions have no home _terrain_ planet (they start on
Asteroid/Protoplanet). **Same-color exclusivity still applies (owner-confirmed 2026-06-27): only one
faction per color per game, exactly like the base game.** The 4 new factions form 2 color pairs —
Tinkeroids↔Darkanians (Asteroid/turquoise) and Moweyds↔Space Giants (Protoplanet/pink) — and are
mutually exclusive within each pair. Implementation: give each its shared planet in the `factions.ts`
map so the existing `oppositeFaction()` pairing enforces this unchanged. The ONLY thing to guard is
terraform cost: `factionPlanet()` feeds `terraformingStepsRequired()`, whose planet-cycle math is
meaningless for these factions (their cost is a flat/board rule, §B2/B4/B5) — so the terraform path,
not the pairing path, needs the guarded branch. Source: `RULEBOOK-TEXT p.7` + `OUR-RULING`
(same-color exclusivity). Confidence: CONFIRMED.
---
## B. NEW FACTION VALUES (fill from faction boards + p.16)
### B1. Tinkeroids — start planet: Asteroid
- Starting resources (one-time): **2k, 4o, 15c, 1q** + **1 step Science track**.
→ engine income[0] ≈ `"2k,4o,15c,q,up-sci"`.
- Recurring base income (income[1]): **+1k, +1o** → `"+o,k"`.
- Starting power: **Area I = 4, Area II = 2** (`power.area1=4, area2=2`).
- Planetary Institute income: **+4pw, +1 token(B1)** (standard) → `["+4pw","+t"]`.
- TS/RL/AC incomes: standard (TS +3/4/4/5c, RL +k+tech, AC1 +2k, AC2 =>q). No building-cost deltas.
- Source: `COMMUNITY (faction-overview PDF, pp.1-2 table; base-faction rows in same table match known
base values → high trust)`. Confidence: **CONFIRMED** (owner-verified 2026-06-25: 2k start + 4/2 power split).
- Terraform: 3 steps for the "cost-3" base colors, 1 step for all others; the cost-3 set is
determined at setup via the Moweyds/Tinkeroids Terraforming board (see revised §B5).
**Gaia planet: making it habitable costs 2 Q.I.C.s.** Source: `rulebook-v1.0.pdf`,
p.13, Appendix I, Tinkeroids: “Making a Gaia planet habitable costs you 2 Q.I.C.s.”
This supersedes the incorrect 2026-06-27 clarification claiming 1 Q.I.C.; that claim
contradicted the cited rulebook. A mine replacing your Gaiaformer still pays no habitability cost
and is considered accessible (base rules p.11,
[official English rulebook](https://www.feuerland-spiele.de/fileadmin/game/Gaia_Project/GAIA_PROJECT_EN_rules_Web.pdf)).
Otherwise, range-extension Q.I.C.s are additional to the habitability cost. This is a faction
ability, not a blanket surcharge for every faction playing with Lost Fleet.
- Starts with Planetary Institute (not mines), placed in stage 2. Source: p.13. CONFIRMED.
- 6 Tinkering tiles (3 for rounds 1-3, 3 for 4-6); PI: once/round use current Tinkering tile as action.
Individual tile effects, all confirmed (owner board-read 2026-06-27):
- **Rounds 1-3** (one of these 3 is the active Tinkering tile each round): (1) terraform 1 step free;
(2) charge 4 power; (3) gain 1 Q.I.C.
- **Rounds 4-6:** (1) terraform 3 steps free; (2) gain 3 knowledge; (3) gain 2 Q.I.C.
- Source: `BOARD-ART tinkering tiles` (owner board-read 2026-06-27). Confidence: CONFIRMED.
### B2. Darkanians — start planet: Asteroid
- Starting resources (one-time): **3k, 7o, 15c, 1q** + **1 step Navigation AND 1 step Economy**.
→ engine income[0] ≈ `"3k,7o,15c,q,up-nav,up-eco"`. (Note: 7 ore is unusually high — confirm.)
- Recurring base income: **+1k, +1o** → `"+o,k"`.
- Starting power: **Area I = 4, Area II = 2**.
- PI income: **+4pw, +1 token(B1)** (standard). TS/RL/AC standard; no cost deltas.
- Source: `COMMUNITY (faction-overview PDF table)`. Confidence: **CONFIRMED** (owner-verified 2026-06-25)
(esp. 7 ore start + the two research advances Nav+Eco).
- Starts with 1 mine (stage 2). **Standard (terrain) planet = a flat 1 terraform step**, any color.
**Gaia planet: a mine costs 2 Q.I.C. instead of the base 1** — a faction-specific surcharge on the
mine-on-Gaia cost (maps to `gaiaFormingCost()` in `player.ts`, which is already faction-aware for
Gleens). The gaiaforming PROJECT cost (converting transdim→Gaia) is untouched. Owner-confirmed
2026-06-27. Source: p.13 + owner. CONFIRMED.
- PI: first time colonizing in a Space/Deep Space sector, gain 2c + 1k. Interspace tiles ≠ sectors.
Source: p.13. CONFIRMED.
### B3. Moweyds — start planet: Protoplanet
- Starting resources (one-time): **5k, 6o, 15c, 2q** + **1 step Gaiaforming track**.
→ engine income[0] ≈ `"5k,6o,15c,2q,up-gaia"`. (High start — compensates 1-mine + 0-VP protoplanet.)
- Recurring base income: **+1k, +1o** → `"+o,k"`.
- Starting power: **Area I = 4, Area II = 4**.
- PI income: **+4pw, +1 token(B1)** (standard). TS/RL/AC standard; no cost deltas.
- Source: `COMMUNITY (faction-overview PDF table)`. Confidence: **CONFIRMED** (owner-verified 2026-06-25)
(esp. 5k / 6o / 2q start — notably generous).
- Starts with 1 mine (stage 2) AND an Exploration Shuttle already on T F Mars. Terraform: 3 steps for
the "cost-3" base colors, 1 step for all others; cost-3 set determined at setup via the Terraforming
board (see revised §B5). **Gaia planet: a mine costs the normal 1 Q.I.C. — NOT 2** (corrected
2026-06-27; Tinkeroids, Darkanians & Space Giants pay the 2-Q.I.C. Gaia surcharge). Source: p.13 + owner
2026-06-27. CONFIRMED.
- PI: once/round place a Power Ring (action) on a planet with your building; +2 power value there.
6 Power Rings available. Source: p.13. CONFIRMED.
### B4. Space Giants — start planet: Protoplanet
- Starting resources (one-time): **3k, 6o, 15c, 1q** + **1 step Navigation track**.
→ engine income[0] ≈ `"3k,6o,15c,q,up-nav"`.
- Recurring base income: **+1k, +1o** → `"+o,k"`.
- Starting power: **Area I = 4, Area II = 4**.
- **PI income: +6pw, +1 token(B1)** — NOTE: +6 power, not the standard +4. → `["+6pw","+t"]`.
TS/RL/AC standard; no cost deltas.
- Source: `COMMUNITY (faction-overview PDF table)`. Confidence: **CONFIRMED** (owner-verified 2026-06-25)
(esp. the +6-power PI income — only non-standard building value among the 4 new boards).
- Starts with 1 mine (stage 2). **Standard (terrain) planet = a flat 2 terraform steps**, any color.
Has a "Build a Mine" action with 2 free terraform steps on the Exploration board. **Gaia planet: a
mine costs 2 Q.I.C. instead of the base 1** (same faction-specific mine-on-Gaia surcharge as
Darkanians, §B2 — maps to `gaiaFormingCost()`; gaiaforming project cost untouched). Owner-confirmed
2026-06-27. Source: p.13 + owner. CONFIRMED.
- PI: immediately take 1 tech tile of choice (Upgrade rules apply); once only. Source: p.13. CONFIRMED.
### B5. Moweyds/Tinkeroids Terraforming board — cost-3 color selection (REVISED 2026-06-30, owner-confirmed)
Determines which base planet colors cost 3 terraform steps (vs. 1 for all others) for these two
no-home-planet factions. **This is NOT a blind random draw** (corrects the earlier description).
Source: `RULEBOOK-TEXT p.8` + owner clarifications 2026-06-27 and 2026-06-30. Confidence: CONFIRMED.
- **There are always exactly 3 base colors that cost 3 steps; every other base color costs 1 step.**
- **Opponents' home colors always cost 3, and take priority.** Terraforming toward any color that is
another player's faction home color costs 3 steps. (An opponent that is itself a no-home-planet
faction — e.g. the _other_ new faction in the game — contributes NO color, so the count of
color-bearing opponents can be fewer than playerCount−1.)
- The remaining cost-3 slots (to always reach exactly 3) are filled from the random setup layout:
- **4 players:** the 3 color-bearing opponents normally already supply all 3 → no random fill.
- **3 players:** ~2 opponents' colors + 1 filled from the setup layout.
- **2 players:** 1 opponent's color + 2 filled from the setup layout.
(If a new-faction opponent reduces the color-bearing-opponent count, proportionally more slots are
filled from the layout — the invariant is simply "exactly 3 cost-3 colors total.")
- **Random-fill procedure (owner-resolved 2026-06-30):** at setup the 7 base colors are placed on the
board in a random order (one satellite of each color, p.8). After assigning/removing the mandatory
opponent colors, scan that randomized 7-color row **left to right** and take the next remaining colors
that are **not already another player's home color** until the board reaches exactly 3 cost-3 colors.
If both Tinkeroids and Moweyds are in the game, the duplicate cubes exist only so both players can
remove the mandatory opponent colors first; the remaining filler colors are then taken left-to-right
in turn order from what remains on the shared row.
- **Engine implications:** this is stateful and per-GAME (not precomputable per faction) — the cost-3
set depends on which other factions are in the game. `terraformingStepsRequired` for Tinkeroids/
Moweyds must therefore consult this per-game cost-3 set + the target planet's color, not the base
planet-cycle math (see PROGRESS.md Integration flag 1). Belongs to Chunk 3 (new-faction setup).
---
## C. SPACESHIP BOARDS (fill from the 4 spaceship boards)
For each ship, capture every action space: {type, cost, effect, grid-position} and tech-slot count.
Each ship has exactly 3 action tiles: 1 Q.I.C.-cost action, 1 Power-cost action, and a 3rd that's
either a Knowledge-cost action (Twilight, Rebellion) or a Credit-cost action (T F Mars, Eclipse).
Color→type mapping CONFIRMED: **green = Q.I.C. action, purple = Power action, blue = Knowledge action,
yellow = Credit action.** Source for C1–C4 effects/costs below: owner board-read 2026-06-27. CONFIRMED.
### C1. Twilight (Nautilaks)
- Q.I.C. action: 3 Q.I.C. → re-score (re-trigger) a Federation token you already own (same mechanic as
the base game's federation re-scoring / the Federation-token-shaped Artifact, G6).
- Power action: 3 power (Area III) + 2 ore → build a Research Lab.
- Knowledge action: 1 knowledge → +3 Range, usable for Build a Mine, Gaiaforming, or Exploring a ship.
- Plus **artifact slots** (the asteroid-cluster art) — artifacts seed here; "Examine Artifact" = discard
6 power (any of Areas I/II/III) → 1 artifact (D4). **Artifact slot count = number of players.**
Source: `RULEBOOK-TEXT` p.6: "Take as many Artifact tokens at random as there are players. Place the
tokens face up on the corresponding spaces on the Twilight spaceship." (remaining tokens return to
the box). Owner-confirmed 2026-06-27. CONFIRMED.
- Standard-tech slots: **0 — Twilight never gets a Standard Tech tile slot.** Only Rebellion, T F Mars,
and Eclipse have one each; see the assignment note under C4. Source: `RULEBOOK-TEXT` p.6 (solo-mode
setup names exactly those 3 ships for tile placement, omitting Twilight) + owner-confirmed
2026-06-27. CONFIRMED.
### C2. Rebellion (Vo'Kron) — excluded in 2p
- Q.I.C. action: 3 Q.I.C. → claim a Tech tile (same as the base game's "take a tech tile" Q.I.C. action).
- Power action: 3 power + 1 ore → build a Trading Station, ignoring the normal adjacency-to-a-mine
requirement.
- Knowledge action: 2 knowledge → gain 2 credits + 1 Q.I.C.
- Standard-tech slots: 1 — randomly filled at setup with one of the 3 new Standard Tech tile types
(see the assignment note under C4). Excluded entirely in 2p (ship not in play). Source:
`RULEBOOK-TEXT` p.6. CONFIRMED.
### C3. T F Mars (Gaia Federation)
- Q.I.C. action: 2 Q.I.C. → gain 2 VP + 1 VP per Tech tile you have.
- Power action: charge 2 power → perform the Instant Gaiaforming action (same mechanic as the
"instant" Round Booster, G3: start a Gaia Project on a transdim planet in range without moving
power tokens into the Gaia Area, then immediately transform that planet into Gaia. A Gaiaformer is
still required and occupies the planet until you later build a Mine there, at which point it
returns for reuse in the same round).
- Credit action: 3 credits → terraform 1 step. The mine itself and any further terraforming steps
still cost their normal building/ore price — the 3 credits replace only the ore cost of the first
step (owner-confirmed 2026-06-28: "the 3 coins only covers 1 terraforming step. You still have to
pay for the mine itself and any additional terraforming steps").
At least one terraforming step must be used, so Gaia and home planets are not legal targets,
as for the base-game power action (`RULEBOOK-TEXT` p.14; [rules clarification #76](https://github.com/boardgamers/gaia-project/issues/76)).
- Standard-tech slots: 1 — same mechanism, see the assignment note under C4. Source: `RULEBOOK-TEXT`
p.6. CONFIRMED.
### C4. Eclipse (Eridani Empire)
- Q.I.C. action: 2 Q.I.C. → gain 2 VP + 1 VP per planet type colonized.
- Power action: 3 power + 2 knowledge → advance 1 level on any Research track of your choice.
- Credit action: 6 credits → place a Mine on an Asteroid under normal range rules; the mine itself is
free (the 6 credits is the entire cost — distinct from the standard Asteroid-mine route in E2, which
instead requires consuming a Gaiaformer and waives the normal build cost).
- Standard-tech slots: 1 — same mechanism. **Assignment mechanism (applies to C2–C4 collectively):**
the box holds 4 copies each of the 3 new Standard Tech tile types (12 total), but only 3 are ever in
play (1 of each type, matching G1) — shuffled and dealt at random, 1 tile per ship, onto Rebellion's
/ T F Mars's / Eclipse's single tech slot, so which specific ship gets which tile type varies by
game. In 2p, Rebellion is removed (C2), so only 2 of the 3 drawn tiles get placed (T F Mars +
Eclipse) and the 3rd is returned to the box unused. Source: `RULEBOOK-TEXT` p.6 ("Place the new
Standard Tech tiles at random ... onto the corresponding 2 or 3 spots on the spaceships. If there
are only 2 players, return the remaining Standard Tech tiles to the box.") + solo-mode setup (names
exactly Rebellion/T F Mars/Eclipse). Owner-confirmed 2026-06-27 ("only 1 tech slot per ship... setup
varies which ship has what"). CONFIRMED.
- **Federation-token setup distribution (separate from the Standard Tech assignment above; applies to
all 4 ships, not just C2-C4) — transcribed verbatim from `rulebook-v1.0.txt` p.6, previously found
but not yet quoted in this doc:** _"Take 4 of the new Federation tokens and distribute them on the 4
spaceships at random. If there are 2 players, you will only be playing with 3 spaceships, so take 3
of the new Federation tokens at random and place them onto those 3 spaceships. Return the remaining
Federation tokens to the box."_ So: 3-4p draws 4 of the 8 tokens (one per ship, all 4 ships incl.
Twilight); 2p draws 3 of the 8 (one per ship, Rebellion excluded per C2); the rest go back in the box
unused. CONFIRMED.
### C5. Shuttle-space charge values — CONFIRMED (owner board-read 2026-06-27)
- The Exploration track has **4 spaces per ship**, not 5 (corrects D1's earlier "5 spaces" guess).
Never more than 1 shuttle per ship per player, so a ship caps out at 4 explorers.
- Space 1: no charge (whoever lands here is by definition the first explorer, per D1's exception).
Space 2: charge 2 power. Space 3: charge 2 power. Space 4: charge 4 power.
---
## D. EXPLORATION ACTION (rules captured; values partial)
- D1. Explore: target spaceship tile must be in range from a colonized planet; Q.I.C./special can
extend range. Need a shuttle on your Exploration board; never more than 1 shuttle per ship.
Place on lowest-numbered free space (4 spaces total per ship, see C5); charge as shown unless first
explorer. Source: p.9. CONFIRMED.
- D2. Deploy cost: usually 5 VP. Bal T'aks 7 VP. Taklons also move Brainstone to Gaia Area.
Nevlas & Itars also discard 1 power to supply. Source: p.9. CONFIRMED.
- D3. A ship is EXPLORED, not colonized — range never measured from a ship. Source: p.9. CONFIRMED.
- D4. Examine Artifact (Twilight only): discard 6 power (any of Areas I/II/III) → gain 1 artifact.
Source: p.9. CONFIRMED.
- D5. Per-faction shuttle deploy cost exceptions — RESOLVED, same 3 exceptions as D2, and confirmed
exhaustive (no other faction has a board-printed deploy-cost exception beyond these 3): Bal T'aks
pay 7 VP instead of 5; Taklons additionally move their Brainstone to their Gaia Area; Itars and
Nevlas additionally discard 1 power token to the supply. Every other faction (incl. all 4 new Lost
Fleet factions) pays a flat 5 VP, no extra cost. Source: `RULEBOOK-TEXT` p.9 (verbatim, "Action:
Explore a Lost Fleet Spaceship"). Owner-confirmed 2026-06-27 ("that's it. For everyone else the cost
is 5vp"). CONFIRMED.
---
## E. BASE-ACTION CHANGES (captured)
- E1. Build a Mine — Protoplanet: 3 terraform steps, +6 VP on mine (0 if it's your start planet).
Source: p.10. CONFIRMED.
- E2. Build a Mine — Asteroid: needs an available Gaiaformer; Gaiaformer is consumed (placed on
overlay, unusable rest of game); no 1o+2c build cost paid. Source: p.10. CONFIRMED.
- E3. Form a Federation — may NOT place a satellite on a spaceship tile. Explored ships with a
remaining fed token grant it when you form a federation. **Owner-clarified 2026-06-27: the ship does
NOT need to be adjacent to/part of the federation being formed — merely having it explored (a shuttle
there) is sufficient to grant its fed token whenever you form any federation.** Source: p.10. CONFIRMED.
- E4. Power/Q.I.C. actions — the Research-board Q.I.C. actions are COVERED by the overlay and
unavailable; ship actions replace them (incl. new Knowledge & Credit action types). Source: p.10. CONFIRMED.
- E5. Upgrade — explored ships offer extra Standard Tech; taking it advances 1 research level.
Source: p.10. CONFIRMED.
- E6. Advanced Tech via Scoring Board Extension — the swap applies to exactly **ONE** Advanced Tech
tile, not a change to the bonus-tech mechanism in general. At setup you take the double-sided Scoring
Board Extension and place 1 randomly-drawn Advanced Tech tile onto it (p.5) — that single tile,
whichever it turns out to be, is the only one affected. Confirms owner's elaboration on this part.
- For that tile, the normal **1st** of the base game's 3 conditions for taking an Advanced Tech tile
(player's marker at level 4 or 5 in the matching Research Area) is REPLACED by whichever side of
the Extension is face up: side A = "≥25 VP", side B = "explored 3 of the 4 Lost Fleet spaceships."
- **Side-selection rule — RESOLVED 2026-06-27 (owner ruling, `OUR-RULING`).** The rulebook states the
rule twice (re-checked directly, not a column-merge/OCR artifact — both passages are clean,
unambiguous text):
- p.5, setup: _"Take the Scoring Board Extension. For 2 players, always use the side showing 25
victory points. For 3 or 4 players, use the side showing 3 Exploration Shuttles. In later games,
you can decide at random which side to use."_
- p.10, the Advanced-Tech-conditions paragraph attached to "Action: Build a Mine" (NOT "Action:
Upgrade Existing Structures" — that's a separate paragraph on the same physical page; corrects an
earlier mis-citation): _"Instead, the conditions shown on the Scoring Board Extension are applied
(either you have at least 25 victory points or have explored 3 different spaceships in the Lost
Fleet; the latter condition only applies in 3- and 4-player games)."_
Both passages agree with each other and tie side selection to player count by default: 2p always
uses the 25-VP side; 3-4p default to the ships-explored side, with randomization offered only as an
optional "in later games" house option for 3-4p. **Owner's final call: keep the printed 2p rule as-is
(always forced to the 25-VP side), but for 3-4p, always randomize the side from game 1 onward**
(exercising the rulebook's own "decide at random" option every game, rather than defaulting to the
ships side with optional later randomization). This is now the engine's locked behavior — no conflict
remains; this was never a misprint, just a digital house-rule choice to apply the rulebook's own
randomization option unconditionally for 3-4p.
- **Engine rule, final:** 2 players → side is always "25 VP." 3 or 4 players → side is chosen uniformly
at random (50/50) at setup, every game.
- The **2nd** condition (flip an owned, unflipped Federation token) and **3rd** condition (cover an
owned Standard Tech tile in the matching Research Area with this Advanced Tech tile) are
UNCHANGED — confirms owner's "AND also have a fed token" framing. Reaching level 4/5 on ANY
research track is irrelevant for this one tile, exactly as owner stated.
- Net gate for this one tile (pending the side-selection resolution above): (≥25 VP, or — in 3-4p,
by default — explored 3 of 4 ships) AND flip an unflipped Federation token AND cover a matching
Standard Tech tile. The other 5 Advanced Tech tiles in the game are still taken under the normal,
unmodified 3-condition rule.
Source: `RULEBOOK-TEXT` p.5 (setup/side selection) + p.10 (Advanced-Tech-conditions paragraph) +
`OUR-RULING` (3-4p always-random side selection, owner-confirmed 2026-06-27).
Confidence: CONFIRMED.
## F. RESEARCH TRACK CHANGES
- F1. Adjusted Economy track — levels 3 & 4 income, BOTH tile sides. Source: `BOARD-ART economy tile`
(owner-read 2026-06-27 — corrects an earlier icon-only guess that had levels 3 and 4 swapped).
Confidence: CONFIRMED.
- **Side "pw" (power-charge side):** Level 3 = 1 ore + 2 credits + charge 3 power. Level 4 = 2 ore +
2 credits + charge 2 power.
- **Side "vp" (flat-VP side):** Level 3 = 1 ore + 3 credits + 1 VP. Level 4 = 2 ore + 4 credits + 1 VP.
- One side is placed at random at setup, covering the base game's level-3/4 income symbols on the
Economy research track. Source: `RULEBOOK-TEXT` (placement only, not the reward values). CONFIRMED.
(Base + Frontiers economy strings are in `research-tracks.ts` for reference.)
- F2. No new research track is added (unlike Frontiers' Diplomacy) — Lost Fleet only modifies the
existing Economy track via the F1 overlay tile, it doesn't add a 7th track. Owner-confirmed 2026-06-27.
CONFIRMED.
## G. TILES — EXACT EFFECTS
- G1. New Standard Tech tiles seeded on spaceship boards (3 distinct types; the rulebook's "4 copies
each" is just spare-reprint count — only 1 of each type is ever in play at a time, see COMPONENTS.md
§3/§7). All 3 confirmed:
- **Range tile:** "Your basic range increases by 1 for the rest of the game, as long as the tile is
not covered by an Advanced Tech tile." Source: `RULEBOOK-TEXT` Appendix V. CONFIRMED.
- **Terraform tile:** "Immediately and only once receive a 'Build a Mine' action with up to 2 free
terraforming steps and without paying the cost for that mine. You may spend additional ore to get a
third terraforming step, and Q.I.C.s to increase range." Source: `RULEBOOK-TEXT` Appendix V. CONFIRMED.
- **Resource tile:** gain 1 ore + 3 knowledge. Source: `BOARD-ART` (owner-read 2026-06-27). CONFIRMED.
- G2. New Advanced Tech tiles (6), all confirmed (rulebook Appendix V for 2; owner board-read for the
other 4, 2026-06-27):
- **asteroidpass:** "When you pass, you gain 2 victory points for each asteroid that you have
colonized." Source: RULEBOOK-TEXT. CONFIRMED.
- **big:** Immediately and only once gain **6 VP per Planetary Institute and/or Academy** you've
built (max 3 such buildings per player — 1 PI + 2 Academies — so max 18 VP). Source: `BOARD-ART`
(owner-confirmed 2026-06-27). CONFIRMED. **Corrects an earlier mis-transcription:** Appendix V's
printed text ("Immediately and only once receive victory points for each Planetary Institute
and/or Academy, and for each Deep Space sector in which you have colonized at least 1 planet")
reads as one combined sentence in the `.txt` extraction, but is actually **two separate tiles'**
text concatenated by the same column-flattening artifact already seen elsewhere in this doc (see
E6's mis-citation note) — the first clause ("...for each Planetary Institute and/or Academy") is
`big`; the second clause ("...for each Deep Space sector...") is a different tile, already captured
independently below as `deep` (its specific 4-VP multiplier came from BOARD-ART, since the rulebook
text alone never states a quantity). `big` does NOT also reward Deep Space sectors — owner-confirmed
these are two separate tiles, not one with a combined effect.
- **deep:** Immediately gain 4 VP per Deep Space sector colonized; the Lost Planet counts if it's
placed in a Deep Space sector you hadn't already colonized. Source: BOARD-ART. CONFIRMED.
- **deeppass:** When you pass, gain 2 VP per Deep Space sector colonized (same Lost-Planet caveat as
"deep"). Source: BOARD-ART. CONFIRMED.
- **qaction:** Every time you take a Q.I.C. action, gain 4 VP. Source: BOARD-ART. CONFIRMED.
- **terra:** Every time you terraform 1 step, gain 2 VP (3 steps on one planet = 6 VP; colonizing a
Protoplanet, which costs 3 steps, gives the full 6). Cannot over-terraform for extra VP. Triggers
off ANY action that grants free terraforming steps, including the "terra" New Federation token (3
free steps + build a mine). Source: BOARD-ART. CONFIRMED.
- (`planetpass` is a reskin of the base "planet" tile, not one of these 6 — see G4b below.)
- G3. Round Boosters (4), all confirmed verbatim from rulebook Appendix III:
- **former:** income 1 ore. Pass bonus: 3 VP per Gaiaformer (on Faction board or deployed); none for
Gaiaformers already used to colonize an asteroid. CONFIRMED.
- **planet:** income 1 ore. Pass bonus: 1 VP per planet type colonized. CONFIRMED.
- **deep:** income 3 credits. Pass bonus: 2 VP per Deep Space sector with ≥1 planet colonized. CONFIRMED.
- **instant:** income 2 power. Special action (once): perform "Start a Gaia Project" without moving
power tokens into the Gaia Area, instantly converting a transdim planet (must be in range; Q.I.C.s
may extend range) into a Gaia planet. A Gaiaformer is still required, occupies that planet until
you later build a Mine there, and then returns for reuse exactly like normal/base-game Gaiaforming.
CONFIRMED.
- G4. Round Scoring (3) + Final Scoring (3): text p.14-15, all 6 CONFIRMED verbatim (lab4/sector3/
planet3 round tiles; asteroid/deep/distance final tiles — exact quotes in the scratchpad review doc).
Owner confirmed (2026-06-27) that the planet-type-counting tiles (G4b) explicitly count
asteroids/protoplanets held only via an Artifact (G6) too, even though no mine is physically placed
for those.
- G4b. Planet-type-counting tiles (3 reskins of existing base tiles, owner-confirmed 2026-06-27, same
underlying template, now counting all 11 planet types incl. Asteroid/Protoplanet/Lost Planet):
- Standard Tech `planetk`: immediately gain 1 knowledge per planet type colonized.
- Advanced Tech `planetpass`: when you pass, gain 1 VP per planet type colonized.
- Final Scoring `planet`: most planet types colonized (counts Protoplanet/Asteroid incl. via Artifact,
and the Lost Planet).
- G4c. **Deep Space Sectors do NOT count for the base game's unmodified "most sectors" Final Scoring
tile** (`FinalTile.Sector`/`Condition.Sector` — engine `player.ts`), nor for the 2 base Advanced Tech
tiles that pay per sector (1 ore/sector, 2 VP/sector — same shared `Condition.Sector`). Only a real
Space Sector tile counts as a sector for these; Interspace already didn't count either way. **Source:
OUR-RULING (owner, 2026-07-05) — there is no rulebook text either way** for this specific tile/these
2 tiles (the base game predates Deep Space and Lost Fleet's own appendix only reprints the 3 _new_
Final Scoring tiles, not this pre-existing one). This is deliberately narrower than `Condition.NewSector`
(the `sector3` Round Scoring tile) and Darkanians' PI ability, which DO count Deep Space — those two
have their own explicit rulebook text ("Space sector / Deep Space sector", rulebook p.6/p.13, line 132
above) that this ruling does not override. Do not "fix" `Condition.Sector` to match `Condition.NewSector`
again without re-confirming this ruling — the split is deliberate, not an oversight.
for the other 4 — their gear-shaped badge is VP, not an unidentified resource as previously guessed):
- **c:** Immediately gain 8 VP + 8 credits. CONFIRMED (BOARD-ART).
- **k:** Immediately gain 4 VP + 4 knowledge. CONFIRMED (BOARD-ART).
- **oq:** Immediately gain 4 VP + 2 ore + 1 Q.I.C. CONFIRMED (BOARD-ART).
- **pwt:** Immediately gain 7 VP + 2 power tokens placed directly into Area III (new tokens, not
charged up from Area II, per owner's reading). CONFIRMED (BOARD-ART).
- **range:** Immediately and only once receive a "Build a Mine" action of limitless range without
paying the build cost; ore still pays for terraforming, Q.I.C. still required for Gaia planets.
CONFIRMED (RULEBOOK-TEXT).
- **tech:** Immediately and only once receive 1 Tech tile of choice (same rules as "Upgrade Existing
Structures"). CONFIRMED (RULEBOOK-TEXT).
- **terra:** Immediately and only once receive a "Build a Mine" action with up to 3 free terraforming
steps, without paying the build cost; Q.I.C.s may still increase range. CONFIRMED (RULEBOOK-TEXT).
- **vp:** Immediately gain 12 VP. Unlike base-game 12-VP Federation tokens, this one ALSO has a green
reverse side. CONFIRMED (RULEBOOK-TEXT) for the gold face.
- **Green reverse side — RESOLVED 2026-06-27 (owner clarification, Source: `BOARD-ART` +
`RULEBOOK-TEXT`, Confidence: CONFIRMED).** This is the base game's existing, universal Federation
mechanic, not anything new or per-token-unique: in the base game, EVERY Federation token has a
green reverse side EXCEPT the 12-VP token — flipping a token to its green side lets you discover an
Advanced Tech tile, or research to the highest level of a Research Area, instead of gaining the
gold side's resource reward. In Lost Fleet, this rule is unchanged for all the new tokens too — ALL
8 new Federation tokens (`c`, `k`, `oq`, `pwt`, `range`, `tech`, `terra`, `vp`) have a green side
using this same standard mechanic. The only thing notable about the new `vp` token specifically is
that, unlike its base-game 12-VP counterpart (which has no green side at all), this Lost-Fleet `vp`
token — found on the spaceships — DOES have one, so it can still be flipped for the Advanced
Tech/research benefit despite being a 12-VP token. No per-token green-side variation to track; it's
"has a green side" (all of them) vs. "has no green side" (only the base game's original 12-VP token).
- G6. Artifact tokens (13), all confirmed. 13 distinct names/images, no two alike — simplest reading is
1 copy of each (owner to confirm physical box count if duplicates actually exist). Effects:
- **1 Knowledge + 1 Ore:** ongoing — gain an extra 1 knowledge + 1 ore EVERY income phase (NOT a
one-time examine bonus — corrects an earlier guess). Source: BOARD-ART (owner 2026-06-27). CONFIRMED.
- **3 Credits + 3 Ore:** immediately (one-time, on examine) gain 3 credits + 3 ore. CONFIRMED.
- **3 Knowledge + 1 Q.I.C.:** immediately gain 3 knowledge + 1 Q.I.C. CONFIRMED.
- **5 Credits + 2 Ore:** immediately gain 5 credits + 2 ore. CONFIRMED.
- **Power-charge:** gain 2 power as income, placed in Area III. Source: RULEBOOK-TEXT Appendix VII. CONFIRMED.
- **Asteroid-themed / Protoplanet-themed** (shared template, 7 VP each): immediately and only once
gain 7 VP; the artifact ALSO counts as if you're building a mine and colonizing an asteroid (or
protoplanet) for that mine — not allocated to a sector (no new-sector credit, no 6 VP protoplanet
bonus), no mine physically placed. Source: RULEBOOK-TEXT Appendix VII (verbatim, shared template). CONFIRMED.
- **Research/Knowledge-themed (per-level):** immediately and only once gain 3 VP per level reached in
the matching Research Area (rulebook's own worked example: Level 5 → 15 VP). Source: RULEBOOK-TEXT
Appendix VII. CONFIRMED. ⚠️ Owner's review comment for this row was cut off mid-sentence ("T") —
flag to owner to resend/finish in case it contained a correction.
- **Research-track-themed (generic, count-based):** immediately and only once gain 3 VP for each
Research Area at Level ≥3 (track-agnostic — distinct from the per-level one above). Source:
RULEBOOK-TEXT Appendix VII. CONFIRMED.
- **Federation-token-shaped:** re-score (re-trigger) a Federation token you ALREADY own — gold or
green side, doesn't matter which. Reuses the base game's federation-scoring mechanic, just
re-triggered by this artifact. Source: BOARD-ART (owner 2026-06-27 — corrects the earlier "grants a
new federation token" guess). CONFIRMED.
- **Gaia-Planet-themed:** immediately and only once gain 3 VP per step up the Gaiaforming track (same
per-level-multiplier mechanism as the Research/Knowledge-themed artifact above, applied to the
Gaiaforming track instead of a Research Area). Source: BOARD-ART (owner 2026-06-27). CONFIRMED.
- **Planet-types-themed:** immediately and only once gain 3 VP + 1 VP per planet type colonized
(counts planet types held only via another Artifact's asteroid/protoplanet effect, see above).
Source: BOARD-ART (owner 2026-06-27). CONFIRMED.
- **Deep-Space-themed:** immediately and only once gain 3 VP per Deep Space sector colonized; the
Lost Planet counts if placed in a Deep Space sector you hadn't already colonized. Source: BOARD-ART
(owner 2026-06-27). CONFIRMED.
## H. MAP / SETUP
- H1. Variable Gameboard Layout setup — full procedure (previously only a one-line summary in this
doc; now captured verbatim from a fresh full read of `rulebook-v1.0.txt` p.4-5, 2026-06-27).
Source: `RULEBOOK-TEXT` p.4-5. CONFIRMED.
- **2 players:** Space Sector tiles **01-07** (7 of the base game's 10). Flip Sectors **05, 06, 07**
to their _"black numbers outlined in white"_ side (a Lost-Fleet-specific revised face — see H4).
Randomly pick 1 of Sectors 01-04 for the center; arrange the other 6 around it, sliding each outer
sector 1 space left/right so it only borders the inner sector along 2 spaces (not a full edge
match like the base game) — this opens **6 holes**, 1 space each, around the center sector. Place
the **6 Interspace tiles for 2p** into the holes at random, such that **each spaceship tile ends up
≥5 spaces from every other spaceship tile** (rulebook's suggested method: alternate
holes-with-a-spaceship and holes-without as you place them). Then place the **6 Deep Space Sector
tiles 11-16**, random side up, in the gaps around the outside edge. (H5's "flip tile 16 if <6
asteroids in play" applies here.)
- **3 players:** Space Sector tiles **01-10 except 08** (9 of 10; 08 returns to the box). Sectors
05/06/07 flipped exactly as in 2p. Randomly pick 1 of Sectors 01-04 for the center; arrange 6 random
others around it the same shifted way (6 holes) — then place the **2 remaining** sectors too,
shifted the same way, extending the ring. Place the **8 Interspace tiles for 3p** into the (now
more numerous) holes at random; the spacing rule is phrased differently at this player count: **no
spaceship tile may be within 3 spaces of another** (vs. 2p's "≥5 spaces" framing — see the
engine-implementation note below). Place the **8 Deep Space Sector tiles**, random side up, in the
gaps around the outside edge — **3p-only rule: place 2 Deep Space tiles next to each other in the
larger gap beside the last-placed sector.**
- **4 players:** **All 10** Space Sector tiles. Sectors 05/06/07 stay on their normal _white numbers_
side (4p is the only player count using the base-game-style face for those 3 tiles — no flip).
Randomly pick 2 of Sectors 01-04 and place them adjacent in the center; arrange the other 8 around
them at random, shifted the same way — 10 holes. Place the **10 Interspace tiles for 4p** at
random; same "not within 3 spaces" spacing rule as 3p. Place the (same) **8 Deep Space Sector
tiles**, random side up, in the gaps — no 3p-style "2 adjacent" rule at 4p.
- **Engine-relevant details not previously captured in this doc:**
1. Deep Space tile _count_ is fixed at 8 in the physical set, but 2p games only place 6 of them
(tiles 11-16 explicitly, by number) — 3p/4p both place all 8.
2. Sectors 05/06/07 are genuine double-sided Lost-Fleet components (revised face for 2-3p, stock
base-game face for 4p) — feeds directly into H4 below.
3. **RESOLVED 2026-06-28 (empirical, engine-side):** the Interspace spacing rule's _wording_ changes
by player count (2p: "≥5 spaces," 3-4p: "not within 3 spaces") but is the **same underlying
constraint**, not two different formulas. Computed all pairwise hex-distances between
`findInterspaceHoles()` results at 2p/3p/4p: the only distances that ever occur are
`{3, 5, 6, 7, 8, 9, 10, 11}` — **a distance of 4 never occurs at any player count.** Therefore
"not within 3 spaces" (i.e. distance > 3) and "≥5 spaces" exclude exactly the same set of pairs
(only the distance-3 minimum-adjacent pairs are excluded either way); there is no case where the
two phrasings would disagree. Engine implementation: a single rule, "no two spaceship-bearing
Interspace holes may be at hex-distance ≤ 3 of each other," applies uniformly at 2p/3p/4p.
4. **RESOLVED 2026-06-28 — the 3p-only "place 2 Deep Space tiles next to each other in the larger
gap by the sector you placed last" rule has an exact geometric match, not just an inferred
convention.** All 8 notches are individually uniform in size (same 3-hex triangle, same local
pocket), but checking pairwise hex-adjacency _between_ notches (do any two notches share a hex
border?) found exactly **one adjacent pair at 3p, and zero adjacent pairs at 2p and 4p** — this
is a fixed structural property of `lostFleetSectorCenters()`'s geometry (sector centers are not
randomized, only which physical tile goes where is), so it holds in every 3p game, never in 2p/4p
games, matching the rulebook's "3p-only" framing exactly. The adjacent pair sits where ring sector
index 2 meets _both_ extra sectors (indices 7 and 8, the two sectors added after the base 6-ring
in `lostFleetSectorCenters(3)`) — i.e. right beside index 8, the array's last sector, matching
"the sector you placed last." Engine implementation: find the (3p-only) adjacent notch pair via
hex-adjacency and place 2 Deep Space tiles there instead of the usual 1; no separate "last sector"
bookkeeping is needed since the adjacency check alone reproduces the rule.
5. **Tile shapes (owner-clarified 2026-06-28, was the cause of a long-running layout bug):** an
**Interspace tile is a single hex**, placed only in the interior holes; a **Deep Space tile is a
3-hex triangle**, placed only in the perimeter notches along the outside edge. A 3-hex cluster
appearing _in the interior_ between sectors is therefore a layout DEFECT (the interior must be
clean single-hex holes), not a Deep Space slot. The "slide every outer sector the same way"
rule must be applied consistently or the seam between two inner-adjacent sectors collapses two
interior singles into a 3-hex middle cluster.
6. **Geometry CODED & verified (Chunk 5):** `engine/src/lost-fleet-map.ts` —
`lostFleetSectorCenters(nbPlayers)` (7/9/10 sectors), `findInterspaceHoles()` (6/8/10 isolated
single hexes), `findDeepSpaceNotches()` (6/8/8 three-hex triangles), all with 0 sector overlap
and no adjacent interior holes. Tile data: `DEEP_SPACE_TILES` (§H2), `INTERSPACE_SETS` (§H3).
Not yet wired into a playable `SpaceMap` (planet placement + spacing rules still to do).
7. **Blocker found 2026-06-28, deferred to a future chunk (owner-confirmed):** `GaiaHex.toString()` /
`relativeCoordinates` (`engine/src/gaia-hex.ts`) compute a hex's move-string address (e.g. `"5A2"`)
via a lattice-reduction algorithm built on the base game's `MATCHED_OFFSET` sector spacing. Lost
Fleet sectors use `SHIFTED_OFFSET` instead. Verified by direct round-trip computation: for every
non-origin sector at every player count, this address calculation is wrong (it does not throw —
it silently returns an incorrect/mismatched suffix). Any future chunk that wires Lost Fleet
sectors into a live, playable `SpaceMap` (move parsing, `available/*` command generation, etc.)
must first fix or bypass this addressing system for `SHIFTED_OFFSET`-placed sectors. Chunk 6
(this chunk) works only at the `Grid<GaiaHex>`/geometry level and never calls `.toString()` on a
Lost-Fleet-placed hex, so it is unaffected, but this is a hard prerequisite for any move-command
integration later.
8. **RESOLVED (Gaia 17, 2026-07-09) — the "randomly pick 1/2 of Sectors 01-04 for the center"
restriction above is now enforced in the engine, opt-in.** Previously the engine's
`generateSectorGrid()` (`engine/src/lost-fleet-board.ts`) shuffled the entire tile pool
uniformly, so any tile (including 5-10) could land in the center — an unenforced gap, not a
deliberate house rule. A new `EngineOptions.officialCenterSectors` flag (default `false`, so
every existing/previously-generated seed keeps producing the exact same board) makes
`generateSectorGrid()` draw the center sector(s) from `["1","2","3","4"]` only when set,
exposed as an "Official center-sector rule (1-4)" checkbox in `CreateGame.vue`'s Setup Preview
section. See `engine/src/lost-fleet-board.spec.ts`'s `officialCenterSectors` describe block.
- H2. Deep Space sector tiles (8 physical tiles, 2 sides each = 16 faces, each a 3-hex cluster). Hex
contents read directly off the randomizer art (2026-06-27). Owner does NOT need the art itself
redrawn pixel-for-pixel (own SVG style instead, per Art policy above) but DOES need this composition
data for game logic — explicitly requested, not yet captured anywhere else:
| Tile | Side a | Side b |
| ---- | -------------------------------- | ---------------------------- |
| 11 | Protoplanet, Asteroid, Blank | Asteroid, Blank, Blank |
| 12 | **Transdim**, Protoplanet, Blank | Asteroid, Blank, Blank |
| 13 | **Transdim**, Blank, Asteroid | Blank, Blank, Asteroid |
| 14 | Protoplanet, Blank, Asteroid | Blank, Blank, Asteroid |
| 15 | Protoplanet, Blank, Blank | Protoplanet, Blank, Asteroid |
| 16 | Blank, Blank, Protoplanet | Asteroid, Blank, Asteroid |
| 17 | **Transdim**, Blank, Blank | Blank, Asteroid, Blank |
| 18 | Protoplanet, Blank, Blank | Asteroid, Blank, Blank |
Source: `BOARD-ART` (randomizer asset read). Confidence: CONFIRMED — including the previously
"unidentified" hex. **RESOLVED 2026-06-27:** the hex on tiles 12a/13a/17a (a solid violet/magenta
cratered sphere, no glow) is a **Transdim planet** — confirmed by direct visual match against the
randomizer's own `planet_transdim.png` base-game asset (same purple nebulous/cratered texture,
side-by-side comparison). This is not a new Lost Fleet element; it's the base game's existing
wildcard/ghost planet type (becomes Gaia when converted via Gaiaforming), simply also seeded onto
Deep Space tiles alongside Protoplanet/Asteroid/Blank. Yes — the randomizer site's own asset set was
sufficient to resolve this without needing the physical component; no further owner check needed.
- Extends H5: tile 16 has 0 asteroid hexes on side a vs. 2 on side b — exactly the swing the setup
code keys off (`advcond`-style forced logic) when deciding whether to flip tile 16 to reach the ≥6
asteroid minimum. A full side-b set totals 9 asteroid hexes across all 8 tiles; a full side-a set
totals only 3 — confirms why tile 16 specifically is the one the rulebook calls out to flip.
- H3. Interspace tile contents per player-count set (30 in 4 sets). Structural detail
(`RULEBOOK-TEXT` p.5 sidebar, verbatim) explaining the "4 sets" framing: each Interspace tile has 2
faces — **front** shows one of {Lost Fleet spaceship tile, planet tile (Protoplanet or Asteroid),
blank}; **back** is marked for the player-count set it belongs to ("Only use the tiles that
correspond to your player count"). This implies 4 genuinely distinct physical groups (solo=6, 2p=6,
3p=8, 4p=10 → 30 total), matching this entry's existing count.
- **Per-set composition, owner-confirmed 2026-06-27 (Source: `BOARD-ART interspace tiles`,
Confidence: CONFIRMED):**
| Set | Asteroid | Protoplanet | Spaceships | Blank | Total |
| ---- | -------- | ----------- | ------------------- | ----- | ----- |
| Solo | 2 | 1 | 3 (excl. Rebellion) | 0 | 6 |
| 2p | 2 | 1 | 3 (excl. Rebellion) | 0 | 6 |
| 3p | 2 | 1 | 4 (all) | 1 | 8 |
| 4p | 4 | 1 | 4 (all) | 1 | 10 |
- **Note (low priority — solo/Automa is not implemented per A3):** the rulebook's own solo-setup text
(p.6) excludes a different ship for solo play than what the owner stated above — it says _"Return
the Twilight spaceship ... to the box. Put the other 3 spaceships [Rebellion, T F Mars, Eclipse]
near the gameboard,"_ i.e. solo excludes **Twilight**, not Rebellion. The owner's solo composition
above says "no Rebellion" instead. Since solo play isn't being built (A3), this discrepancy is
flagged for completeness only and isn't blocking — 2p (which IS in scope and does exclude Rebellion,
per C2) matches the owner's data exactly.
- Exact face-by-face identity of WHICH spaceship/planet-type goes on which specific numbered tile
(as opposed to just the per-set counts above) is not needed for engine logic — at setup, the set's
tiles are placed into the board's holes at random (per H1), so only the aggregate counts matter.
- H4. Revised Space Sector tile planet layouts: `TODO [BOARD-ART revised sectors]`. Newly confirmed
which tiles are "revised" (`RULEBOOK-TEXT` p.4 setup text): specifically Sectors **05, 06, and 07**
are genuinely double-sided Lost-Fleet components — one face matches the base game's appearance
("white numbers," used at 4p), the other is Lost-Fleet-specific ("black numbers outlined in white,"
used at 2p and 3p). Sectors 01-04 and 08-10 are unmodified base-game tiles reused as-is (no revision).
Still need the actual revised-side planet arrangement for 05/06/07 from the physical components.
- **Fallback decision (owner-confirmed 2026-06-28), used until the real revised-face art is
supplied:** match the base game's own existing per-player-count choice for these 3 sectors. The
base game already ships both faces (`s5`/`s6`/`s7` = "A" side, `s5b`/`s6b`/`s7b` = "B" side in
`engine/src/map.ts`) and already picks B-side for its 2-3p `smallConfiguration` and A-side for its
4-5p `bigConfiguration`. Lost Fleet board generation reuses that exact same split — B-side
(`s5b`/`s6b`/`s7b`) for LF 2p/3p, A-side (`s5`/`s6`/`s7`) for LF 4p — even though it isn't
confirmed to be the _correct_ Lost-Fleet-specific revised art, since it's the closest available
proxy and keeps 4p genuinely unrevised (matching the rulebook's explicit "white numbers" note for
4p above).
- H5. "Most asteroids" final scoring needs ≥6 asteroids in play (flip Deep Space tile 16 if not). p.4. CONFIRMED.
## I. EXISTING-FACTION DELTAS — RESOLVED 2026-06-27 via p.16 screenshot
- **I7. Full 18-faction comparison table — CONFIRMED (Source: `BOARD-ART p.16`, owner screenshot
2026-06-27 of the rulebook's own per-faction comparison graphic; supersedes the earlier `COMMUNITY`/
`INFERRED` partial extract).** Green-highlighted cells in the original mark "deviation from a generic
baseline faction" (≈ 2 mines / 2pw Area I+4pw Area II / 3k,4o,15c,1q / no start research / +1k+1o
basic income / +3/4/4/5c TS / +4pw+1 token PI / +1k RL / +2k AC1 / 1q AC2 / 5VP shuttle / no special
ability) — transcribed verbatim below, abbreviations: M=Mine, PI=Planetary Institute (starting
buildings); B1/B2=power Area I/II; K=knowledge, R=ore, C=credit, Q=Q.I.C. (resources/income); P=power;
PB1/PB2=token(s) gained into Area I/II; "de" (Ambas TS) = a board-printed footnote abbreviation, not
yet decoded — flag if it matters when implementing Ambas.
| Faction | Bldgs | Power B1/B2 | Resources | Start research | Basic income | TS 1/2/3/4 | PI | RL | AC1 | AC2 | Ship cost | LF special ability |
| ------------- | ----- | ----------- | ------------ | -------------- | ------------- | ------------ | --------- | --- | ------- | --- | --------------------- | ----------------------- |
| Terrans | 2M | 4/4 | 3K,4R,15C,1Q | GF | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
| Lantids | 2M | 4/0 | 3K,4R,13C,1Q | None | +1K,+1R,+1PB1 | +3/4/4/5C | +4P | +1K | +2K | 1Q | 5VP | None |
| Xenos | 3M | 2/4 | 3K,4R,15C,1Q | AI | +1K,+1R | +3/4/4/5C | +4P,+1Q | +1K | +2K | 1Q | 5VP | 1R→1PB3 free action |
| Gleens | 2M | 2/4 | 3K,4R,15C | Nav | +1K,+1R | +3/4/4/5C | +4P,+1R | +1K | +2K | 1Q | 5VP | +2 range special action |
| Taklons | 2M | 2+BS/4 | 3K,4R,15C,1Q | None | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP + BS to gaia area | None |
| Ambas | 2M | 2/4 | 3K,4R,15C,1Q | Nav | +1K,+2R | +3/4/4/5C de | +4P,+2PB1 | +1K | +2K | 1Q | 5VP | None |
| Hadsch Hallas | 2M | 2/4 | 3K,4R,15C,1Q | Eco | +1K,+1R,+3C | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
| Ivits | 1PI | 2/2 | 3K,4R,15C,1Q | None | +1K,+1R,+1Q | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
| Geodens | 2M | 2/4 | 3K,4R,15C,1Q | TF | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
| Bal T'aks | 2M | 2/2 | 3K,4R,15C | GF | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 4C | 7VP | None |
| Firaks | 2M | 2/4 | 2K,4R,15C,1Q | None | +2K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
| Bescods | 2M | 2/4 | 3K,4R,15C,1Q | None | +1R | +1/1/1/1K | +4P,+2PB1 | +2K | +3/4/5C | 1Q | 5VP | None |
| Nevlas | 2M | 2/4 | 2K,4R,15C,1Q | Sci | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +2P | +2K | 1Q | 5VP + burn 1P | None |
| Itars | 2M | 4/4 | 3K,5R,15C,1Q | None | +1K,+1R,+1PB1 | +3/4/4/5C | +4P,+1PB1 | +1K | +3K | 1Q | 5VP + burn 1P | None |
| Moweyds | 1M | 4/4 | 5K,6R,15C,2Q | GF | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
| Space Giants | 1M | 4/4 | 3K,6R,15C,1Q | Nav | +1K,+1R | +3/4/4/5C | +6P,+1PB1 | +1K | +2K | 1Q | 5VP | 2 dig special action |
| Darkanians | 1M | 4/2 | 3K,7R,15C,1Q | Nav,Eco | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
| Tinkeroids | 1PI | 4/2 | 2K,4R,15C,1Q | Sci | +1K,+1R | +3/4/4/5C | +4P,+1PB1 | +1K | +2K | 1Q | 5VP | None |
**Important caveat before using this for I1/I3/I6 below:** most of the green-highlighted deviations
above (e.g. Ivits' 1-PI start, Taklons' Brainstone, Bescods' all-knowledge research income, Ambas'
extra ore) are this faction's **pre-existing base-game personality**, not something Lost Fleet
changed — the table just shows each faction's actual current numbers, it doesn't separately flag
"changed by this expansion" vs. "always been true." The one column that DOES isolate genuinely NEW
Lost-Fleet content is **"LF special ability"**, and it shows non-`None` for exactly 3 existing
factions: **Xenos** (matches I4's `1o→1pw(AreaIII)` free action — same ability, table's "R" = ore),
**Gleens** (matches I5's `+2 range` special action), and **Space Giants** (matches B4's "2 free
terraform steps" Build-a-Mine action — "2 dig" in the table's shorthand). Every other faction,
including Lantids/Ivits/Bescods/Itars, shows `None` here.
**Resolution for I1/I3/I6:** there is no further Lost-Fleet-specific delta to chase for Ivits,
Bescods, or any of the other existing factions beyond what's already captured (I2 Lantids, I4 Xenos,
I5 Gleens) — the LF-special-ability column is empty for all of them. The other column values above
(income, PI, AC1/AC2, etc.) are each faction's correct CURRENT numbers under Lost Fleet, useful as a
direct implementation reference, but determining whether any specific cell differs from that
faction's pre-existing vanilla number (the only way a "silent" non-ability rule change could hide)
isn't something to guess at from memory — **when actually coding each base faction's Lost Fleet
config, diff this table's row against that faction's existing `engine/src/faction-boards/*.ts`
definition** (which already encodes correct, tested vanilla numbers); any mismatch found that way is
the real delta to apply, anything matching needs no change. No further owner input is needed for I1/
I3/I6 — this is now a coding-time verification step, not an open question.
- I1. Ivits — **CLOSED**, see I7: power 2/2 (table-confirmed, matches p.8 and pre-existing vanilla
value), no LF-specific ability or other delta found.
- I2a. Lantids shared mines count for **sector presence**, including the Lost Fleet Deep Space
final goal, booster and Advanced Tech tiles. They do not count for planet-type/Gaia/asteroid
conditions or grant the 6-VP protoplanet reward. The exclusion is about planet types, not sector
presence. Use `colonizedBy(player)` for sector counts, not `isMainOccupier(player)`.
The earlier fuzzer note calling shared Deep Space mines an oracle bug was incorrect;
both the engine and oracle were excluding valid mines. See [Lantids audit](LANTIDS_AUDIT.md)
for sources, verified mechanics and regression coverage (2026-11-01).
- I2. Lantids: +1 power Area I income (CONFIRMED, p.8). Adjusted PI tile, text-only (no image in the
uiqoo.kr randomizer, see COMPONENTS.md §8), both sides: **solo/2-player side** — gain 2 knowledge
both when adding a mine to a colonized planet AND when building a mine on the Lantids' home planet
type (Terra = the blue planet in this viewer's palette, see `viewer/src/data/planets.ts`), even
without using their faction ability. **3-player side** — gain 2 knowledge AND charge 1 additional
power when adding a mine to a colonized planet. **Owner board-read 2026-06-27 corrects the rulebook
prose** (`RULEBOOK-TEXT` p.8's "Choosing Your Faction" recap only mentioned the power charge for the 3p side,
omitting the knowledge gain that's also on the physical tile — abbreviated narrative vs. full tile
text). Only relevant with fewer than 4 players (a 4-player game uses the unadjusted base PI tile,
which itself already grants 2 knowledge per additional mine when a Planetary Institute is built —
see `player.ts` `gainRewards([new Reward("2k")], Faction.Lantids)`). CONFIRMED.
- I3. Bescods — **CLOSED**, see I7: table shows no LF-specific ability; the "starts 3 knowledge"
recap on p.8 just restates their pre-existing vanilla starting resources (3K is the table's own
baseline value, not a deviation) — no Lost-Fleet delta found for Bescods.
- I4. Xenos: free action 1o→1pw(AreaIII) (p.11). Board deltas: cross-validated by I7's table — no
further deltas beyond this one ability. CONFIRMED.
- I5. Gleens: special action incl. Explore +2 range (p.11). Board deltas: cross-validated by I7's
table — no further deltas beyond this one ability. CONFIRMED.
- I6. Every other faction (Taklons, Ambas, Hadsch Hallas, Geodens, Bal T'aks, Firaks, Nevlas, Itars) —
**CLOSED**, see I7: table shows `None` in the LF-special-ability column for all of them; their
other column values are pre-existing vanilla traits (Brainstone, inverted research income, etc.),
not new Lost Fleet content. Per-faction implementation should still diff against existing engine
code per I7's note, but no owner input is needed.
## J. MULTIPLAYER / SYNC RULINGS
- J1. Turn commitment: only completed turns persist + broadcast (ties to A2 undo). OUR-RULING. CONFIRMED.
- J2. Leech/charge-power interrupts: another player may owe a charge decision mid-turn. The sync
layer must surface "who can act now" from the engine's available-commands, not assume strict
sequential turns. Source: OUR-RULING / engine behavior. CONFIRMED (need), INFERRED (impl).
- J3. Seed fixed at game creation, stored, never regenerated (engine is deterministic from seed +
moves). OUR-RULING. CONFIRMED.
- J4. Notifications: ~~email on turn-change (works everywhere). PWA push optional later~~ —
**AMENDED by owner ruling 2026-07-01: Web Push notifications are the one notification channel;
turn-change emails are dropped entirely** (owner doesn't check email and doesn't want the spam).
The only emails in the system are Supabase Auth's built-in magic-link sign-in emails. Accepted
caveats, raised and acknowledged: iOS requires the viewer added to the home screen as a PWA
(iOS 16.4+) before push works, and each device must grant notification permission once; a
player with no subscribed device simply gets no notification (the game itself is unaffected).
Source: OUR-RULING (owner, 2026-07-01). CONFIRMED.
## K. ERRATA CHECK LOG (2026-06-25)
- **K1. No official errata/FAQ document exists for Lost Fleet.** Capstone's official product page links
exactly one rules file, `GP_Exp_Rule_EN_V1_Web.pdf` (the v1.0 rulebook already in this repo) — no separate
errata or FAQ. The "Gaia FAQ and Errata" file on BGG (filepage 155926) is dated Feb 2018, predates Lost
Fleet by 6 years, and is base-game only. **The v1.0 rulebook prose is authoritative.**
Source: `ERRATA` (negative result) — https://capstone-games.com/products/gaia-project-the-lost-fleet
Confidence: CONFIRMED.
- **K2. Lost-Fleet corrections exist only as BGG community forum threads** (not official errata, and BGG
blocks automated fetch with HTTP 403, so they must be read by a human). Threads to review and, if a
ruling is found, record with `COMMUNITY` source (NOT `ERRATA`). **Owner pre-authorized 2026-06-27:
if a thread states a clear ruling on a question this doc has open, record it directly as
`Confidence: CONFIRMED`** (not `INFERRED`) — no separate owner re-confirmation needed after the
human read, since the read itself IS the confirmation step here.
- "Confusing things after first reading" — https://boardgamegeek.com/thread/3278038
- "Geodens' Planetary Institute and Protoplanets/Asteroids" — https://boardgamegeek.com/thread/3354496
(directly relevant to §I: does an existing per-planet-type bonus fire on the 2 new planet types?)
- "How The Lost Fleet affects Gaia Project's design" — https://boardgamegeek.com/thread/3353396
- "Another Update from Feuerland" — https://boardgamegeek.com/thread/3253233
Status: ☐ awaiting human review (owner has BGG access).
- **K3.** Confirmed from rulebook prose (so `RULEBOOK-TEXT`, not errata): the "Gain VP for Planet types"
Q.I.C. action base is reduced to **2** points (p.13), because there are now more planet types.
---
## OPEN QUESTIONS / TODO BEFORE CODING
1. ☑ Check BGG errata thread; record any corrections here with `ERRATA` source. → DONE: no official
errata exists (§K1). Remaining: human review of community threads (§K2).
2. ◐ Fill all `TODO [BOARD-ART]` placeholders from the physical game. Remaining open: H4 (revised
Sector 05/06/07 planet layout — still needs the physical component). Everything else closed
2026-06-27 (H2 Transdim ID, H3 Interspace composition, B1 Tinkering tiles, B5 closed as
not-needed, G2 "big" tile fix, G5 green-side rule, full §I faction audit).
3. ☑ Decide final `Expansion` enum restructure shape (A1) before touching enums.ts. → LOCKED, see §A1.
4. ☑ Confirm no new research track (F2). → DONE, owner-confirmed 2026-06-27, see §F2.
5. ☑ Complete the p.16 existing-faction audit (section I). → DONE 2026-06-27 via owner screenshot of
p.16; see §I7's full 18-faction table. No Lost-Fleet-specific delta found beyond what was already
captured (Lantids/Xenos/Gleens/Space Giants); diff-against-engine-code note left for implementation time.
6. ☑ Resolve the E6 side-selection conflict. → DONE, owner ruling 2026-06-27: 2p always forced to the
25-VP side (matches rulebook); 3-4p always randomize the side every game (exercising the rulebook's
own "decide at random" option unconditionally, rather than as an optional later-game variant). See §E6.
7. ☐ K2: human review of the 4 BGG community threads (owner has BGG access) — any clear ruling found
should be recorded directly as CONFIRMED, per owner's 2026-06-27 pre-authorization. See §K2.
8. ☑ **Rescore-with-no-owned-token gate (fuzzer finding LF-2, 2026-07-03).** May a player take a
"re-score a Federation token you already own" effect while owning NO Federation token (pool or
ship-claimed)? Affects 2 Lost Fleet surfaces: (a) the Federation-token-shaped **Artifact** (§G6)
being choosable on Examine Artifact, and (b) **Twilight's Q.I.C. action** (§C1, 3 Q.I.C.).
**Owner ruling 2026-07-03 (revised same day): YES — the action/token stays choosable, it just
has no effect.** Unlike the base game's identical QIC2 rescore mechanic (which hides the
action entirely with no owned token — `engine/src/available/actions.ts`, "Prevent using the
rescore action if no federation token"), the owner explicitly chose the opposite UX for these
2 Lost Fleet surfaces: pay the cost/claim the token as normal, and if nothing is owned to
rescore, the effect silently resolves as a no-op (previously this threw/dead-ended — that was
the actual bug LF-2 reported). Both surfaces are flagged with a warning so a future UI can
tell the player in advance: `AvailableSpaceshipBoardAction.warnings` (new
`BuildWarning.noOwnedFederationToRescore`) for Twilight's Q.I.C. action, and
`Command.ChooseArtifactToken`'s new `noEffectTokens` field for the Federation-shaped Artifact.
Source: `OUR-RULING` (owner, 2026-07-03). Confidence: CONFIRMED. Fixed in
`engine/src/engine.ts` (the shared `gain-${Resource.RescoreFederation}` listener is no longer
`required`) and `available/federations.ts`'s `possibleFederationTiles()` (the rescore branch
returns no command at all — not one with an empty `tiles` list — when the player owns nothing,
so the non-required `processNextMove` call resolves it as a genuine no-op instead of an
unanswerable forced choice).

View file

@ -0,0 +1,90 @@
# Faction starting-conditions overview (COMMUNITY source, transcribed values only)
# Provenance: fan-made 'Gaia Project + Lost Fleet faction overview' PDF supplied by repo owner.
# Base-faction rows cross-validate vs known base values. Confidence INFERRED; confirm vs physical boards.
# Columns: Faction | StartBuildings | Power(B1/B2) | StartResources | StartResearch | BasicIncome | TS | PI | RL | AC1 AC2 | ShuttleCost | LF special
# ---
Shows deviation from standard starting conditions
Faction Starting Starting Starting Start Basic TS PI RL AC1 AC2 Space Lost
ship fleet
buildings power ressources research income (1/2/3/4) cost special
abilities
(B1/B2) +2K 1Q 5VP
None
Terrans 2M 4/4 3K, 4R, GF +1K, +1R +3/4/4/5C +4P, +1PB1 +1K
15C, 1Q
Lantids 2M 4/0 3K, 4R, None +1K, +1R, +3/4/4/5C +4P +1K +2K 1Q 5VP None
13C, 1Q +1PB1
Xenos 3M 2/4 3K, 4R, AI +1K, +1R +3/4/4/5C +4P, +1Q +1K +2K 1Q 5VP 1R
1PB3
15C, 1Q free
action
Gleens 2M 2/4 3K, 4R, Nav +1K, +1R +3/4/4/5C +4P, +1R +1K +2K 1Q 5VP
+2
15C range
special
Taklons 2M 2+BS/4 3K, 4R, None +1K, +1R +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP + action
15C, 1Q BS to
gaia None
area
None
Ambas 2M 2/4 3K, 4R, Nav +1K, +2R +3/4/4/5C +4P, +2PB1 +1K +2K 1Q 5VP
15C, 1Q de
Hadsch 2M 2/4 3K, 4R, Eco +1K, +1R, +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP None
15C, 1Q +3C
Ivits 1PI 2/2 3K, 4R, None +1K, +1R, +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP None
15C, 1Q +1Q
Geodens 2M 2/4 3K, 4R, TF +1K, +1R +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP None
15C, 1Q
Bal T'aks 2M 2/2 3K, 4R, GF +1K, +1R +3/4/4/5C +4P, +1PB1 +1K +2K 4C 7VP None
15C
Firaks 2M 2/4 2K, 4R, None +2K, +1R +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP None
15C, 1Q
Bescods 2M 2/4 3K, 4R, None +1R +1/1/1/1K +4P, +2PB1 +3/4/5C +2K 1Q 5VP None
15C, 1Q
Nevlas 2M 2/4 2K, 4R, Sci +1K, +1R +3/4/4/5C +4P, +1PB1 +2P +2K 1Q 5VP + None
burn 1P
15C, 1Q
Itars 2M 4/4 3K, 5R, None +1K, +1R, +3/4/4/5C +4P, +1PB1 +1K +3K 1Q 5VP + None
15C, 1Q +1PB1 burn 1P
Moweyds 1M 4/4 5K, 6R, GF +1K, +1R +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP None
15C, 2Q
Space 1M 4/4 3K, 6R, Nav +1K, +1R +3/4/4/5C +6P, +1PB1 +1K +2K 1Q 5VP 2 dig
giants 15C, 1Q special
action
Darkanians 1M 4/2 3K, 7R, Nav, +1K, +1R +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP None
15C, 1Q Eco
Tinkeroids 1PI 4/2 2K, 4R, Sci +1K, +1R +3/4/4/5C +4P, +1PB1 +1K +2K 1Q 5VP None
15C, 1Q
TWILIGHT TF MARS
REBELLION ECLIPSE

Binary file not shown.

View file

@ -0,0 +1,815 @@
"I can see something on the display." Gratsol, the aged Over time, the Moweyds were able to locate further
admiral of the Moweyds fleet, had heard this said many spaceships thought to be part of this fleet, so we now
times over the years. The Moweyds have been searching know more about the origin of the Q.I.C.s. Even back
for the Lost Fleet for generations, and time after time, then, these spacecraft already had Q.I.C. interfaces, so
this observation had led only to disappointment. It was Quantum Intelligence Cubes must have been available
the first time for the young engineer looking at the screen, back in the mythical early days of interstellar space
however, so he was hopping from one leg to the other in t ravel. The various factions are now all setting out to find
excitement. Gratsol sighed and started to head over. Yes, these spacecraft, in order to exploit the benefits of their
there had been leaps forward in the technology: It was legendary technology. News of the reemergence of the
now possible to colonize a group of asteroids, if you were Lost Fleet has quickly spread to even the farthest corners
prepared to scrap a Gaiaformer for it, and then eventually, of the galaxy, and more species are now also hoping to
it became possible to colonize protoplanets. Well, what discover the secrets of these long-forgotten civilizations.
actually happened was that you settled in orbit and used Not hailing from this part of the galaxy, they quickly es-
the latest kit to siphon energy from the planet that
was forming.. But Gratsol didn't think that tablished launch bases on asteroids and protoplanets,
the sensors had improved by all that thereby giving themselves the chance to
much. He went over to the screen. explore the spacecraft that have re-
"By Vo'Kron," he thought. "Could emerged. But the Moweyds are already
it really be ... ?" one step ahead of the game, being
"Get closer!" he commanded, first to board the T F Mars ...
now also gripped with
excitement. After only a few
seconds, he was sure of it:
There, in front of their eyes,
was the legendary T F Mars,
the Gaia Federation's sparkling
flagship spacecraft. At last! They
had found the first spaceship of the
Lost Fleet.
4 Lost Fleet Spaceship Boards Components 4 Round Boosters
8 Deep Space Sector tiles
(double-sided)
1 Colonization overlay for new planet types 3 Final Scoring tiles
(covers the Q.I.C. actions) 3 Round Scoring tiles
6 Advanced Tech tiles
30 Interspace tiles in 4 sets,
for 1­4 players (single-hex Spaceship
tiles, Planet tiles; and blank tiles)
1 double-sided Scoring Board Extension
(Different Planet Types / Additional Advanced Tech)
13 Artifact tokens 9 Exploration boards 12 Standard Tech tiles;
(double-sided) 4 each of:
2 Faction boards (double-sided)
8 Federation tokens (gold outline)
Darkanians
4 Gaia Planet tokens 12 Action tokens
6 Tinkering tiles 6 Power Rings Expansion components 1 adjusted Economy
(for the Tinkeroids faction) (for the Moweyds that correspond to those in Research Area tile 1 adjusted Lantids
the base game are marked
faction) (double-sided) Planetary Institute tile,
with this icon . for 1­3 players
(double-sided)
2
Revised Expansion Components Player Aids Automa Components
(these replace their counterparts 1 Turn Order 1 Moweyds / Tin- 3 Automa Spaceship tiles
in the base game)
board, with keroids Terraforming 1 Automa
1 Final Scoring tile Terraforming
Actions Reference board, with Actions
1 Advanced Reference
4 Standard Tech tiles Tech tile on the back Reference on the back board
Structures and Other Player Pieces (in each new player color) 27 Exploration
Turquoise, pink Shuttles
8 Mines 4 Trading 3 Research 2 Academies 1 Planetary 3 Gaiaformers 7 player 25 Satellites (3× 9 colors)
Stations Labs Institute tokens
4 Credit markers 2 Ore markers 2 Knowledge markers
Introduction
This expansion gives you more options and variants for your Gaia Project game.
Huge, deserted spaceships have been discovered in the galaxy, providing evidence
of highly-evolved civilizations that have been forgotten through the mists of time.
Your job is to explore these spacecraft and learn their factions' secrets.
You can now also choose one of 4 new factions.
The new factions start on asteroids or protoplanets--two new types of planet--which can now also be colonized.
These new planets can be found all across the galaxy.
Before Your First Game with the Expansion
Before you add this expansion to your base game, remove all the Base game New symbol This new symbol shows all
components showing the base-game symbol for "Different Planet symbol 11 different planet types
Types" from the game. Replace those components with the revised (including the Lost Planet
components from the expansion (see right). from level-5 Navigation).
It still represents the different
Sort the Interspace tiles into sets, based on the player count. For types of planet that you have
any given game, you will only need the set for the player count of colonized.
that game.
Conversely, the base-game home planet
Add the additional Gaia Planets and Action tokens to the base- symbol only shows the 7 types of home planet
game components. Shuffle the new Round Boosters, Final Scor- for the factions in the base game, i.e. the
ing tiles, Round Scoring tiles, and Advanced Tech tiles in with the standard planet types. You will see the symbol
base-game components. Make sure that you do not mix the new on the new Faction boards.
Standard Tech tiles with the base-game Standard Tech tiles. Set
out the Round Boosters, Round Scoring and Final Scoring tiles,
Advanced Tech tiles, and base-game Standard Tech tiles as nor-
mal. All the usual base-game rules apply in the expansion, except
for the changes explained along with the supplementary rules.
3
Changes to Setup
Variable Gameboard Layout
Set out the play area as described below. As usual, the final player in player order may freely rotate the Space Sector tiles
(but not the Deep Space sectors) to achieve a fairer distribution of planets, if they wish.
Setup for 2 players
Take the Space Sector tiles numbered 01­07. Flip Sectors 05, 06, and 07 so that the sides with the black numbers outlined in white
are face up. Randomly choose one of the Sectors 01­04
and place it in the center of the table. Arrange the other
6 sectors around it. However, do not match up those 6
sectors as per the base game, but instead slide them all
one space along to the left or the right, so that each outer
sector only borders the inner sector along two spaces.
This will create 6 holes around the inner sector, each the
size of one space (see image).
Take the 6 Interspace tiles for your player count and place
one into each of the holes at random. Make sure that
each spaceship is 5 spaces away from each of the other
spaceships (alternately placing Interspace tiles with a
spaceship and without a spaceship, and so on).
Take the Deep Space Sector tiles 11­16 and place them
with a random side up in the gaps along the outside edge
of the gameboard.
Special note: If you are using the Final Scoring tile
"Most asteroids colonized," then you must have at least
6 asteroids in play. If this is not the case, flip Deep Space
Sector tile 16.
Setup for 3 players
Take the Space Sector tiles 01­10, apart from 08 (return 08 to the box). Flip Sectors 05, 06, and 07 so that the sides with the black
numbers outlined in white are face up. Randomly choose one of the Sectors 01­04 and place it in the center of the table. Arrange 6
random other around them. However, do not
match up those 6 sectors as per the base game,
but instead slide them all one space to the left or
the right, so that each outer sector only borders
the inner sector along two spaces. This will
create 6 holes around the inner sector, each the
size of one space. Then place the two remaining
sectors, shifting them one space in the same way
(see image).
Take the 8 Interspace tiles for your player count
and place them in the holes at random. Make
sure that no two spaceship tiles are next to each
other, i.e. a spaceship tile should not be within
3 spaces of another spaceship tile.
Take the 8 Deep Space Sector tiles and place
them with a random side up in the gaps along
the outside edge of the gameboard. Place 2
Deep Space Sector tiles next to each other in
the larger gap by the sector you placed last (see
image).
4
Interspace Tiles
Front Back
Tile with a Lost Fleet Tile with a planet Blank tile Only use the tiles that correspond
spaceship (Protoplanet, Asteroid) to your player count.
Setup for 4 players
Take all 10 Space Sector tiles, using the side with the white numbers for Sectors 05, 06 and 07. Randomly choose two of the Sectors
01­04 and place them next to each other in the center of the table. Arrange the other 8 Space Sectors around them at random. However,
do not match up those sectors as per
the base game, but instead slide them
all one space to the left or the right,
so that each outer sector only borders
an inner sector along two spaces. This
will create 10 holes around the inner
sectors, each the size of one space (see
image).
Take the 10 Interspace tiles for your
player count and place them in the
10 holes at random. Make sure that
no two spaceship tiles are next to
each other, i.e. a spaceship tile should
not be within 3 spaces of another
spaceship tile.
Take the 8 Deep Space Sector tiles
and place them with a random side
up in the gaps along the outside edge
of the gameboard.
Changes to the Boards
Scoring Board Advanced Tech tile Take the Scoring Board Extension.
(drawn at random)
Scoring Board For 2 players, always use the side showing
Extension for 25 victory points.
2/3/4 players
For 3 or 4 players, use the side showing
Reverse side of 3 Exploration Shuttles. In later games, you
Scoring Board can decide at random which side to use.
Extension for
3/4 players Put the Scoring Board Extension below
the scoreboard and then place a random
additional Advanced Tech tile onto the
extension.
5
Research Board Place the Colonization overlay for
the new planet types on the Research
Adjusted tile for Board so it covers the Q.I.C. actions.
the Economy
Research Area Take the adjusted Economy Research
(random side) Area tile and place it with a random
side up so it covers the previous
income symbols for levels 3 and 4.
Colonization
overlay for the
new planet types
Lost Fleet Spaceships
There are 4 Spaceship Boards for the Lost Fleet. In these rules, Place the new Standard Tech tiles at random (using
"spaceship" will always refer to these boards, and not the [single- the 3 tiles with green markings on the back) onto
hex] spaceship tiles that are part of the gameboard. the corresponding 2 or 3 spots on the spaceships.
If there are only 2 players, return the remaining
2 players Standard Tech tiles to the box.
You will not be using the Rebellion spaceship , so return it to Take as many Artifact tokens at random as there
the box. Take the remaining 3 spaceships and place them near the are players. Place the tokens face up on the
gameboard. corresponding spaces on the Twilight spaceship
3­4 players . Return any remaining Artifact tokens to the
box.
Place all 4 spaceships near the gameboard.
Take 4 of the new Federation tokens and distribute
You can either place the spaceships in separate spots around the them on the 4 spaceships at random. If there are
gameboard so that they are near their corresponding spaceship 2 players, you will only be playing with 3 spaceships,
tiles, or you can keep them all together in one place. so take 3 of the new Federation tokens at random
and place them onto those 3 spaceships. Return the
remaining Federation tokens to the box.
Artifact token
(drawn at random)
Federation token
(drawn at random)
6
Twilight ­ Nautilaks spaceship
The Nautilaks were a legendary species of space researchers
that are mentioned in the early records of the Firaks. They are
said to have been able to perform astonishing jumps through
space. What has only just become known about them is that
they were able to compress intriguing paraphernalia into
artifacts.
Rebellion ­ Vo'Kron Directorate spaceship
The Vo'Krons are said to have been masters at harnessing the
power of artificial intelligence. They are thought to have
originally constructed the Q.I.C.s, which gave them an
enormous advantage both technologically and economically.
This is assumed to be the freight ship that they initially used to
transport the Q.I.C.s.
T F Mars ­ Gaia Federation spaceship
The Gaia Federation are said to have developed the first
Gaiaformer, in addition to other technologies based around
transdimensional quantum mechanics. They are also considered
to be the pioneers of planetary terraforming.
Eclipse ­ Eridani Empire spaceship
The Eridani Empire originates from Epsilon Eridani.
This advanced civilization possessed a range of extraordinary
technologies. Over time, their once expansive empire broke
apart into many disparate powers, which became so technologi-
cally distinct that there are now a number of different factions
who claim to be descended from the Eridani. The Geodens and
the Bal T'aks in particular are descended from the Eridani.
Choosing Your Faction
There are 4 additional factions in this expansion. Tinkeroids and Moweyds have
These 4 factions have the following things in common: nonstandard terraforming costs for
base-game planets during play, and
· They all begin the game with only 1 structure (Planetary those get established after all factions
Institute for the Tinkeroids; 1 mine for each of the other are chosen in Setup.
factions). Essentially, 3 base-game planet types
(which always includes their oppo-
· They begin the game on an asteroid or protoplanet (see the nents' base-game types) will require
"Build a Mine" action on page 10 for details on the new types 3 steps, and the others will require
of planet). just 1.
· They have no home planet; thus, just like the other factions,
they must terraform any other asteroids and protoplanets in
order to colonize them.
· There are two new sets of colored components for the new
factions.
You can find more details about the new factions in the Appendices on page 13.
There is a summary of all eighteen factions on page 16, to help you choose your factions.
7
Before anyone chooses factions, populate Once you have chosen your factions, you each take the Exploration
the Moweyds/Tinkeroids Terraforming board that corresponds to your faction. Place it next to your
board: Randomly fill the seven spaces Faction board.
1­7 with 1 base-game Satellite cube of
each color. This order determines the 2 players
other planets for which the Moweyds and
Tinkeroids must perform 3 terraforming Place 2 of the 3 Exploration Shuttles for your color on the desig-
steps, if they are not playing against nated spaces. Return the other shuttle to the box.
3 factions from the base game.
3­4 players
After choosing factions, if both Tinkeroids
and Moweyds were chosen, then for Place all 3 Exploration Shuttles of your color on the designated
each base-game faction chosen, add a duplicate Satellite cube to spaces.
its same space of the Terraforming board (see example below).
After choosing factions, if anyone chose the Tinkeroids or
Moweyds, then do the following:
· F or each base-game faction someone is playing, take a Satellite
cube of that faction's color from the Terraforming board and
place it on any 1 of the 3 spaces of the Terraforming Steps area
of your player board.
· In turn order, the Tinkeroids/Moweyds player(s) do the follow-
ing: Until filled, for each remaining Terraforming Steps space
you need to fill, take the first Satellite cube remaining on the
Terraforming board (see example below).
Example The cost of deploying one of your Exploration Shuttles is shown
on the left, and any additional, faction-specific adjustments are at
At the beginning of a 3-player the top.
game, they draw the color order
(see left). Player 1 chooses the There are some adjustments that affect game setup: The Ivits
Tinkeroids, player 2 chooses the only receive 2 power in Area I and 2 power in Area II, and the
Bescods and player 3 chooses Bescods start with 3 knowledge.
the Moweyds. Gray (the Bescods)
is a type of planet that costs For the Lantids, there is an adjustment that relates to their income
3 terraforming steps for both during the game: They gain 1 power in Area I.
new factions. The players who
chose those factions both take a
gray satellite, which they place
on their Faction board.
The Tinkeroids player then If the Lantids faction has been chosen and there are fewer than
takes the blue and yellow 4 players, take the corresponding adjustment tile and use it to cover
satellites from the row of colors their Planetary Institute ability. (The solo/2-player side of the tile
and places them on their Faction gives the Lantids 2 knowledge both when adding a mine to a
board. The Moweyds player colonized planet and when they build a mine on their home planet
takes the red and white satel- type, even if they do not use their faction ability. The 3-player side
lites. of the tile allows them to charge 1 additional power when adding
a mine to a colonized planet.)
Placing your Initial Structures
1) All players who have chosen a faction This has 3 stages: 3) The Ivits: Once all the other factions
from the base game, with the excep have placed their structures, place your
tion of the Ivits: Place your 2 or 3 2) All players who have chosen one of Planetary Institute.
mines as usual. the factions in the expansion: Place
your structure in turn order, going
around clockwise from the first player.
8
New Actions
11) Action: Explore Example
a Lost Fleet Spaceship
Since the Taklons currently have a range of 2, they must
Exploring a spaceship from the Lost Fleet gives you additional spend 1 Q.I.C. in order to explore the Eclipse spaceship .
action options. The following rules apply:
The corresponding spaceship tile on the game board must be
accessible from one of your planets. You can also use your
Q.I.C.s and special actions to increase your range for these
actions just like when you increase the range of the "Build a
Mine" or "Start a Gaia Project" actions.
You must still have an Exploration Shuttle on your Exploration
board. You can never send more than 1 Exploration Shuttle to
a Lost Fleet spaceship.
P lace your Exploration Shuttle on They pay [the standard]
the unoccupied shuttle space with 5 victory points and move
the lowest number. Unless you their Brainstone to their Gaia
are the first faction to explore this Area (the Taklons' additional
spaceship, you immediately charge cost, per their Exploration
power as indicated in the shuttle board) in order to deploy
space. their Exploration Shuttle
onto the corresponding
To deploy your Exploration Shuttle, pay the cost shown on Spaceship Board.
your Exploration board. This will usually be 5 victory points. They charge 2 power, as
indicated in Space 2.
12) Action: Examine an Artifact
If you explored the Twilight , you can examine the artifacts
you found there.
Discard 6 power from any combination of Areas I, II, and III.
Return these tokens to the supply to gain 1 artifact from the
spaceship.
The Taklons must additionally move their Brainstone to their
Gaia Area.
The Nevlas and Itars must additionally discard 1 power,
returning it to the supply.
The Bal T`aks must pay 7 instead of 5 victory points.
A spaceship is explored rather than colonized. When determining
the range in subsequent turns, you never measure from the
spaceship but from your closest colonized planet, as usual.
Artifacts are explained in the Appendices, on page 15.
9
Changes to the Base Game Actions
1) Action: Build a Mine There will also be 1 additional Advanced Tech available. However,
when taking this tile, you do not need to meet the first condition
The overlay tile that you used to cover the Q.I.C. actions on the for taking an Advanced Tech (i.e. your player token must have
Research board explains both of the new terraforming options. reached level 4 or 5 of the research area).
Protoplanet Each faction needs 3 terraforming steps to build a mine Instead, the conditions shown on the Scoring Board Extension are
applied (either you have at least 25 victory points or have explored
on the new Protoplanet planet type. If you build a mine on a pro- 3 different spaceships in the Lost Fleet; the latter condition only
toplanet, you receive 6 victory points. If you start the game on a applies in 3- and 4-player games).
protoplanet, you do The second and third conditions for taking an Advanced Tech tile
not receive any victory (flip a Federation token and cover a Standard Tech tile with an
points for that proto- Advanced Tech tile) remain unchanged.
planet.
4)Action: Form a Federation
Asteroid To build a mine on the new Asteroid planet type, your
When forming a federation, you may not place a satellite on a
faction must have an available Gaiaformer. Once a Gaiaformer spaceship tile.
has been used to colonize an asteroid, it cannot be used anymore
for the rest of the game. Do not place that Gaiaformer on the
asteroid, but instead on the available spot on the overlay tile. This
spot has no limit for holding useless Gaiaformers. You do not
need to pay the build costs (1 ore and 2 credits) for the mine.
The asteroids scattered through space need to be brought near If you have explored some of the spaceships in the Lost Fleet, new
enough so that they can be colonized, but also be kept far Federation tokens become available, in addition to the Federation
enough apart that they don't collide. This requires a huge tokens in the general supply.
amount of energy, which must be provided by the Gaiaformer.
Due to these high energy requirements, the Gaiaformer's If you have an Exploration Shuttle on a Lost
energy unit is redlining constantly until the colonization is Fleet spaceship and there is still a Federation to-
complete. After this process, the Gaiaformer is no longer of ken there, you can gain that token when you form
any use, except as a playground for youngsters. a Federation.
6)Action: Power
and Q.I.C. Actions
3)Action: Upgrade The Q.I.C. actions on the Research board are covered and thus
Existing Structures cannot be used.
If you have explored some of the spaceships in the Lost Fleet, If you have explored
new Standard Tech options become available, in addition to the some of the space-
Standard Tech tiles on the Research board. ships in the Lost
Fleet, new actions
If you have an Exploration become available for
Shuttle on a spaceship in the rest of the game.
the Lost Fleet, you can
take the Standard Tech On the spaceships, you gain access to Q.I.C. actions, Power
you find there when you actions and two new types of action: Knowledge actions and
upgrade a structure to a Credit actions. Many of the power actions on the spaceships cost
Research Lab or Academy. not only power, but also an additional resource.
If you do, advance 1 level
in a Research Area of your If you have an Exploration Shuttle on a spaceship, and the action
choosing. that you wish to use has not been covered by an action token,
you can use it (and then cover it with an action token). You must
The new technologies are explained in the Appendices, on page spend the resources and power specified.
15.
These new actions are explained in the Appendices, on pages
13­14.
10
7)Special Actions 10)Free Actions
The Space Giants and the Gleens each have a special action on Xenos
their Exploration board that they can use once per round. You As a free action, the Xenos can spend 1 ore
cannot combine this special action with another action. to gain 1 power (in area III).
Gleens Looking for more information or missing something?
The Gleens' special action allows you to
perform one of the following actions once: https://capstone-games.com/board-games/gaia-project-the-lost-fleet
"Build a Mine", "Start a Gaia Project", or
"Explore a Lost Fleet Spaceship," with your © 2024 Feuerland Capstone Games Version 1.0
basic range increased by 2 spaces. All the Verlagsgesellschaft mbH 2 Techview Drive, Suite 2
usual rules for performing the respective Nassaustr. 3 Cincinnati, OH 45215
action still apply. 65719 Hofheim am Taunus
www.capstone-games.com
Space Giants www.feuerland-spiele.de
The Space Giants' special action allows
you to perform a "Build a Mine" action
with exactly 2 free terraforming steps, in
order to make a planet habitable.
You can, if you need to, pay extra ore to
add the third terraforming step.
Changes to the Automa Solo Game
You can also play this expansion against the Automa artificial opponent.
The overall gameplay for the Automa functions as in the base game,
but with a few adaptations, which are explained below.
Note: The Automa in the base game was developed by the Automa Factory.
The adaptations described below have not been developed by the Automa Factory.
The Automa cannot be used to control any of the new factions from the expansion.
Setup The T F Mars (on the right) was randomly drawn to show
the action side. The other 2 ships show the spaceship side.
Use the variable setup for 2 players on page 4 in this rulebook.
Rotate the tiles so that you form a horizontal line of 5 hex spaces The spaceship side counts as 1 option for the ,,Power/Q.I.C."
along the top. Automa action. The action side counts as 0-3 options for the
,,Power/Q.I.C." Automa action (only count the empty spaces).
The following exceptions apply Whenever the Automa or you use an action on a spaceship, mark
· Take the 6 Interspace tiles for the solo game. Return the Twi- the corresponding space on the Automa Spaceship tile with a
power token.
light spaceship (the one with places for artifacts) to the box.
Artifacts are not used in the solo game, so return them to the
box as well. Put the other 3 spaceships near the gameboard.
Place a different new Standard Tech tile and a new Federation
token on each of the 3 ships at random.
· The Automa has 3 Exploration Shuttles.
· Do not cover the Q.I.C. actions using the new planets' Coloni-
zation overlay tile. Place this tile near the gameboard. Instead,
cover the Q.I.C. actions with the 3 Automa Spaceship tiles. Place
a random 1 of the 3 tiles Action side up to show that the Auto-
ma has already explored this spaceship. Place the other two tiles
Spaceship side up. The three tiles should be placed on the Q.I.C.
actions in the following order.
5 4 321
Automa takes a Power/Q.I.C. action with the
"4 from the right" icon and explores the Eclipse.
11
Changes to the Automa Actions
Build a Mine 4. Perform an action:
3. Tiebreaker: a. If the action is a power action from the base game, place an
c. For the new planet types: The asteroids require 2 terraforming action marker on the chosen action. The Automa gains no
steps and the protoplanets require 3 terraforming steps (see benefit.
the new Terraforming board).
b. If the action is the spaceship side of an Automa Spaceship
The following table shows the Final Scoring tiles that add an tile, then the Automa explores this Lost Fleet spaceship
additional condition to the tiebreaker (3b). at no cost (Action 11). Place 1 of Automa's Exploration
Shuttles on that spaceship and flip the Automa Spaceship
Most asteroids (i) Asteroid planets. tile to its action side. (From now on, that tile lists 3 possible
colonized (ii) Planets closest to an uncolonized actions.) Mark any spaces corresponding to an action space
you already used this round with a power token.
Present in the asteroid.
most Deep c. If the action is a space on the action side of an Automa
Space sectors (i) Planets in Deep Space sectors in which Spaceship tile, cover it with a power token. This will help you
the Automa has no colonized planets yet. determining further such actions by the Automa. If there is
a neigboring space to the left of it on the same Spaceship
(ii) Planets closest to an uncolonized planet tile and it is still empty, place a power token on that space
in a Deep Space sector in which the as well. Then place an action marker on the corresponding
Automa has no colonized planets yet. action(s) on the Spaceship. The Automa gains no benefit.
Upgrade 4 3 21
3. Tiebreaker: Using a Power/Q.I.C. action ,,3 from the right",
If the final scoring tile "Longest distance between your Pla the Automa selects the Q.I.C. action on the Eclipse
netary Institute and one of your Academies" is in play, then for and places a power token there.
the following "Valid Options", use this tiebreaker before those
from the base game rules: At the end of the round, remove both the action markers and
power tokens.
2b. Upgrade a mine into a Trading Station:
If the Automa has already built its Planetary Institute but Difficulty Levels
neither of its Academies yet, choose the mine furthest away
from its Planetary Institute. When adjusting the difficulty level in the Lost Fleet expansion,
apply the usual deck modifications and also adjust the Automa's
2d. Upgrade a Trading Station into a Research Lab: starting victory points as follows:
Choose the Trading Station that is furthest away from its
Planetary Institute. Automalein: 0 VP (no changes)
Automa: 15 VP
Power/Q.I.C. Actions Automächtig: 20 VP
Ultoma: 25 VP
2. Possible options: Alptrauma: 10 VP (no changes)
· Any power actions on the research board not covered
by an action marker.
· Any Automa Spaceship tile with the spaceship-side up.
· A ny space on the action side of an Automa Spaceship tile
(power, Q.I.C., knowledge or credit actions) not covered
by a power token.
Credits
Gaia Project ­ The Lost Fleet is designed by Helge Ostertag and Jens Drögemüller.
Artwork and graphics by Dennis Lohausen. These rules were written by Bastian Winkelhaus
as well as Stephan Rink, who also edited and produced this game.
We would like to thank Ursula Steinhoff for the DTP, Translation Circus for translation and additional DTP,
Nathan Morse for proofreading, Christof Tisch and Inga Keutmann for editorial support, our brilliant testing team -
who were Andreas Estensen, Nils Lindkvist, Jimmy Flumé, Göran Kero, Tonje Lindmark, David Johansson and Joakim Hägglund -
for all our playtesting and their suggestions for some of the components. Joe Farrell and Monrad Pedersen as well as the Automa Fac-
tory team for their invaluable ideas for the solo mode, plus the many playtesters and especially: Florian Schlusnus, Johannes Grimm,
Sascha Huning, Alexander Fendt, Florian Bücherl, Christian Blatakes, and Jonas Egel.
12
APPENDICES
Appendix I: New Factions
Tinkeroids Starting Planet: Asteroid Planetary Institute: The first time the Darkanians colonize a planet
in a Space sector or Deep Space sector, they always gain 2 credits
Ability: You start the game with your Planetary Institute instead of and 1 knowledge. Interspace tiles do not count as sectors.
2 mines, which you place during the second stage of placement.
When you terraform a standard planet, you will require 3 Moweyds Starting Planet: Protoplanet
terraforming steps for 3 of the the base-game planet types, and
1 terraforming step for the other base-game planet types (see Ability: You start the game with 1 mine instead of 2, which you
"Choosing Your Faction" on page 7). Making a Gaia planet place during the second stage of placement. You start the
habitable costs you 2 Q.I.C.s. The Tinkeroids have 6 different game with an Exploration Shuttle on T F Mars . When
Tinkering tiles to use: 3 of the tiles are to be used in rounds terraforming a standard planet, you will require 3 terraforming
1­3, and the rest in rounds 4­6. At the start of each round steps for 3 of the the base-game planet types, and 1 terraforming
choose 1 Tinkering tile that corresponds to that round. Place it step for the other base-game planet types (see "Choosing Your
on your Faction board. At the end of the round, remove that Faction" on page 7).
tile from play (each tile is only used once).
Planetary Institute: Once per round, you may place a Power
This tile is to be used by the Tinkeroids Ring as an ACTION onto a planet that contains one of your
during one of the first 3 rounds. It lets buildings and does not already have a Power Ring (if you need
them perform 1 "Build a Mine" action to, lift up the structure on the planet, put the Power Ring on the
with 1 free terraforming step. planet and then put the structure on top). The power value of
your structure on this planet increases by 2.
Planetary Institute: Once per round, you may use the action on Space Giants Starting Planet: Protoplanet
your current Tinkering tile as an ACTION.
Ability: You start the game with 1 instead of 2 mines, which you
Darkanians Starting Planet: Asteroid place during the second stage of placement. When terraforming
a standard planet, you require 2 terraforming steps. You have
Ability: You start the game with 1 mine instead of 2, which you (on the Exploration board) 1 "Build a Mine" action with 2 free
place during the second stage of placement. Making a standard terraforming steps. Making a Gaia planet habitable costs
planet habitable costs you 1 terraforming step, and making a 2 Q.I.C.s.
Gaia planet habitable costs 2 Q.I.C.s.
Planetary Institute: Immediately take 1 Tech tile of your choice.
The same rules apply as for the action "Upgrade Existing
Structures". You may only perform this ability once.
Appendix II: New Action Spaces
When you use this Q.I.C. action, you immediately · For the "Gain VP for Planet types" action, the base number
and only once receive 2 victory points, plus 1 of points you receive is reduced to 2 (because there are more
victory point for each of your Standard Tech tiles planet types available).
(whether or not there is an Advanced Tech tile on
it). · For the "Score a Federation Token Again" action, you not
only gain the victory points and resources again, but also all
The other Q.I.C. other immediate effects on that Federation token.
actions generally
correspond to those The depicted power actions cost an
in the base game, but additional 1 or 2 ore. When you use
with the following one of these actions, you
changes: immediately and only once gain an
· The "Gain a Tech Tile" action only costs 3 Q.I.C.s. If you have "Upgrade Existing Structures"
an Exploration Shuttle on a Lost Fleet ship, you can take the action, with which you can upgrade
Standard Tech tile there. a Mine to a Trading Station, or a Trading Station to a Research
Lab, at no additional cost.
13
This power action costs an additional 2 know These actions are the same as the
ledge. When you use this action, you may power action "Take 1 free terra
immediately move one of your player tokens up forming step" and the special action
1 Research level. The usual rules about advancing "+3 Range" from the base game,
to Level 5 apply. except that they cost 3 credits and
1 knowledge respectively. Note that
Perform a "Start a Gaia Project" action without you can also use the "+3 Range" for the new action "Explore a
needing to move any power tokens into the green Lost Fleet Spaceship."
Gaia Area, and immediately transform the
transdim planet into a Gaia planet (this means Immediately and only once receive the resources
you can build a mine on it as a later action in this depicted.
round and then use the Gaiaformer again this
round). Immediately and only once receive a "Build a
The transdim planet must be within your range. You may still Mine" action, which allows you to build a mine
spend Q.I.C.s to increase your range. on an asteroid at no extra cost: That asteroid must
be within your range, although you may discard
Q.I.C.s to increase your range. You do not need to
discard (or even have) a Gaiaformer.
Appendix III: New Round Boosters
In addition to income (1 ore, 3 credits, or 2 power), the new Round Boosters also give you the following benefits:
1 2 3 4 2 As soon as you perform the Pass action and return this
1 As soon as you perform the Pass action and return this Round Booster, you gain 1 victory point for each planet
type that you have colonized.
Round Booster, you gain 3 victory points for each of your
Gaiaformers, regardless of whether the Gaiaformer is on 3 As soon as you perform the Pass action and return this
your Faction board or is deployed. You do not receive
any victory points for Gaiaformers that you have used for Round Booster, you gain 2 victory points for each Deep
colonizing asteroids. Space sector in which you have colonized at least one
planet.
4 As a special action, you can perform a "Start a Gaia Project"
action once without needing to move any power tokens
into the green Gaia Area, and immediately transform the
transdim planet into a Gaia planet (this means you can
build a mine on it as a later action in this round and then
use the Gaiaformer again this round). The transdim planet
must be within your range. You may still spend Q.I.C.s to
increase your range.
Appendix IV: New Scoring Tiles
Each time you build a mine Round Scoring Tiles Each time you build
in a Space sector / Deep one of your Research
Space sector that you had Each time you build Labs, gain an additional
not colonized on a previous a mine on a planet 4 victory points.
turn, gain an additional 3 type that you had not
victory points. Interspace colonized on a previous
tiles do not count as sectors. turn, gain an additional
3 victory points.
14
Most Final Scoring Tiles Most Deep Space
asteroids sectors where you
colonized. Longest distance between have colonized at
your Planetary Institute and least one planet.
one of your Academies. This The Lost Planet counts as a colonized
distance is the range from planet.
your Planetary Institute to that Academy.
(You do not score any points if you have not built
these structures.)
Appendix V: New Tech Tiles
Immediately and only once receive a "Build a Immediately and only once receive
Mine" action with up to 2 free terraforming steps victory points for each Planetary
and without paying the cost for that mine. Institute and/or Academy, and for
You may spend additional ore to get a third each Deep Space sector in which
terraforming step, and you may spend Q.I.C.s you have colonized at least 1
to increase the range for this action. planet.
Your basic range increases by 1 for the rest of When you pass, you gain 2 victory points for
the game, as long as the tile is not covered by each asteroid that you have colonized.
an Advanced Tech tile.
Appendix VI: New Federation Tokens
Immediately and only once receive 12 victory points. Immediately and only once receive a "Build a Mine"
Unlike the 12-point Federation tokens in the base action of limitless range and without paying the cost
game, this token also has a green side, which allows for that mine. You still use ore to pay for any
you to discover an Advanced Tech or research the terraforming steps. For Gaia planets, you must pay
highest level of a Research Area. the required number of Q.I.C.s.
Immediately and only once receive 1 Tech tile of Immediately and only once receive a "Build a Mine"
your choice. The same rules apply as for the action action with up to 3 free terraforming steps and
"Upgrade Existing Structures". without having to pay the build cost for that mine.
You may still spend Q.I.C.s to increase your range.
Appendix VII: Artifacts
Immediately and only once receive Immediately and only once receive
7 victory points. This tile also 3 victory points for each level in
counts (in a similar way to the Lost the corresponding Research Area.
Planet) as if you are currently
building a mine and are colonizing an asteroid or protoplanet for (For example, for the tile on the right, if you have
that mine. This colonization is not allocated to a particular reached Science Level 5, you gain 15 victory points.)
sector, so does not count as colonizing a (new) sector; neither do
you receive 6 victory points for colonizing a protoplanet. Immediately and only once receive 3 victory points
for each Research Area in which you have reached
During the game, the artifact counts for all purposes as a mine at least Level 3.
on an asteroid or protoplanet that is not allocated to a sector.
However, you do not actually place a mine on it. Gain 2 power as income. Place them in Area III.
15
Itars NEvlas
Lantids Terrans
Hadsch Hallas
Bal T'aks IVITS
Gleens Geodens
Ambas
Firaks Xenos
Taklons
BESCODS
MoWeyds Space Giants
Darkanians Tinkeroids
16

View file

@ -0,0 +1,15 @@
# Lost Fleet variants
## Keep 4 QIC → tech tile (2 players)
An optional house rule, disabled by default. In a two-player Lost Fleet game, it restores the base
game's shared **4 QIC → tech tile** action beside the seven power actions. It follows the usual
technology selection, research advancement and once-per-round rules. No exploration is required.
The other two base-game QIC actions remain unavailable, and Rebellion stays out of the game.
The setup option is `lostFleet2pQicTech: true`. It has no effect without Lost Fleet or with more
than two players. Games created without this option retain the official rules.
The BGS setup checkbox is defined in `scripts/game-options/lost-fleet-2p-qic-tech.json`. When
deploying, merge it into the current Gaia Project v3 gameinfo document's `options` by `name`,
after publishing the engine and viewer that support it. Preserve the rest of the document.

View file

@ -0,0 +1,936 @@
{
"schema": 1,
"game": "gaia-project",
"status": "activated-and-verified",
"sourceCommit": "a96681aa6123b1e607763bdb37cbf1b9ed231e3d",
"envelopeSha256": "9e4db39d946d5a8cb94d712e6f2dfdb7f3f69fd152b1ee9421a71b29a2a0cb16",
"privateReceiptSha256": "14c7d53d628d51cda7bedc37ff9ecebacab03acd2a2f825d84cf5ef164521b6b",
"assets": {
"achievement-build-all-standard": {
"sourceSha256": "733ac94fc16d4b367ce7460cfce95f4f612c2ebae0e921a4e9c9337a30cdc993",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-build-all-standard/8cf83a5cc369f8ad/achievement-build-all-standard.webp",
"sha256": "8cf83a5cc369f8adbeb8758eb5cf002cf3da6b1eb424a15fe43b378f0bd72989",
"size": 13834,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.006Z",
"metadataPreserved": true
},
"achievement-explore-all-types-base": {
"sourceSha256": "f519bf72ab631881f3d7df67dac59f9b9b6e4e1d88fffcd4bcebcc4d566e80e0",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-explore-all-types-base/7147fa7c3baa8bed/achievement-explore-all-types-base.webp",
"sha256": "7147fa7c3baa8bed26de64053b0b10f85be916dc886ae437be97b8fa4a8542c8",
"size": 20686,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.043Z",
"metadataPreserved": true
},
"achievement-explore-all-types-lost-fleet": {
"sourceSha256": "ef465d87272ff673460f47450a005f42132c2479d632a50167d1bbb5711fea1a",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-explore-all-types-lost-fleet/9c853c76171c624f/achievement-explore-all-types-lost-fleet.webp",
"sha256": "9c853c76171c624fdfffac046b1fea5207f5ae4105bcd6cb018956514f998521",
"size": 22502,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.147Z",
"metadataPreserved": true
},
"achievement-faction-bescods-balanced-research": {
"sourceSha256": "ff6c0061eab0c7bbf8165781c3c387bdf5420d469557a8389a488711f174e494",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-bescods-balanced-research/f7ef5932b383392b/achievement-faction-bescods-balanced-research.webp",
"sha256": "f7ef5932b383392bc527e89267bf1218b714cfee9bbeb5d083c96281a8cd6933",
"size": 13720,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.190Z",
"metadataPreserved": true
},
"achievement-faction-ivits-growing-federation": {
"sourceSha256": "6c6d23c2a634c0b59528147bfb13c8e6287dbfc011f2966567feb41307eac393",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ivits-growing-federation/7167f0b15979c573/achievement-faction-ivits-growing-federation.webp",
"sha256": "7167f0b15979c57329404d3bab890404775a26b1f48a9060e2fd6d325c19872c",
"size": 14564,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.220Z",
"metadataPreserved": true
},
"achievement-faction-lantids-shared-civilization": {
"sourceSha256": "b7efe38eb028e9d160f54c4e0121ef3989d99a48a6e631cdd81f88fd04f3b5d2",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-lantids-shared-civilization/e8a687dc00861891/achievement-faction-lantids-shared-civilization.webp",
"sha256": "e8a687dc008618916da47b0ac660a6678aaaf803c7e64b64c8cc81919c52c286",
"size": 18568,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.254Z",
"metadataPreserved": true
},
"achievement-federation-form-4": {
"sourceSha256": "4af6c26009889ac856b801c1ec08067034ee3052e179be6b28704637634bb9c9",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-federation-form-4/7f148d86b726f823/achievement-federation-form-4.webp",
"sha256": "7f148d86b726f823c33f32809f66b49acb4700d4a0b7936ed6aa8e55cc3b7d30",
"size": 15356,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.289Z",
"metadataPreserved": true
},
"achievement-win-automa-alptrauma": {
"sourceSha256": "2d16d888cb1987b768872831ba7d7294617bd62b8f658c791a7148f81f753e80",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-win-automa-alptrauma/4e8048fdedb43b42/achievement-win-automa-alptrauma.webp",
"sha256": "4e8048fdedb43b421ac7355e6f4556a595d96dca4c6b99bc0348be739a71fb36",
"size": 17582,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.323Z",
"metadataPreserved": true
},
"achievement-win-automa-automa": {
"sourceSha256": "b72d601f3d0c218bd0275ab2f26581e3463499a84a4729b71f81c10a5f1b51d5",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-win-automa-automa/6a4c705d0f6ac810/achievement-win-automa-automa.webp",
"sha256": "6a4c705d0f6ac810c965ce5b4899209acb70c6c76365caee1d53750cfd37592f",
"size": 15464,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.383Z",
"metadataPreserved": true
},
"achievement-win-automa-automaechtig": {
"sourceSha256": "c6a97a930ec03d2dc7547f0b6e9639b0cfec881a80df2842140a46efdcebee61",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-win-automa-automaechtig/7a48232431034501/achievement-win-automa-automaechtig.webp",
"sha256": "7a48232431034501dc7a07a97ee4da091faa2d9b1d86be12c7277a88c7797e26",
"size": 16146,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.717Z",
"metadataPreserved": true
},
"achievement-win-automa-automalein": {
"sourceSha256": "0efdf83ec7d624a1d25ed278d89766a562801ec89a3c45f90d2e95bdcc14bda9",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-win-automa-automalein/1249beb87d342bac/achievement-win-automa-automalein.webp",
"sha256": "1249beb87d342bac6fb533a908e7e554222c8a317eba4cf1151b983dc33b643d",
"size": 14806,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.748Z",
"metadataPreserved": true
},
"achievement-win-automa-ultoma": {
"sourceSha256": "3d8752bbe24f181619e31cc689e1f71e8cb3587c70967f9a55ca801c57bc30bf",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-win-automa-ultoma/7c37bb4988578b08/achievement-win-automa-ultoma.webp",
"sha256": "7c37bb4988578b08a77656900a013fdd9a83c7400bca2ea144c17c62b227024a",
"size": 16748,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.801Z",
"metadataPreserved": true
},
"achievement-win-mode-base": {
"sourceSha256": "75dab63aec00f5fe19dbfb4a4eecdc74c8bda3425434604e46fc2ccc695d221e",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-win-mode-base/1a4c4898d833485a/achievement-win-mode-base.webp",
"sha256": "1a4c4898d833485aebbba1f2d660bd761b56146ea65fbb96e1928106042d2428",
"size": 18566,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.836Z",
"metadataPreserved": true
},
"achievement-win-mode-lost-fleet": {
"sourceSha256": "b9fa460ea945dfc3e7c51c343653ced48e2fc79a7bc9845b9e2342e1694e0f03",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-win-mode-lost-fleet/a8c4bf3f4ed49e72/achievement-win-mode-lost-fleet.webp",
"sha256": "a8c4bf3f4ed49e726b6d6fef818867fe70f909cd91f7e6751533d3802c616be5",
"size": 18964,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:05.872Z",
"metadataPreserved": true
}
},
"preserved": {
"achievement-faction-ambas": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ambas/d7937048f3aa6c75/achievement-faction-ambas.webp",
"sha256": "d7937048f3aa6c7546b31c0ca479cd5ed80a7edc215653bab3f279ca8d77de91",
"size": 8578,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:05.907Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ambas/d7937048f3aa6c75/achievement-faction-ambas.webp",
"contentType": "image/webp",
"size": 8578,
"uploadedAt": "2026-11-14T00:21:55.887Z"
}
},
"achievement-faction-baltaks": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-baltaks/d4e2cc2591b0e088/achievement-faction-baltaks.webp",
"sha256": "d4e2cc2591b0e088a6f0bb41d8fed1119bf7d0556d541c89b8809bc41aee58a8",
"size": 8368,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:05.932Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-baltaks/d4e2cc2591b0e088/achievement-faction-baltaks.webp",
"contentType": "image/webp",
"size": 8368,
"uploadedAt": "2026-11-14T00:21:56.410Z"
}
},
"achievement-faction-bescods": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-bescods/6d05714af6d47492/achievement-faction-bescods.webp",
"sha256": "6d05714af6d47492f6168d0dab128ceaee9f383444871cfdb33bf4555ac5c51c",
"size": 9766,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:05.958Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-bescods/6d05714af6d47492/achievement-faction-bescods.webp",
"contentType": "image/webp",
"size": 9766,
"uploadedAt": "2026-11-14T00:21:56.891Z"
}
},
"achievement-faction-darkanians": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-darkanians/6f11567b37a79672/achievement-faction-darkanians.webp",
"sha256": "6f11567b37a79672e0805e416b32f878f540af89f702c2dd9643cef8867ea6e4",
"size": 9200,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:05.988Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-darkanians/6f11567b37a79672/achievement-faction-darkanians.webp",
"contentType": "image/webp",
"size": 9200,
"uploadedAt": "2026-11-14T00:21:57.284Z"
}
},
"achievement-faction-firaks": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-firaks/187a5c29e5ebc1b1/achievement-faction-firaks.webp",
"sha256": "187a5c29e5ebc1b1621c178ce7473901f81d1f9b9806a7fb43b7b2c50f380c17",
"size": 8514,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.014Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-firaks/187a5c29e5ebc1b1/achievement-faction-firaks.webp",
"contentType": "image/webp",
"size": 8514,
"uploadedAt": "2026-11-14T00:21:57.662Z"
}
},
"achievement-faction-geodens": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-geodens/16ea770361a16fdf/achievement-faction-geodens.webp",
"sha256": "16ea770361a16fdfa98d6faca956be309dd03906afa3d0714537ddf9ef5e7248",
"size": 8838,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.041Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-geodens/16ea770361a16fdf/achievement-faction-geodens.webp",
"contentType": "image/webp",
"size": 8838,
"uploadedAt": "2026-11-14T00:21:58.061Z"
}
},
"achievement-faction-gleens": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-gleens/5cd106e053ca3952/achievement-faction-gleens.webp",
"sha256": "5cd106e053ca39527be8d27602ef52093fbae90b3573819fb6ff9ee8e451a8a1",
"size": 8268,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.069Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-gleens/5cd106e053ca3952/achievement-faction-gleens.webp",
"contentType": "image/webp",
"size": 8268,
"uploadedAt": "2026-11-14T00:21:58.510Z"
}
},
"achievement-faction-hadsch-hallas": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-hadsch-hallas/91d1136703d94477/achievement-faction-hadsch-hallas.webp",
"sha256": "91d1136703d944777ef09b0abcd34af439b9507f980176798a2b31668937508a",
"size": 8490,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.095Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-hadsch-hallas/91d1136703d94477/achievement-faction-hadsch-hallas.webp",
"contentType": "image/webp",
"size": 8490,
"uploadedAt": "2026-11-14T00:21:58.888Z"
}
},
"achievement-faction-itars": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-itars/7240e6d9dad1ee01/achievement-faction-itars.webp",
"sha256": "7240e6d9dad1ee01cde60116f90f016b5049c1bed1600f63d7ab9da973d83d4b",
"size": 7866,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.120Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-itars/7240e6d9dad1ee01/achievement-faction-itars.webp",
"contentType": "image/webp",
"size": 7866,
"uploadedAt": "2026-11-14T00:21:59.311Z"
}
},
"achievement-faction-ivits": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ivits/a7cae70e778b234e/achievement-faction-ivits.webp",
"sha256": "a7cae70e778b234e975921bf0bcb398b175f0a1f9c935fa00888bdad88465ca4",
"size": 7780,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.150Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ivits/a7cae70e778b234e/achievement-faction-ivits.webp",
"contentType": "image/webp",
"size": 7780,
"uploadedAt": "2026-11-14T00:21:59.745Z"
}
},
"achievement-faction-lantids": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-lantids/a45146b469f0f697/achievement-faction-lantids.webp",
"sha256": "a45146b469f0f69743438224b12b87d5eb333451ae4dd959eb0b94732abdcb7c",
"size": 7730,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.182Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-lantids/a45146b469f0f697/achievement-faction-lantids.webp",
"contentType": "image/webp",
"size": 7730,
"uploadedAt": "2026-11-14T00:22:00.319Z"
}
},
"achievement-faction-moweyds": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-moweyds/43cf990e3907d58c/achievement-faction-moweyds.webp",
"sha256": "43cf990e3907d58c63c4dfba3dd92c7dc8493e30447f09e23a6f37f6ab6b3e9e",
"size": 9238,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.210Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-moweyds/43cf990e3907d58c/achievement-faction-moweyds.webp",
"contentType": "image/webp",
"size": 9238,
"uploadedAt": "2026-11-14T00:22:00.717Z"
}
},
"achievement-faction-nevlas": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-nevlas/9150358d281068e8/achievement-faction-nevlas.webp",
"sha256": "9150358d281068e847f37eab4473b783d6d460b3d12a77f6ff18fa7383fb0a59",
"size": 7982,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.234Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-nevlas/9150358d281068e8/achievement-faction-nevlas.webp",
"contentType": "image/webp",
"size": 7982,
"uploadedAt": "2026-11-14T00:22:01.097Z"
}
},
"achievement-faction-space-giants": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-space-giants/be1ff3af83185a17/achievement-faction-space-giants.webp",
"sha256": "be1ff3af83185a174d2a0175e5f80c811fb27ded1056c7859847676e1a905368",
"size": 9194,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.260Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-space-giants/be1ff3af83185a17/achievement-faction-space-giants.webp",
"contentType": "image/webp",
"size": 9194,
"uploadedAt": "2026-11-14T00:22:01.524Z"
}
},
"achievement-faction-taklons": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-taklons/7d4ef15dfc3bc15a/achievement-faction-taklons.webp",
"sha256": "7d4ef15dfc3bc15ac149df6476d9c2e10fe16dfefd7b6ea5f3d26ace9658abb9",
"size": 8118,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.298Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-taklons/7d4ef15dfc3bc15a/achievement-faction-taklons.webp",
"contentType": "image/webp",
"size": 8118,
"uploadedAt": "2026-11-14T00:22:01.962Z"
}
},
"achievement-faction-terrans": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-terrans/a30b9d5e3f9dbbc6/achievement-faction-terrans.webp",
"sha256": "a30b9d5e3f9dbbc6acdec984510f291923dd6099501c43b89dcc59c2d8646c2f",
"size": 8922,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.327Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-terrans/a30b9d5e3f9dbbc6/achievement-faction-terrans.webp",
"contentType": "image/webp",
"size": 8922,
"uploadedAt": "2026-11-14T00:22:02.416Z"
}
},
"achievement-faction-tinkeroids": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-tinkeroids/ddf22fc3ea7a43e7/achievement-faction-tinkeroids.webp",
"sha256": "ddf22fc3ea7a43e70f0806450c95945b2bfc5439ce7379387bcf2277d5ea06f6",
"size": 8940,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.361Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-tinkeroids/ddf22fc3ea7a43e7/achievement-faction-tinkeroids.webp",
"contentType": "image/webp",
"size": 8940,
"uploadedAt": "2026-11-14T00:22:02.836Z"
}
},
"achievement-faction-xenos": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-xenos/3ab0339586a45d6e/achievement-faction-xenos.webp",
"sha256": "3ab0339586a45d6e69bbf4d4e007655b3bb9b3f5fc7580210de0e590ba719ddf",
"size": 8392,
"format": "webp",
"width": 167,
"height": 167,
"verifiedAt": "2026-11-14T12:46:06.386Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-xenos/3ab0339586a45d6e/achievement-faction-xenos.webp",
"contentType": "image/webp",
"size": 8392,
"uploadedAt": "2026-11-14T00:22:03.349Z"
}
},
"achievement-score-150": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-150/6ba2bb28578f2f20/achievement-score-150.webp",
"sha256": "6ba2bb28578f2f20f35835a00f5b51cdec38490b3b6e0625e921ec8eb668449a",
"size": 16454,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:06.420Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-150/6ba2bb28578f2f20/achievement-score-150.webp",
"contentType": "image/webp",
"size": 16454,
"uploadedAt": "2026-11-14T00:22:03.957Z"
}
},
"achievement-score-200": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-200/c2c299dc2850cd0c/achievement-score-200.webp",
"sha256": "c2c299dc2850cd0c94acd11e21e5a56a6ae691b580458d0906a514625154796b",
"size": 19724,
"format": "webp",
"width": 512,
"height": 512,
"verifiedAt": "2026-11-14T12:46:06.762Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-200/c2c299dc2850cd0c/achievement-score-200.webp",
"contentType": "image/webp",
"size": 19724,
"uploadedAt": "2026-11-14T00:22:04.531Z"
}
},
"pictogram": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/pictogram/09bdce75fb8e0020/pictogram.webp",
"sha256": "09bdce75fb8e0020a1b52e9e4352d62bced93b117e94704549e0662e04093a62",
"size": 29934,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:46:06.786Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/pictogram/09bdce75fb8e0020/pictogram.webp",
"contentType": "image/webp",
"size": 29934,
"uploadedAt": "2026-09-28T23:30:11.491Z",
"name": "Game pictogram"
}
},
"screenshot-showcase-1": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-1/ccc2f1db5fd8e665/screenshot-showcase-1.webp",
"sha256": "ccc2f1db5fd8e6654075d9d8629e3f20e0e6f9abd56efe8e85b58bd25c1dc7c8",
"size": 223980,
"format": "webp",
"width": 1536,
"height": 993,
"verifiedAt": "2026-11-14T12:46:06.868Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-1/ccc2f1db5fd8e665/screenshot-showcase-1.webp",
"contentType": "image/webp",
"size": 223980,
"name": "Explore the galaxy with The Lost Fleet",
"uploadedAt": "2026-10-04T22:16:59.964Z"
}
},
"screenshot-showcase-1-dark": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-1-dark/3ab3ef4a571e52de/screenshot-showcase-1-dark.webp",
"sha256": "3ab3ef4a571e52de7fb3199b6dcd95562ecd886721d8cc753b0fa5ff52c57f92",
"size": 213022,
"format": "webp",
"width": 1536,
"height": 993,
"verifiedAt": "2026-11-14T12:46:06.941Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-1-dark/3ab3ef4a571e52de/screenshot-showcase-1-dark.webp",
"contentType": "image/webp",
"size": 213022,
"name": "Explore the galaxy with The Lost Fleet",
"uploadedAt": "2026-10-04T22:17:00.047Z"
}
},
"screenshot-showcase-2": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-2/59a59d64eb3940d5/screenshot-showcase-2.webp",
"sha256": "59a59d64eb3940d5484d5b5d70827b4ede7cf68919fc821c3c5aed3b40596411",
"size": 55186,
"format": "webp",
"width": 768,
"height": 542,
"verifiedAt": "2026-11-14T12:46:06.977Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-2/59a59d64eb3940d5/screenshot-showcase-2.webp",
"contentType": "image/webp",
"size": 55186,
"name": "Your faction board: buildings, resources and power",
"uploadedAt": "2026-10-04T22:17:00.123Z"
}
},
"screenshot-showcase-2-dark": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-2-dark/ae2cb0e097f947ed/screenshot-showcase-2-dark.webp",
"sha256": "ae2cb0e097f947ed6d990070ab115e495f1a2a99a354db4c29f56e3dc71dc266",
"size": 54732,
"format": "webp",
"width": 768,
"height": 542,
"verifiedAt": "2026-11-14T12:46:07.013Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-2-dark/ae2cb0e097f947ed/screenshot-showcase-2-dark.webp",
"contentType": "image/webp",
"size": 54732,
"name": "Your faction board: buildings, resources and power",
"uploadedAt": "2026-10-04T22:17:00.281Z"
}
},
"screenshot-showcase-3": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-3/7e7bdf1548c8c7ad/screenshot-showcase-3.webp",
"sha256": "7e7bdf1548c8c7ad13e9bc9e2b6f93b9c701af24e1ab5994233af097a4a365a8",
"size": 32518,
"format": "webp",
"width": 1276,
"height": 350,
"verifiedAt": "2026-11-14T12:46:07.050Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-3/7e7bdf1548c8c7ad/screenshot-showcase-3.webp",
"contentType": "image/webp",
"size": 32518,
"name": "Follow every move and resource change in the game log",
"uploadedAt": "2026-10-04T22:17:00.367Z"
}
},
"screenshot-showcase-3-dark": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-3-dark/1047e87797338aac/screenshot-showcase-3-dark.webp",
"sha256": "1047e87797338aacc7b8d6fe0d4644b9aee286493e1609245418fb742cebc9f8",
"size": 31898,
"format": "webp",
"width": 1276,
"height": 350,
"verifiedAt": "2026-11-14T12:46:07.162Z",
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/screenshot-showcase-3-dark/1047e87797338aac/screenshot-showcase-3-dark.webp",
"contentType": "image/webp",
"size": 31898,
"name": "Follow every move and resource change in the game log",
"uploadedAt": "2026-10-04T22:17:00.419Z"
}
}
},
"planSha256": "af86352546069a0a95c3480fa6e6a0378f0558e431fa5c28f0d34f00cd8b1a71",
"activationReceiptSha256": "233c7f2afe85eef8a21fd5d1d351509107ad8fe29b4311d3f5aa7040a4ce6bc2",
"tgzSha256": "a21b4c587f6488fb1c75a9c6a81c182230b2ed7e9272172f33866e0d0e1df151",
"package": {
"name": "@gaia-project/engine",
"version": "4.17.10",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/a21b4c587f6488fb/gaia-project-engine-4.17.10.tgz",
"size": 915098,
"sha256": "a21b4c587f6488fb1c75a9c6a81c182230b2ed7e9272172f33866e0d0e1df151"
},
"hostedPackage": {
"name": "@gaia-project/engine",
"version": "4.17.10",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/a21b4c587f6488fb/gaia-project-engine-4.17.10.tgz",
"size": 915098,
"sha256": "a21b4c587f6488fb1c75a9c6a81c182230b2ed7e9272172f33866e0d0e1df151"
},
"manifest": {
"revision": 5,
"achievements": [
{
"id": "win-faction-terrans",
"icon": {
"type": "asset",
"key": "achievement-faction-terrans"
},
"name": "Terrans Victory",
"description": "Win as Terrans. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-lantids",
"icon": {
"type": "asset",
"key": "achievement-faction-lantids"
},
"name": "Lantids Victory",
"description": "Win as Lantids. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-hadsch-hallas",
"icon": {
"type": "asset",
"key": "achievement-faction-hadsch-hallas"
},
"name": "Hadsch Hallas Victory",
"description": "Win as Hadsch Hallas. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-ivits",
"icon": {
"type": "asset",
"key": "achievement-faction-ivits"
},
"name": "Ivits Victory",
"description": "Win as Ivits. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-geodens",
"icon": {
"type": "asset",
"key": "achievement-faction-geodens"
},
"name": "Geodens Victory",
"description": "Win as Geodens. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-baltaks",
"icon": {
"type": "asset",
"key": "achievement-faction-baltaks"
},
"name": "Baltaks Victory",
"description": "Win as Baltaks. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-xenos",
"icon": {
"type": "asset",
"key": "achievement-faction-xenos"
},
"name": "Xenos Victory",
"description": "Win as Xenos. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-gleens",
"icon": {
"type": "asset",
"key": "achievement-faction-gleens"
},
"name": "Gleens Victory",
"description": "Win as Gleens. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-taklons",
"icon": {
"type": "asset",
"key": "achievement-faction-taklons"
},
"name": "Taklons Victory",
"description": "Win as Taklons. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-ambas",
"icon": {
"type": "asset",
"key": "achievement-faction-ambas"
},
"name": "Ambas Victory",
"description": "Win as Ambas. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-firaks",
"icon": {
"type": "asset",
"key": "achievement-faction-firaks"
},
"name": "Firaks Victory",
"description": "Win as Firaks. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-bescods",
"icon": {
"type": "asset",
"key": "achievement-faction-bescods"
},
"name": "Bescods Victory",
"description": "Win as Bescods. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-nevlas",
"icon": {
"type": "asset",
"key": "achievement-faction-nevlas"
},
"name": "Nevlas Victory",
"description": "Win as Nevlas. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-itars",
"icon": {
"type": "asset",
"key": "achievement-faction-itars"
},
"name": "Itars Victory",
"description": "Win as Itars. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-tinkeroids",
"icon": {
"type": "asset",
"key": "achievement-faction-tinkeroids"
},
"name": "Tinkeroids Victory",
"description": "Win as Tinkeroids. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-darkanians",
"icon": {
"type": "asset",
"key": "achievement-faction-darkanians"
},
"name": "Darkanians Victory",
"description": "Win as Darkanians. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-moweyds",
"icon": {
"type": "asset",
"key": "achievement-faction-moweyds"
},
"name": "Moweyds Victory",
"description": "Win as Moweyds. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-faction-space-giants",
"icon": {
"type": "asset",
"key": "achievement-faction-space-giants"
},
"name": "Space Giants Victory",
"description": "Win as Space Giants. Shared first place counts; either ruleset qualifies."
},
{
"id": "win-mode-base",
"icon": {
"type": "asset",
"key": "achievement-win-mode-base"
},
"name": "Base Game Victory",
"description": "Win a Base Game game, including shared first place."
},
{
"id": "score-base-150",
"icon": {
"type": "asset",
"key": "achievement-score-150"
},
"name": "Base Game: 150 Points",
"description": "Finish a Base Game game with at least 150 final victory points, after auction deductions. No win required."
},
{
"id": "score-base-200",
"icon": {
"type": "asset",
"key": "achievement-score-200"
},
"name": "Base Game: 200 Points",
"description": "Finish a Base Game game with at least 200 final victory points, after auction deductions. No win required."
},
{
"id": "win-mode-lost-fleet",
"icon": {
"type": "asset",
"key": "achievement-win-mode-lost-fleet"
},
"name": "Lost Fleet Victory",
"description": "Win a Lost Fleet game, including shared first place."
},
{
"id": "score-lost-fleet-150",
"icon": {
"type": "asset",
"key": "achievement-score-150"
},
"name": "Lost Fleet: 150 Points",
"description": "Finish a Lost Fleet game with at least 150 final victory points, after auction deductions. No win required."
},
{
"id": "score-lost-fleet-200",
"icon": {
"type": "asset",
"key": "achievement-score-200"
},
"name": "Lost Fleet: 200 Points",
"description": "Finish a Lost Fleet game with at least 200 final victory points, after auction deductions. No win required."
},
{
"id": "win-automa-automalein",
"icon": {
"type": "asset",
"key": "achievement-win-automa-automalein"
},
"name": "Defeat Automalein",
"description": "Win against Automa at exactly automalein difficulty. A tied score counts as a human win."
},
{
"id": "win-automa-automa",
"icon": {
"type": "asset",
"key": "achievement-win-automa-automa"
},
"name": "Defeat Automa",
"description": "Win against Automa at exactly automa difficulty. A tied score counts as a human win."
},
{
"id": "win-automa-automaechtig",
"icon": {
"type": "asset",
"key": "achievement-win-automa-automaechtig"
},
"name": "Defeat Automaechtig",
"description": "Win against Automa at exactly automaechtig difficulty. A tied score counts as a human win."
},
{
"id": "win-automa-ultoma",
"icon": {
"type": "asset",
"key": "achievement-win-automa-ultoma"
},
"name": "Defeat Ultoma",
"description": "Win against Automa at exactly ultoma difficulty. A tied score counts as a human win."
},
{
"id": "win-automa-alptrauma",
"icon": {
"type": "asset",
"key": "achievement-win-automa-alptrauma"
},
"name": "Defeat Alptrauma",
"description": "Win against Automa at exactly alptrauma difficulty. A tied score counts as a human win."
},
{
"id": "build-all-standard",
"icon": {
"type": "asset",
"key": "achievement-build-all-standard"
},
"name": "Full Deployment",
"description": "Finish with all 18 standard building pieces simultaneously deployed: 8 mines, 4 trading stations, 3 research labs, the institute and both academies. Excludes Lost Planet, artifacts, Gaiaformers and space stations. No win required."
},
{
"id": "federation-form-4",
"icon": {
"type": "asset",
"key": "achievement-federation-form-4"
},
"name": "Federation Builder",
"description": "Complete at least four federation formations in one game (extensions of the growing federation for Ivits). Token rewards and rescores do not count. No win required."
},
{
"id": "explore-all-types-base",
"icon": {
"type": "asset",
"key": "achievement-explore-all-types-base"
},
"name": "Every World: Base Game",
"description": "Finish a base game with main-owned colonies on all seven ordinary planet types, Gaia and the Lost Planet. Gaiaformers and Lantids shared mines do not count. No win required."
},
{
"id": "explore-all-types-lost-fleet",
"icon": {
"type": "asset",
"key": "achievement-explore-all-types-lost-fleet"
},
"name": "Every World: Lost Fleet",
"description": "Finish a Lost Fleet game with main-owned colonies on all seven ordinary types, Gaia, Lost Planet, Asteroid and Protoplanet. Artifacts, Gaiaformers and Lantids shared mines do not count. No win required."
},
{
"id": "faction-ivits-growing-federation",
"icon": {
"type": "asset",
"key": "achievement-faction-ivits-growing-federation"
},
"name": "Growing Federation",
"description": "As Ivits, complete at least four formation milestones of your growing federation in one game. No win required."
},
{
"id": "faction-lantids-shared-civilization",
"icon": {
"type": "asset",
"key": "achievement-faction-lantids-shared-civilization"
},
"name": "Shared Civilization",
"description": "As Lantids, finish with at least six additional mines on opponents' colonies. No win required."
},
{
"id": "faction-bescods-balanced-research",
"icon": {
"type": "asset",
"key": "achievement-faction-bescods-balanced-research"
},
"name": "Balanced Research",
"description": "As Bescods, finish at level 3 or higher on all six research tracks. No win required."
}
]
},
"verification": {
"publicCatalog": true,
"allAssets": true,
"unchangedMetadata": true
},
"reconciliation": {
"readOnly": true,
"additionalPOSTs": 0,
"originalIncompleteReceiptSha256": "762fb42ea5dfdfa69cbb1cad5eb67120b298b6b50322f8afda89b34b0580d6bd",
"originalStage": "awaiting-installer",
"originalReceiptUnmodified": true
}
}

View file

@ -0,0 +1,39 @@
# Engine 4.17.10 publication receipt
The adjacent `engine-4.17.10.json` is the sanitized combined asset and activation
receipt for the original production publication, including read-only reconciliation
of its initially incomplete installer receipt. No duplicate engine POST was made.
- Approved source: `a96681aa6123b1e607763bdb37cbf1b9ed231e3d`.
- Independent approval: `sub-1794658886674-c27120b5` (shared release coordination).
- Exact original tarball SHA-256:
`a21b4c587f6488fb1c75a9c6a81c182230b2ed7e9272172f33866e0d0e1df151`.
- Artwork manifest SHA-256:
`4476a12a56b9c61e1dccfc17d02be9a6a60954371eab3f37a0c09236b954275a`.
- Live engine 4.17.10, manifest revision 5: 36 achievement definitions,
14 new illustrations and 22 preserved achievement rows (20 distinct assets).
- Canonical delivery: GitHub `boardgamers/gaia-project`, `master`.
The separate private `lost-fleet` fork is not a required mirror and was not pushed.
## Source-delivery checks
Anonymous GET of `https://boardgamers.space/api/boardgame/gaia-project/info/latest`
matched the complete receipt manifest and engine package reference. All 41 hosted
assets (14 new, 20 preserved achievement images, seven other preserved assets)
matched receipt SHA-256, byte size, format and dimensions and decoded successfully.
Preserved asset metadata matched exactly; all 14 local source PNG hashes matched.
The original local tarball and anonymously downloaded hosted package both matched
the approved hash and hosted byte count (915098); neither was rebuilt or repacked.
Two existing focused scene tests passed against the extracted exact tarball:
complete protocol references/preserved definitions/evaluator and depicted semantic
counts/difficulty mapping. The initial extracted-package invocation lacked dependency
resolution; rerunning with `NODE_PATH` pointing to existing engine dependencies
passed. No installation or rebuild was needed. The export-generation test was not
rerun because this delivery does not regenerate artwork.
The sanitized receipt records unchanged publication metadata. Viewer, settings and
visibility were not changed by this delivery; only these release documents were
added after the reviewed source commit. No upload, activation, server, preview or
original-checkout mutation was performed. Private raw receipts and metadata
snapshots are not included; reconciliation retains only their SHA-256 evidence.

View file

@ -0,0 +1,67 @@
{
"game": "gaia-project",
"gameinfoVersion": 3,
"engineVersion": "4.17.11",
"sourceCommit": "5a7fdec4a04a12bca90d33335be6575bb2ded50a",
"verifiedAt": "2026-11-14T18:10:20.088Z",
"engine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.11",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/42758e9e66dcfe60/gaia-project-engine-4.17.11.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"previousEngine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.10",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/a21b4c587f6488fb/gaia-project-engine-4.17.10.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"tarball": {
"filename": "gaia-project-engine-4.17.11.tgz",
"sha256": "42758e9e66dcfe60dcfe31ba6b4a718f175d9be01c6be1e03c63a601aac3d2f2",
"bytes": 917691
},
"publicPackageHashVerified": true,
"viewerSettingsAchievementsAssetsPreserved": true,
"productionGamesModified": false,
"verificationNote": "Upload response is raw version metadata; fresh admin GET confirmed merged shared asset metadata unchanged. One engine POST only.",
"activation": {
"key": "gaia-project_3_gaia-project-engine_4.17.11_a3dd947b3cc16656",
"engine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.11",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/42758e9e66dcfe60/gaia-project-engine-4.17.11.tgz"
},
"entryPoint": "dist/wrapper.js"
}
},
"checks": {
"enginePassed": 1021,
"enginePending": 4,
"viewerPassed": 1171,
"viewerFiles": 100,
"engineBuild": "passed",
"viewerBuild": "passed; not published",
"oldUiBuild": "passed; not published",
"engineLintErrors": 0,
"engineLintWarnings": 247,
"viewerLint": "passed",
"prettier": "passed",
"frozenInstall": "passed; lockfiles unchanged",
"packedRematches": "1–4 players passed",
"browserProtocol": "8 configurations passed: both viewers, base/Lost Fleet, mobile/desktop",
"browserUndo": "4 configurations passed: both viewers, mobile/desktop",
"productionBrowser": {
"url": "https://boardgamers.space/game/Abstract-piston-1122",
"status": 200,
"viewerRendered": true,
"uncaughtErrors": 0
}
},
"status": "active"
}

View file

@ -0,0 +1,590 @@
{
"game": "gaia-project",
"gameinfoVersion": 3,
"engineVersion": "4.17.8",
"manifestRevision": 3,
"startedAt": "2026-11-14T00:21:55.666306+00:00",
"enginePublished": true,
"assets": [
{
"key": "achievement-faction-ambas",
"inputPath": "artifacts/achievement-portraits/achievement-faction-ambas.png",
"inputSha256": "df6acb77b185a8ae30b01f623c6f43ffa8035bcaaa53d6345c37ae0a38180e42",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ambas/d7937048f3aa6c75/achievement-faction-ambas.webp",
"contentType": "image/webp",
"size": 8578,
"uploadedAt": "2026-11-14T00:21:55.887Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ambas/d7937048f3aa6c75/achievement-faction-ambas.webp",
"storedSha256": "d7937048f3aa6c7546b31c0ca479cd5ed80a7edc215653bab3f279ca8d77de91",
"size": 8578,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 5.1607
},
{
"key": "achievement-faction-baltaks",
"inputPath": "artifacts/achievement-portraits/achievement-faction-baltaks.png",
"inputSha256": "82ed62af00c8ede5fbea286761de9b24b1ab97c933503f25ff67ffd3a0f840d5",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-baltaks/d4e2cc2591b0e088/achievement-faction-baltaks.webp",
"contentType": "image/webp",
"size": 8368,
"uploadedAt": "2026-11-14T00:21:56.410Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-baltaks/d4e2cc2591b0e088/achievement-faction-baltaks.webp",
"storedSha256": "d4e2cc2591b0e088a6f0bb41d8fed1119bf7d0556d541c89b8809bc41aee58a8",
"size": 8368,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 5.3254
},
{
"key": "achievement-faction-bescods",
"inputPath": "artifacts/achievement-portraits/achievement-faction-bescods.png",
"inputSha256": "ebf767f204767840eb39b985713991708fd2e486dd02222e3f0104097592c5e8",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-bescods/6d05714af6d47492/achievement-faction-bescods.webp",
"contentType": "image/webp",
"size": 9766,
"uploadedAt": "2026-11-14T00:21:56.891Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-bescods/6d05714af6d47492/achievement-faction-bescods.webp",
"storedSha256": "6d05714af6d47492f6168d0dab128ceaee9f383444871cfdb33bf4555ac5c51c",
"size": 9766,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.658
},
{
"key": "achievement-faction-darkanians",
"inputPath": "artifacts/achievement-portraits/achievement-faction-darkanians.png",
"inputSha256": "f28ef1a392d436be71adc0114cd3d9b02729c84febf0d0e0e146931736bb4938",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-darkanians/6f11567b37a79672/achievement-faction-darkanians.webp",
"contentType": "image/webp",
"size": 9200,
"uploadedAt": "2026-11-14T00:21:57.284Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-darkanians/6f11567b37a79672/achievement-faction-darkanians.webp",
"storedSha256": "6f11567b37a79672e0805e416b32f878f540af89f702c2dd9643cef8867ea6e4",
"size": 9200,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.1296
},
{
"key": "achievement-faction-firaks",
"inputPath": "artifacts/achievement-portraits/achievement-faction-firaks.png",
"inputSha256": "ca0fae27a89effd01014d4a652f704df141222af6509846e5fbf25d87b1f7dc2",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-firaks/187a5c29e5ebc1b1/achievement-faction-firaks.webp",
"contentType": "image/webp",
"size": 8514,
"uploadedAt": "2026-11-14T00:21:57.662Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-firaks/187a5c29e5ebc1b1/achievement-faction-firaks.webp",
"storedSha256": "187a5c29e5ebc1b1621c178ce7473901f81d1f9b9806a7fb43b7b2c50f380c17",
"size": 8514,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.3113
},
{
"key": "achievement-faction-geodens",
"inputPath": "artifacts/achievement-portraits/achievement-faction-geodens.png",
"inputSha256": "3a0a4b9889b74d0cbcb15ddc2897357f826151971e58e1a9f01e17da039b0fa7",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-geodens/16ea770361a16fdf/achievement-faction-geodens.webp",
"contentType": "image/webp",
"size": 8838,
"uploadedAt": "2026-11-14T00:21:58.061Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-geodens/16ea770361a16fdf/achievement-faction-geodens.webp",
"storedSha256": "16ea770361a16fdfa98d6faca956be309dd03906afa3d0714537ddf9ef5e7248",
"size": 8838,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 5.3393
},
{
"key": "achievement-faction-gleens",
"inputPath": "artifacts/achievement-portraits/achievement-faction-gleens.png",
"inputSha256": "39dc2bee151f6a88aa802559517ec83f55a5a94f6760026574ac5d976d38d2da",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-gleens/5cd106e053ca3952/achievement-faction-gleens.webp",
"contentType": "image/webp",
"size": 8268,
"uploadedAt": "2026-11-14T00:21:58.510Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-gleens/5cd106e053ca3952/achievement-faction-gleens.webp",
"storedSha256": "5cd106e053ca39527be8d27602ef52093fbae90b3573819fb6ff9ee8e451a8a1",
"size": 8268,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 5.1265
},
{
"key": "achievement-faction-hadsch-hallas",
"inputPath": "artifacts/achievement-portraits/achievement-faction-hadsch-hallas.png",
"inputSha256": "713c816aff4598691cad493d4702a2219624f2a5ae6940bcba29588763d629fa",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-hadsch-hallas/91d1136703d94477/achievement-faction-hadsch-hallas.webp",
"contentType": "image/webp",
"size": 8490,
"uploadedAt": "2026-11-14T00:21:58.888Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-hadsch-hallas/91d1136703d94477/achievement-faction-hadsch-hallas.webp",
"storedSha256": "91d1136703d944777ef09b0abcd34af439b9507f980176798a2b31668937508a",
"size": 8490,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 5.341
},
{
"key": "achievement-faction-itars",
"inputPath": "artifacts/achievement-portraits/achievement-faction-itars.png",
"inputSha256": "088951a4c338276bcdd8f95527ec2b6d6c19730c334381e53f0332f6415cf930",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-itars/7240e6d9dad1ee01/achievement-faction-itars.webp",
"contentType": "image/webp",
"size": 7866,
"uploadedAt": "2026-11-14T00:21:59.311Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-itars/7240e6d9dad1ee01/achievement-faction-itars.webp",
"storedSha256": "7240e6d9dad1ee01cde60116f90f016b5049c1bed1600f63d7ab9da973d83d4b",
"size": 7866,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.1517
},
{
"key": "achievement-faction-ivits",
"inputPath": "artifacts/achievement-portraits/achievement-faction-ivits.png",
"inputSha256": "96ec38b9df41297b46b65eca2b4b44296eade9d68725457e1271d1d20a59c5eb",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ivits/a7cae70e778b234e/achievement-faction-ivits.webp",
"contentType": "image/webp",
"size": 7780,
"uploadedAt": "2026-11-14T00:21:59.745Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-ivits/a7cae70e778b234e/achievement-faction-ivits.webp",
"storedSha256": "a7cae70e778b234e975921bf0bcb398b175f0a1f9c935fa00888bdad88465ca4",
"size": 7780,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 5.027
},
{
"key": "achievement-faction-lantids",
"inputPath": "artifacts/achievement-portraits/achievement-faction-lantids.png",
"inputSha256": "3c65910ef0f1418ef65e6b3c44f0354ea9a447c465aaf555634dd944a1ae9890",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-lantids/a45146b469f0f697/achievement-faction-lantids.webp",
"contentType": "image/webp",
"size": 7730,
"uploadedAt": "2026-11-14T00:22:00.319Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-lantids/a45146b469f0f697/achievement-faction-lantids.webp",
"storedSha256": "a45146b469f0f69743438224b12b87d5eb333451ae4dd959eb0b94732abdcb7c",
"size": 7730,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.6266
},
{
"key": "achievement-faction-moweyds",
"inputPath": "artifacts/achievement-portraits/achievement-faction-moweyds.png",
"inputSha256": "5187fa64cf152bba82d2dfae465c76cea7dc124f2f159127bd41142c4a83a70c",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-moweyds/43cf990e3907d58c/achievement-faction-moweyds.webp",
"contentType": "image/webp",
"size": 9238,
"uploadedAt": "2026-11-14T00:22:00.717Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-moweyds/43cf990e3907d58c/achievement-faction-moweyds.webp",
"storedSha256": "43cf990e3907d58c63c4dfba3dd92c7dc8493e30447f09e23a6f37f6ab6b3e9e",
"size": 9238,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.2274
},
{
"key": "achievement-faction-nevlas",
"inputPath": "artifacts/achievement-portraits/achievement-faction-nevlas.png",
"inputSha256": "483c117c8ed577e23fcdfc197c925986a0a02c2e5c659e804f9d73e766ea6659",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-nevlas/9150358d281068e8/achievement-faction-nevlas.webp",
"contentType": "image/webp",
"size": 7982,
"uploadedAt": "2026-11-14T00:22:01.097Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-nevlas/9150358d281068e8/achievement-faction-nevlas.webp",
"storedSha256": "9150358d281068e847f37eab4473b783d6d460b3d12a77f6ff18fa7383fb0a59",
"size": 7982,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.2623
},
{
"key": "achievement-faction-space-giants",
"inputPath": "artifacts/achievement-portraits/achievement-faction-space-giants.png",
"inputSha256": "1eeb9cced6717ad972b2800c5784d79fc77bc6e06327f74e0bd7406054bd341b",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-space-giants/be1ff3af83185a17/achievement-faction-space-giants.webp",
"contentType": "image/webp",
"size": 9194,
"uploadedAt": "2026-11-14T00:22:01.524Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-space-giants/be1ff3af83185a17/achievement-faction-space-giants.webp",
"storedSha256": "be1ff3af83185a174d2a0175e5f80c811fb27ded1056c7859847676e1a905368",
"size": 9194,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.5426
},
{
"key": "achievement-faction-taklons",
"inputPath": "artifacts/achievement-portraits/achievement-faction-taklons.png",
"inputSha256": "7a61266c3b526da5cc1cadaeb1074610dc83c71a498324ee67467b09f870715f",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-taklons/7d4ef15dfc3bc15a/achievement-faction-taklons.webp",
"contentType": "image/webp",
"size": 8118,
"uploadedAt": "2026-11-14T00:22:01.962Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-taklons/7d4ef15dfc3bc15a/achievement-faction-taklons.webp",
"storedSha256": "7d4ef15dfc3bc15ac149df6476d9c2e10fe16dfefd7b6ea5f3d26ace9658abb9",
"size": 8118,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.4539
},
{
"key": "achievement-faction-terrans",
"inputPath": "artifacts/achievement-portraits/achievement-faction-terrans.png",
"inputSha256": "7b07b1d7dc6ce2a8101a5e398b94b615c6a476adb017af01fd41b1bd34a4c27f",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-terrans/a30b9d5e3f9dbbc6/achievement-faction-terrans.webp",
"contentType": "image/webp",
"size": 8922,
"uploadedAt": "2026-11-14T00:22:02.416Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-terrans/a30b9d5e3f9dbbc6/achievement-faction-terrans.webp",
"storedSha256": "a30b9d5e3f9dbbc6acdec984510f291923dd6099501c43b89dcc59c2d8646c2f",
"size": 8922,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.6844
},
{
"key": "achievement-faction-tinkeroids",
"inputPath": "artifacts/achievement-portraits/achievement-faction-tinkeroids.png",
"inputSha256": "4eabea79256d8b8f13d77a342dd2bafc6a657ed05c44929bd26cebaa0597e701",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-tinkeroids/ddf22fc3ea7a43e7/achievement-faction-tinkeroids.webp",
"contentType": "image/webp",
"size": 8940,
"uploadedAt": "2026-11-14T00:22:02.836Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-tinkeroids/ddf22fc3ea7a43e7/achievement-faction-tinkeroids.webp",
"storedSha256": "ddf22fc3ea7a43e70f0806450c95945b2bfc5439ce7379387bcf2277d5ea06f6",
"size": 8940,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.3117
},
{
"key": "achievement-faction-xenos",
"inputPath": "artifacts/achievement-portraits/achievement-faction-xenos.png",
"inputSha256": "50e0b839bab91945cd917046e7a0d2eacedbe0989b8f2984c7fcf5c8a973a37f",
"expectedWidth": 167,
"expectedHeight": 167,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-xenos/3ab0339586a45d6e/achievement-faction-xenos.webp",
"contentType": "image/webp",
"size": 8392,
"uploadedAt": "2026-11-14T00:22:03.349Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-faction-xenos/3ab0339586a45d6e/achievement-faction-xenos.webp",
"storedSha256": "3ab0339586a45d6e69bbf4d4e007655b3bb9b3f5fc7580210de0e590ba719ddf",
"size": 8392,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 167,
"decodedHeight": 167,
"meanAbsolutePixelError": 4.8185
},
{
"key": "achievement-score-150",
"inputPath": "artifacts/achievement-portraits/achievement-score-150.png",
"inputSha256": "6f6159efff9654c1fe874f1b55ae12e91cc4022b6c23092474343d6047a34f76",
"expectedWidth": 512,
"expectedHeight": 512,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-150/6ba2bb28578f2f20/achievement-score-150.webp",
"contentType": "image/webp",
"size": 16454,
"uploadedAt": "2026-11-14T00:22:03.957Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-150/6ba2bb28578f2f20/achievement-score-150.webp",
"storedSha256": "6ba2bb28578f2f20f35835a00f5b51cdec38490b3b6e0625e921ec8eb668449a",
"size": 16454,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 512,
"decodedHeight": 512,
"meanAbsolutePixelError": 1.4756
},
{
"key": "achievement-score-200",
"inputPath": "artifacts/achievement-portraits/achievement-score-200.png",
"inputSha256": "2d7815f572b0fad9ad2a73b3448d4f898a506d1fc118668fa66f27d6afe9b078",
"expectedWidth": 512,
"expectedHeight": 512,
"uploadStatus": 200,
"metadata": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-200/c2c299dc2850cd0c/achievement-score-200.webp",
"contentType": "image/webp",
"size": 19724,
"uploadedAt": "2026-11-14T00:22:04.531Z"
},
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/gaia-project/achievement-score-200/c2c299dc2850cd0c/achievement-score-200.webp",
"storedSha256": "c2c299dc2850cd0c94acd11e21e5a56a6ae691b580458d0906a514625154796b",
"size": 19724,
"publicStatus": 200,
"contentType": "image/webp",
"decodedWidth": 512,
"decodedHeight": 512,
"meanAbsolutePixelError": 1.939
}
],
"assetsVerifiedAt": "2026-11-14T00:22:05.047346+00:00",
"metadataReadback": "all 20 matched",
"assetsPixelVerifiedAt": "2026-11-14T00:22:19.583Z",
"catalogAssetCoverage": "exact match: 22 references, 20 keys",
"status": "active",
"activeEngineVersion": "4.17.8",
"sourceMergeCommit": "0f37489aa3f265ae765d589097fb5e9ed877f502",
"versionCommit": "ef589687d8cd0da0201734a0c527a495d948e6d5",
"pullRequest": "https://github.com/boardgamers/gaia-project/pull/343",
"platformPullRequest": "https://codeberg.org/boardgamers/boardgamers/pulls/578",
"checks": {
"engine": {
"passed": 999,
"pending": 4
},
"viewer": {
"files": 100,
"passed": 1171,
"nodeOptions": "--max-old-space-size=12288",
"maxWorkers": 1
},
"portraitGenerator": {
"passed": 2
},
"engineBuild": "passed",
"viewerBuild": "passed; not published",
"engineLint": {
"errors": 0,
"warnings": 247
},
"viewerLint": "passed",
"prettier": "passed",
"actualPlatformSchemas": "Official npm validators passed: manifest revision3,36 IDs,22 asset refs,20 keys and four fixture seats",
"builtViewerBrowser": "CDN Vue2/BootstrapVue IIFE launch and completed fixture render passed, no uncaught JS errors; legacy fixture resource requests returned 410",
"lockfile": "Registry install and frozen install passed; only protocol resolution changed",
"commonJsRuntime": "Built wrapper loaded; achievement JavaScript has no runtime protocol import",
"freshCheckRunAt": "2026-11-14T00:24:37.920119+00:00"
},
"previousAssetAttempt": {
"at": "2026-11-13T22:52:32.553967+00:00",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/achievement-faction-ambas/d7937048f3aa6c75/achievement-faction-ambas.webp",
"publicStatus": 403,
"resolution": "Dedicated achievements namespace deployed; all 20 keys reuploaded and anonymously verified."
},
"protocol": {
"version": "0.11.0",
"source": "npm registry",
"integrity": "sha512-YQ54+aVOIZvxUJvFmUbZR7xSBEgQaemstPdmYKVGCUHCviRX2UXRLgqLSQl6PFhr++lUT+Nynbf+p7h19zN+/g==",
"tarball": "https://registry.npmjs.org/@boardgamers/protocol/-/protocol-0.11.0.tgz",
"sha256": "ce9b1448dc8abbb9f26be95d300c828c6808d072f8f6ee6ec37a56a2a2cfc2fc",
"engineAndViewerInstalled": true
},
"tarball": {
"filename": "gaia-project-engine-4.17.8.tgz",
"sha256": "cc8dec51ea635414073849e8255da1f806db93105374b74f6166f02ed75b1d86",
"bytes": 914763
},
"policy": {
"at": "2026-11-13T23:29:35.034Z",
"bucket": "bgs-assets",
"version": "2023-04-17",
"statementCountBefore": 5,
"statementCountAfter": 6,
"priorStatementsUnchanged": true,
"ownerBucketAndObjectAccessPreserved": true,
"concurrentChangeCheck": "passed immediately before write",
"addedStatement": {
"Sid": "PublicAchievementsGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "bgs-assets/achievements/*"
},
"beforeBackup": "/home/bgs/.local/state/bgs-policy-backups/achievements-namespace-before-2026-11-13T23-29-32-625Z.json",
"beforeSha256": "31760187a5a92e56b0acdb6a57a88f1a500b21e52c193b1bad3d5c52575b9f77",
"afterBackup": "/home/bgs/.local/state/bgs-policy-backups/achievements-namespace-after-2026-11-13T23-29-32-625Z.json",
"afterSha256": "461b446e7fd979291fbdf9ec0879be271e2cc1945afe52717dd26914e4da13ac",
"readback": "exact match",
"uploadsResumed": false
},
"verificationAt": "2026-11-14T00:28:08.665647+00:00",
"sourceCommit": "d0bd5825a453c8510c67e8f98e87eb74ad36b3b3",
"independentReview": {
"head": "d0bd5825a453c8510c67e8f98e87eb74ad36b3b3",
"base": "d60485024f4d606f0a6142d2c7b0824d981a966c",
"result": "approved by coordinator; no blockers"
},
"engineUpload": {
"at": "2026-11-14T00:27:30.277792+00:00",
"status": 200,
"engine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.8",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/cc8dec51ea635414/gaia-project-engine-4.17.8.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"tarballSha256": "cc8dec51ea635414073849e8255da1f806db93105374b74f6166f02ed75b1d86",
"size": 914763
},
"previousEngine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.7",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/f45d3c9fc13be792/gaia-project-engine-4.17.7.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"viewerUnchanged": true,
"activation": {
"activeKey": "gaia-project_3_gaia-project-engine_4.17.8_316fe368a2f0502f",
"engine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.8",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/cc8dec51ea635414/gaia-project-engine-4.17.8.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"achievementsProbed": true,
"publicManifestMatchesReviewedCatalog": true,
"revision": 3,
"definitions": 36,
"assetReferences": 22,
"uniqueAssetKeys": 20,
"allAssetsAnonymousHashReverified": true,
"publicTarballHashMatches": true,
"albumUrl": "https://boardgamers.space/badges/games/gaia-project",
"albumHttpStatus": 200,
"viewerUnchanged": true,
"fabricatedGamesOrAwards": false,
"browserAlbum": {
"httpStatus": 200,
"loadedAchievementImages": 22,
"uniqueImages": 20,
"uncaughtErrors": 0,
"interception": false
}
}
}

View file

@ -0,0 +1,85 @@
{
"game": "gaia-project",
"gameinfoVersion": 3,
"engineVersion": "4.17.9",
"manifestRevision": 4,
"status": "active",
"sourceCommit": "58ff3f1cd5ff579bb071d5b43aad17c7d9c80a5d",
"independentReview": "Coordinator approved exact source and tarball; 25 release-gate tests and 537 archive files verified",
"tarball": {
"filename": "gaia-project-engine-4.17.9.tgz",
"sha256": "33534c7a5b0516abddfeb642bb24066e1cab5702f870dd4b185219a045b01575",
"bytes": 914886
},
"engineUpload": {
"at": "2026-11-14T01:08:04.760526+00:00",
"engine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.9",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/33534c7a5b0516ab/gaia-project-engine-4.17.9.tgz"
},
"entryPoint": "dist/wrapper.js"
}
},
"previousEngine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.8",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/cc8dec51ea635414/gaia-project-engine-4.17.8.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"checks": {
"enginePassed": 1000,
"enginePending": 4,
"engineLintErrors": 0,
"engineLintWarnings": 247,
"viewerPassed": 1171,
"viewerFiles": 100,
"viewerInitialRun": "One unchanged sandbox queued-moves test timed out at 15 seconds; full retry passed without settings or code changes",
"engineBuild": "passed",
"viewerBuild": "passed; not published",
"viewerLint": "passed",
"prettier": "passed",
"frozenInstall": "passed",
"officialProtocolValidators": "passed; other 34 definitions unchanged",
"browserSmoke": "passed; no uncaught errors; historical fixture resources HTTP410"
},
"assetsUploaded": false,
"viewerPublished": false,
"migrationOrBackfill": false,
"activeEngineVersion": "4.17.9",
"verifiedAt": "2026-11-14T01:08:41.825402+00:00",
"activation": {
"activeKey": "gaia-project_3_gaia-project-engine_4.17.9_52314dfb49944e25",
"engine": {
"package": {
"name": "@gaia-project/engine",
"version": "4.17.9",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/engine/33534c7a5b0516ab/gaia-project-engine-4.17.9.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"revision": 4,
"definitions": 36,
"fourFormationDescriptionsVerified": true,
"oldGeneralIdAbsent": true,
"other34DefinitionsUnchanged": true,
"assetReferences": 22,
"uniqueAssetKeys": 20,
"artworkMetadataAndAnonymousHashesUnchanged": true,
"publicManifestMatchesReviewedCatalog": true,
"publicTarballHashMatches": true,
"viewerUnchanged": true,
"albumUrl": "https://boardgamers.space/badges/games/gaia-project",
"browserAlbum": {
"httpStatus": 200,
"achievementCount": 36,
"loadedImages": 22,
"uniqueImages": 20,
"uncaughtErrors": 0,
"interception": false
}
}
}

View file

@ -0,0 +1,594 @@
{
"game": "gaia-project",
"gameinfoVersion": 3,
"engineVersion": "4.17.7",
"enginePublished": false,
"description": "Saved-analysis controls follow host-selected decision seats; replay remains read-only. Engine runtime unchanged.",
"lockfile": "Offline lockfile-only install completed with no lockfile changes required.",
"checks": {
"viewer": {
"files": 99,
"passed": 1162,
"gameSpecPassed": 135,
"nodeOptions": "--max-old-space-size=16384",
"maxWorkers": 1
},
"engine": {
"passed": 982,
"pending": 4
},
"alternate": {
"files": 3,
"passed": 42
},
"lint": "Engine and full viewer ESLint passed; changed-file Prettier passed.",
"locales": "Passed",
"build": "Engine, viewer and alternate builds passed",
"browser": "Built primary and alternate: manual charge click, following seat, no autoplay and replay denial passed.",
"assets": "All 72 deployed files fetched and SHA-256 matched local build before activation.",
"live": [
{
"game": "Romulans-forever",
"alternate": false,
"errors": [],
"bad": []
},
{
"game": "Romulans-forever",
"alternate": true,
"errors": [],
"bad": []
},
{
"game": "Devious-basket-7886",
"alternate": false,
"errors": [],
"bad": []
},
{
"game": "Devious-basket-7886",
"alternate": true,
"errors": [],
"bad": []
},
{
"game": "Wicked-banana-8201",
"alternate": false,
"errors": [],
"bad": []
},
{
"game": "Wicked-banana-8201",
"alternate": true,
"errors": [],
"bad": []
}
]
},
"bundles": [
{
"viewer": "primary",
"version": "5.22.34",
"bundle": "split-e667cd1d4d2770165f65",
"activated": true,
"previousUrl": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-39be4b49828ee8dd6232/viewer.umd.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/viewer.umd.js",
"files": [
{
"name": "ambas.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/ambas.jpg",
"bytes": 26115,
"storedBytes": 26115,
"sha256": "75ee8098fb6b76445d4a580a47a24a3fd444575d23124dbf0e4cf2957b553fed"
},
{
"name": "baltaks.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/baltaks.jpg",
"bytes": 28696,
"storedBytes": 28696,
"sha256": "84e74163497a5b90b9dde76d72ff2e130fa31b88f46486400090d0577ebde68e"
},
{
"name": "bescods.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/bescods.jpg",
"bytes": 27005,
"storedBytes": 27005,
"sha256": "aac494b6ca9ae7e1acc18fdfa69241f07b6a111296c8973746b8c2c5e2467c6a"
},
{
"name": "da.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/da.json",
"bytes": 339819,
"storedBytes": 100428,
"sha256": "7f785f9c29e389d2274208f274f708db510f7b683afe34810b3acb55e3e200b5"
},
{
"name": "darkanians.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/darkanians.jpg",
"bytes": 47576,
"storedBytes": 47576,
"sha256": "312687adedc5faf74b61ea8f608bd6f505c1ac9a836ae537fb15dd87da77d81b"
},
{
"name": "de.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/de.json",
"bytes": 354242,
"storedBytes": 106512,
"sha256": "9223e4f9dc17d7add42cf8e310fd5f0dee022ee4288ad54cc1d9cdec5b98c6c6"
},
{
"name": "el.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/el.json",
"bytes": 493644,
"storedBytes": 126408,
"sha256": "3e7ffe0fa911b260cc2134b6e32e49a8b7bb873e445f5dfdbab546562e5ae2bd"
},
{
"name": "fa.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/fa.json",
"bytes": 403846,
"storedBytes": 102582,
"sha256": "87376353a07edecc42346215015a9e09b74cde71e23c3f3387baf8c3902c1480"
},
{
"name": "firaks.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/firaks.jpg",
"bytes": 24068,
"storedBytes": 24068,
"sha256": "d6a04fc4fe9b2426cf4c04e26974f32c6dff7b70503e7a05bc4672b2da8a9ca8"
},
{
"name": "fr.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/fr.json",
"bytes": 361267,
"storedBytes": 104952,
"sha256": "006f843e5830e798ed7e976f0998e7fd18bb1dd5bfe4bda191075793e80216ee"
},
{
"name": "geodens.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/geodens.jpg",
"bytes": 28467,
"storedBytes": 28467,
"sha256": "915067d842c34e3ed8907011391935e196464681af36647a0be3eec7f2ba3a6e"
},
{
"name": "gleens.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/gleens.jpg",
"bytes": 27278,
"storedBytes": 27278,
"sha256": "0fcaa4fc1e6948bebdc8b7094faa5b97f14381d1c18e5ad5bf39cc212f28539b"
},
{
"name": "hadsch-hallas.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/hadsch-hallas.jpg",
"bytes": 26792,
"storedBytes": 26792,
"sha256": "a802d0425503db30a660905aaf9378b1caf8731c9d259664e5fa0cba7b50f950"
},
{
"name": "hi.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/hi.json",
"bytes": 535423,
"storedBytes": 120531,
"sha256": "27b7faefa6d4b2d9ec39c647d59d9bd72bdad6adc47746718e156df4cc5dfe67"
},
{
"name": "it.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/it.json",
"bytes": 355974,
"storedBytes": 103582,
"sha256": "fbd3fba7994ac83f79d9419ec92c02b36b5f50a8a23b61e5df09b2ce0b4f9063"
},
{
"name": "itars.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/itars.jpg",
"bytes": 23773,
"storedBytes": 23773,
"sha256": "a83f4affbebdecbdbadf06d38bbea1e06db0f2bc1a635ba9b7bb9b61ea13f2cc"
},
{
"name": "ivits.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/ivits.jpg",
"bytes": 27341,
"storedBytes": 27341,
"sha256": "e0307d8944befe8f991f685834d9d02a5ff89f472793be8a018552e819aeaec9"
},
{
"name": "ko.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/ko.json",
"bytes": 360277,
"storedBytes": 108537,
"sha256": "397771549445cd9dc06b2644b20211aea8c713a983b09ecad5195fed4b98225e"
},
{
"name": "lantids.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/lantids.jpg",
"bytes": 25870,
"storedBytes": 25870,
"sha256": "2332ee2596e6a6ecdfac00c9a3f4bfc7186d57ac1bd319d11ccae9c7f0d8e811"
},
{
"name": "mowyeds.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/mowyeds.jpg",
"bytes": 47770,
"storedBytes": 47770,
"sha256": "9ee2bf809ab77a6362b148bdf865c82c7ca67854570222316ac28765959dcdaf"
},
{
"name": "nevlas.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/nevlas.jpg",
"bytes": 24569,
"storedBytes": 24569,
"sha256": "e5c464d4e423ae252984f7224fa48063d3966331169c9defb411f719d96d9ccf"
},
{
"name": "nl.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/nl.json",
"bytes": 344159,
"storedBytes": 101866,
"sha256": "b575a9ca7e937854a78fd9700d614618f9fc6492f35634356217d323b0ae33fe"
},
{
"name": "pl.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/pl.json",
"bytes": 350308,
"storedBytes": 108183,
"sha256": "884e74ef2ddf20428b06e8264dd0e0e4b684a9eb2d5cc756119e81f41686513e"
},
{
"name": "pt-BR.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/pt-BR.json",
"bytes": 355551,
"storedBytes": 103725,
"sha256": "a3134d082b43955f18ceffeb16f3c71bc0d705ac0528eb66b0e12e19c321d5fd"
},
{
"name": "ro.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/ro.json",
"bytes": 359765,
"storedBytes": 105650,
"sha256": "4ac2a49e3a4a2689f1c603c2bcb1c5f0d8762d0b301694382881fba26c56ca36"
},
{
"name": "ru.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/ru.json",
"bytes": 467822,
"storedBytes": 122866,
"sha256": "badf546f81397ff998366433e43a0f6b471198dfcc37508840c662a5fea6e38c"
},
{
"name": "space-giants.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/space-giants.jpg",
"bytes": 47318,
"storedBytes": 47318,
"sha256": "fd232a4a41658f4545fc90dd991db496bc8e028b10d914935615b869d20cc64a"
},
{
"name": "taklons.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/taklons.jpg",
"bytes": 25473,
"storedBytes": 25473,
"sha256": "437eeac297fe498a51542c7ce6fcb02794558df1c651204d6cc1ab2d8ae5063f"
},
{
"name": "terrans.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/terrans.jpg",
"bytes": 26968,
"storedBytes": 26968,
"sha256": "36e356e4de96a96b481244fa6d2a774ab71498d81fe2ca73df0eff2dc12614ad"
},
{
"name": "tinkeroids.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/tinkeroids.jpg",
"bytes": 46866,
"storedBytes": 46866,
"sha256": "7aa4f8725c3feb39ac68a25366185108d24fcf27b33aebb4f140eed30d108144"
},
{
"name": "vi.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/vi.json",
"bytes": 382815,
"storedBytes": 106514,
"sha256": "48fbbf7ded1767573fdd1b067c1add8da58d25373d79c19a14da687cbac41768"
},
{
"name": "viewer.css",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/viewer.css",
"bytes": 326742,
"storedBytes": 51445,
"sha256": "c415aae3924a324fc465e3c69891ddcdb6a966400d14dfcb7835568408760e71"
},
{
"name": "viewer.umd.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/viewer.umd.js",
"bytes": 1164251,
"storedBytes": 340328,
"sha256": "72e0dfafa09ed5ca9ba9495a065ea976d130c9d8967f3ef7a2d1a77db331989e"
},
{
"name": "xenos.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/xenos.jpg",
"bytes": 25907,
"storedBytes": 25907,
"sha256": "a5d61249be68a07b3109cf3d3e0238e828bd21423e106e1038bdcd235d006ce7"
},
{
"name": "zh-CN.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/zh-CN.json",
"bytes": 325683,
"storedBytes": 100743,
"sha256": "2945fbdd929230a3763c01f732571b432c92366d676c93d0b1c83fec85e4025e"
},
{
"name": "zh-TW.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer/split-e667cd1d4d2770165f65/zh-TW.json",
"bytes": 324065,
"storedBytes": 107823,
"sha256": "a5de0555d0b874947a3b0a0c4f9a514c4598748392d3e2bbcdd7df078cc139aa"
}
]
},
{
"viewer": "alternate",
"version": "1.2.34",
"bundle": "split-3394ae5060564522c841",
"activated": true,
"previousUrl": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-da22833042df278440e3/old-ui.umd.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/old-ui.umd.js",
"files": [
{
"name": "ambas.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/ambas.jpg",
"bytes": 26115,
"storedBytes": 26115,
"sha256": "75ee8098fb6b76445d4a580a47a24a3fd444575d23124dbf0e4cf2957b553fed"
},
{
"name": "baltaks.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/baltaks.jpg",
"bytes": 28696,
"storedBytes": 28696,
"sha256": "84e74163497a5b90b9dde76d72ff2e130fa31b88f46486400090d0577ebde68e"
},
{
"name": "bescods.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/bescods.jpg",
"bytes": 27005,
"storedBytes": 27005,
"sha256": "aac494b6ca9ae7e1acc18fdfa69241f07b6a111296c8973746b8c2c5e2467c6a"
},
{
"name": "da.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/da.json",
"bytes": 339819,
"storedBytes": 100428,
"sha256": "7f785f9c29e389d2274208f274f708db510f7b683afe34810b3acb55e3e200b5"
},
{
"name": "darkanians.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/darkanians.jpg",
"bytes": 47576,
"storedBytes": 47576,
"sha256": "312687adedc5faf74b61ea8f608bd6f505c1ac9a836ae537fb15dd87da77d81b"
},
{
"name": "de.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/de.json",
"bytes": 354242,
"storedBytes": 106512,
"sha256": "9223e4f9dc17d7add42cf8e310fd5f0dee022ee4288ad54cc1d9cdec5b98c6c6"
},
{
"name": "el.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/el.json",
"bytes": 493644,
"storedBytes": 126408,
"sha256": "3e7ffe0fa911b260cc2134b6e32e49a8b7bb873e445f5dfdbab546562e5ae2bd"
},
{
"name": "fa.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/fa.json",
"bytes": 403846,
"storedBytes": 102582,
"sha256": "87376353a07edecc42346215015a9e09b74cde71e23c3f3387baf8c3902c1480"
},
{
"name": "firaks.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/firaks.jpg",
"bytes": 24068,
"storedBytes": 24068,
"sha256": "d6a04fc4fe9b2426cf4c04e26974f32c6dff7b70503e7a05bc4672b2da8a9ca8"
},
{
"name": "fr.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/fr.json",
"bytes": 361267,
"storedBytes": 104952,
"sha256": "006f843e5830e798ed7e976f0998e7fd18bb1dd5bfe4bda191075793e80216ee"
},
{
"name": "geodens.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/geodens.jpg",
"bytes": 28467,
"storedBytes": 28467,
"sha256": "915067d842c34e3ed8907011391935e196464681af36647a0be3eec7f2ba3a6e"
},
{
"name": "gleens.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/gleens.jpg",
"bytes": 27278,
"storedBytes": 27278,
"sha256": "0fcaa4fc1e6948bebdc8b7094faa5b97f14381d1c18e5ad5bf39cc212f28539b"
},
{
"name": "hadsch-hallas.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/hadsch-hallas.jpg",
"bytes": 26792,
"storedBytes": 26792,
"sha256": "a802d0425503db30a660905aaf9378b1caf8731c9d259664e5fa0cba7b50f950"
},
{
"name": "hi.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/hi.json",
"bytes": 535423,
"storedBytes": 120531,
"sha256": "27b7faefa6d4b2d9ec39c647d59d9bd72bdad6adc47746718e156df4cc5dfe67"
},
{
"name": "it.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/it.json",
"bytes": 355974,
"storedBytes": 103582,
"sha256": "fbd3fba7994ac83f79d9419ec92c02b36b5f50a8a23b61e5df09b2ce0b4f9063"
},
{
"name": "itars.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/itars.jpg",
"bytes": 23773,
"storedBytes": 23773,
"sha256": "a83f4affbebdecbdbadf06d38bbea1e06db0f2bc1a635ba9b7bb9b61ea13f2cc"
},
{
"name": "ivits.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/ivits.jpg",
"bytes": 27341,
"storedBytes": 27341,
"sha256": "e0307d8944befe8f991f685834d9d02a5ff89f472793be8a018552e819aeaec9"
},
{
"name": "ko.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/ko.json",
"bytes": 360277,
"storedBytes": 108537,
"sha256": "397771549445cd9dc06b2644b20211aea8c713a983b09ecad5195fed4b98225e"
},
{
"name": "lantids.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/lantids.jpg",
"bytes": 25870,
"storedBytes": 25870,
"sha256": "2332ee2596e6a6ecdfac00c9a3f4bfc7186d57ac1bd319d11ccae9c7f0d8e811"
},
{
"name": "mowyeds.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/mowyeds.jpg",
"bytes": 47770,
"storedBytes": 47770,
"sha256": "9ee2bf809ab77a6362b148bdf865c82c7ca67854570222316ac28765959dcdaf"
},
{
"name": "nevlas.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/nevlas.jpg",
"bytes": 24569,
"storedBytes": 24569,
"sha256": "e5c464d4e423ae252984f7224fa48063d3966331169c9defb411f719d96d9ccf"
},
{
"name": "nl.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/nl.json",
"bytes": 344159,
"storedBytes": 101866,
"sha256": "b575a9ca7e937854a78fd9700d614618f9fc6492f35634356217d323b0ae33fe"
},
{
"name": "old-ui.css",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/old-ui.css",
"bytes": 327226,
"storedBytes": 51608,
"sha256": "d5bd0a95012b3463602eaf4b361d61e064d937f92d89657ef0872c181e707960"
},
{
"name": "old-ui.umd.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/old-ui.umd.js",
"bytes": 1160003,
"storedBytes": 333811,
"sha256": "9a3e2667174bc72ad56cf41f2cf0d8abc5d5ccb06faaf84636e5b80eb2f0120d"
},
{
"name": "pl.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/pl.json",
"bytes": 350308,
"storedBytes": 108183,
"sha256": "884e74ef2ddf20428b06e8264dd0e0e4b684a9eb2d5cc756119e81f41686513e"
},
{
"name": "pt-BR.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/pt-BR.json",
"bytes": 355551,
"storedBytes": 103725,
"sha256": "a3134d082b43955f18ceffeb16f3c71bc0d705ac0528eb66b0e12e19c321d5fd"
},
{
"name": "ro.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/ro.json",
"bytes": 359765,
"storedBytes": 105650,
"sha256": "4ac2a49e3a4a2689f1c603c2bcb1c5f0d8762d0b301694382881fba26c56ca36"
},
{
"name": "ru.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/ru.json",
"bytes": 467822,
"storedBytes": 122866,
"sha256": "badf546f81397ff998366433e43a0f6b471198dfcc37508840c662a5fea6e38c"
},
{
"name": "space-giants.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/space-giants.jpg",
"bytes": 47318,
"storedBytes": 47318,
"sha256": "fd232a4a41658f4545fc90dd991db496bc8e028b10d914935615b869d20cc64a"
},
{
"name": "taklons.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/taklons.jpg",
"bytes": 25473,
"storedBytes": 25473,
"sha256": "437eeac297fe498a51542c7ce6fcb02794558df1c651204d6cc1ab2d8ae5063f"
},
{
"name": "terrans.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/terrans.jpg",
"bytes": 26968,
"storedBytes": 26968,
"sha256": "36e356e4de96a96b481244fa6d2a774ab71498d81fe2ca73df0eff2dc12614ad"
},
{
"name": "tinkeroids.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/tinkeroids.jpg",
"bytes": 46866,
"storedBytes": 46866,
"sha256": "7aa4f8725c3feb39ac68a25366185108d24fcf27b33aebb4f140eed30d108144"
},
{
"name": "vi.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/vi.json",
"bytes": 382815,
"storedBytes": 106514,
"sha256": "48fbbf7ded1767573fdd1b067c1add8da58d25373d79c19a14da687cbac41768"
},
{
"name": "xenos.jpg",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/xenos.jpg",
"bytes": 25907,
"storedBytes": 25907,
"sha256": "a5d61249be68a07b3109cf3d3e0238e828bd21423e106e1038bdcd235d006ce7"
},
{
"name": "zh-CN.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/zh-CN.json",
"bytes": 325683,
"storedBytes": 100743,
"sha256": "2945fbdd929230a3763c01f732571b432c92366d676c93d0b1c83fec85e4025e"
},
{
"name": "zh-TW.json",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/gaia-project/3/viewer-alternate/split-3394ae5060564522c841/zh-TW.json",
"bytes": 324065,
"storedBytes": 107823,
"sha256": "a5de0555d0b874947a3b0a0c4f9a514c4598748392d3e2bbcdd7df078cc139aa"
}
]
}
]
}

13
docs/viewer-publishing.md Normal file
View file

@ -0,0 +1,13 @@
# Publishing the viewer
Upload the complete `viewer/dist/package` folder: entry JS, CSS, language JSON and faction JPG files. Repeat for `old-ui/dist/package` with `--alternate`.
All files in a release must share one BGS `bundle` directory, with their relative paths preserved. Upload everything before saving the new entry URL. A main-JS-only upload will break language or asset loading. Keep engines and test data out of the viewer upload.
BGS compresses JS, CSS, JSON and WASM automatically during upload. Send the original bytes; do not create `.gz` files. Keep sourcemaps local unless you deliberately want to publish them. Set `viewer.scriptBytes` to the original entry size so BGS can show download progress.
The BGS admin's **Upload folder** control handles multi-file builds. For scripted releases, use BGS's `scripts/publish-viewer.mjs` with `--dir`, `--entry` and `--style`; it verifies every uploaded file, records the previous viewer, and activates only with `--apply --activate`. The full command and API contract are in the [BGS viewer documentation](https://docs.boardgamers.space/guide/viewer-api#publishing-a-viewer-with-multiple-files).
English needs no language download; other languages load when selected. Test a cold load and a language change after publishing. Also check the browser Network panel for missing relative assets.
Keep `"chat"` in both viewers’ `integratedControls` metadata. Gaia supplies the chat button and unread badge; this prevents BGS from adding a duplicate chat shortcut.

View file

@ -2,9 +2,14 @@
Javascript engine for Gaia Project.
## Demo
## Achievements
Check out [boardgamers.space](https://www.boardgamers.space)! Reach out to us if you want to contribute.
See the [achievement hooks and revision 4 catalog](../docs/achievements.md) for the
optional BGS contract, completion requirements, award semantics, and verification scope.
## Play online at
Check out [boardgamers.space](https://boardgamers.space/boardgame/gaia-project)! Reach out to us if you want to contribute.
## Setup

331
engine/achievements.spec.ts Normal file
View file

@ -0,0 +1,331 @@
import { expect } from "chai";
import Beta2 from "./fixtures/Beta-2.json";
import { automaDifficulties } from "./src/automa";
import Engine from "./src/engine";
import { Building, Expansion, Faction, Phase, Planet, ResearchField, Round } from "./src/enums";
import { achievementDefinitions, achievements, factions, rankings, scores } from "./wrapper";
// Existing completed-game fixture for integration; mutations below are predicate boundary tests,
// not claims that the difficult feats have been demonstrated in a six-round resource budget.
function state(): Record<string, any> {
return JSON.parse(JSON.stringify(Beta2));
}
function earned(data: Record<string, any>, seat = 0): string[] {
return achievements(data).find((result) => result.seat === seat).earned;
}
const baseTypes = [
Planet.Terra,
Planet.Desert,
Planet.Swamp,
Planet.Oxide,
Planet.Volcanic,
Planet.Titanium,
Planet.Ice,
Planet.Gaia,
Planet.Lost,
];
function colonies(data: Record<string, any>, types: Planet[]) {
for (const hex of data.map) {
delete hex.data.player;
delete hex.data.building;
delete hex.data.additionalMine;
}
types.forEach((planet, index) => {
Object.assign(data.map[index].data, { planet, player: 0, building: Building.Mine });
});
}
function solo(difficulty = "automa"): Record<string, any> {
const data = state();
data.players = data.players.slice(0, 2);
data.players[1].isAutoma = true;
data.automa = { difficulty, round: 6, remaining: 0, discard: [], boosters: [], lastActions: [] };
// Keep a valid map after removing the other two fixture seats.
for (const hex of data.map) {
if (hex.data.player > 1) {
delete hex.data.player;
delete hex.data.building;
}
}
return data;
}
describe("BGS achievement hooks", () => {
it("exports a complete, unique, isolated revision-5 catalog", () => {
const manifest = achievementDefinitions();
const ids = manifest.achievements.map((definition) => definition.id);
expect(manifest.revision).to.equal(5);
expect(ids).to.include("federation-form-4");
expect(ids).not.to.include("federation-form-3");
expect(ids).to.include("faction-ivits-growing-federation");
expect(ids).to.have.length(36);
expect(new Set(ids).size).to.equal(ids.length);
// BGS packages/protocol/achievements.ts: achievementIdSchema.
for (const id of ids) expect(id).to.match(/^[a-z0-9][a-z0-9-]{0,63}$/);
for (const faction of Faction.values(Expansion.All)) expect(ids).to.include(`win-faction-${faction}`);
for (const difficulty of automaDifficulties) expect(ids).to.include(`win-automa-${difficulty}`);
expect(manifest.achievements.every((definition) => definition.name && definition.description)).to.equal(true);
manifest.achievements[0].name = "mutated";
expect(achievementDefinitions().achievements[0].name).not.to.equal("mutated");
});
it("references all 34 assets, preserving 18 faction and two shared score keys", () => {
const definitions = achievementDefinitions().achievements;
const assets = definitions.filter((definition) => definition.icon?.type === "asset");
const texts = definitions.filter((definition) => definition.icon?.type === "text");
expect(assets).to.have.length(36);
expect(texts).to.have.length(0);
const keys = assets.map((definition) => (definition.icon.type === "asset" ? definition.icon.key : ""));
expect(new Set(keys).size).to.equal(34);
for (const faction of Faction.values(Expansion.All)) {
expect(definitions.find((definition) => definition.id === `win-faction-${faction}`).icon).to.deep.equal({
type: "asset",
key: `achievement-faction-${faction}`,
});
}
for (const mode of ["base", "lost-fleet"]) {
for (const score of [150, 200]) {
expect(definitions.find((definition) => definition.id === `score-${mode}-${score}`).icon).to.deep.equal({
type: "asset",
key: `achievement-score-${score}`,
});
}
}
for (const definition of definitions) {
const icon = definition.icon;
if (icon?.type === "asset") {
expect(Object.keys(icon).sort()).to.deep.equal(["key", "type"]);
expect(icon.key).to.match(/^[a-z0-9][a-z0-9-]{0,63}$/);
} else if (icon?.type === "text") {
expect(Object.keys(icon).sort()).to.deep.equal(["text", "type"]);
expect(icon.text).to.match(/^[A-Za-z0-9]{1,4}$/);
} else {
expect(definition).not.to.have.property("icon");
expect(definition.id.startsWith("win-faction-") || definition.id.startsWith("score-")).to.equal(false);
}
}
const first = assets[0];
if (first.icon.type === "asset") first.icon.key = "mutated";
expect(
achievementDefinitions().achievements.find((definition) => definition.id === first.id).icon
).not.to.deep.equal(first.icon);
});
it("hydrates the existing completed fixture, agrees with wrapper outcomes, and is deterministic", () => {
const data = state();
const engine = Engine.fromData(state());
const result = achievements(data);
expect(result.map((entry) => entry.seat)).to.deep.equal([0, 1, 2, 3]);
expect(scores(engine)).to.deep.equal([151, 135, 213, 138]);
expect(factions(engine)[2]).to.equal(Faction.HadschHallas);
expect(result[2].outcome).to.equal("win");
expect(result[2].earned).to.include.members([
"win-faction-hadsch-hallas",
"win-mode-base",
"score-base-150",
"score-base-200",
]);
expect(result[0].outcome).to.equal("loss");
expect(result[0].earned).to.include("score-base-150");
expect(result[0].earned.some((id) => id.startsWith("win-"))).to.equal(false);
expect(achievements(engine)).to.deep.equal(result);
expect(achievements(data)).to.deep.equal(result);
const ids = new Set(achievementDefinitions().achievements.map((definition) => definition.id));
expect(result.every((entry) => entry.earned.every((id) => ids.has(id)))).to.equal(true);
});
it("does not mutate serialized legacy options or federation caches during hydration", () => {
const data = state();
const engine = Engine.fromData(state());
data.players[0].federationCache = {
federations: [{ hexes: [engine.players[0].data.occupied[0].toString()] }],
};
const before = JSON.stringify(data);
achievements(data);
expect(JSON.stringify(data)).to.equal(before);
achievements(data);
expect(JSON.stringify(data)).to.equal(before);
});
it("awards nothing before authoritative final scoring or after early cancellation", () => {
for (const phase of [Phase.RoundMove, Phase.RoundGaia]) {
const data = state();
data.phase = phase;
expect(achievements(data)).to.deep.equal([]);
}
const cancelled = state();
cancelled.round = 0;
expect(achievements(cancelled)).to.deep.equal([]);
const stopped = state();
stopped.advancedLog = stopped.advancedLog.filter((entry) => entry.phase !== Phase.EndGame);
expect(achievements(stopped)).to.deep.equal([]);
});
it("retains human-seat indexing without awarding dropped players", () => {
const data = state();
data.players[0].dropped = true;
const result = achievements(data);
expect(result[0]).to.deep.equal({ seat: 0, earned: [] });
expect(result[2].seat).to.equal(2);
expect(result[2].earned).to.include("win-faction-hadsch-hallas");
});
it("treats multiplayer tied first place as wins, not draws", () => {
const data = state();
data.players[0].data.victoryPoints = 213;
expect(achievements(data).map((entry) => entry.outcome)).to.deep.equal(["win", "loss", "win", "loss"]);
});
it("uses exact resolved Automa difficulty and excludes the bot seat, including ties and losses", () => {
for (const difficulty of automaDifficulties) {
const data = solo(difficulty);
data.players[0].data.victoryPoints = 200;
for (const botScore of [199, 200, 201]) {
data.players[1].data.victoryPoints = botScore;
const result = achievements(data);
expect(result).to.have.length(1);
expect(result[0].seat).to.equal(0);
const won = rankings(Engine.fromData(data))[0] === 1;
expect(result[0].outcome).to.equal(won ? "win" : "loss");
expect(result[0].earned.filter((id) => id.startsWith("win-automa-"))).to.deep.equal(
won ? [`win-automa-${difficulty}`] : []
);
expect(result[0].earned).to.include("score-base-200");
}
}
});
it("separates rulesets, not faction origin, and checks final-score thresholds inclusively", () => {
for (const lostFleet of [false, true]) {
const data = state();
data.options.lostFleet = lostFleet;
const mode = lostFleet ? "lost-fleet" : "base";
for (const score of [149, 150, 199, 200]) {
data.players[0].data.victoryPoints = score;
const ids = earned(data);
expect(ids.includes(`score-${mode}-150`)).to.equal(score >= 150);
expect(ids.includes(`score-${mode}-200`)).to.equal(score >= 200);
expect(ids.some((id) => id.startsWith(`score-${lostFleet ? "base" : "lost-fleet"}-`))).to.equal(false);
}
expect(earned(data, 2)).to.include(`win-mode-${mode}`);
}
});
it("supports every faction win, including the four expansion factions", () => {
for (const faction of Faction.values(Expansion.All)) {
const data = state();
data.options.lostFleet = true;
data.players[2].faction = faction;
delete data.players[2].variant;
expect(earned(data, 2)).to.include(`win-faction-${faction}`);
}
});
it("requires every standard piece currently deployed, not virtual or returned mines", () => {
const data = state();
const buildings = {
[Building.Mine]: 8,
[Building.TradingStation]: 4,
[Building.ResearchLab]: 3,
[Building.PlanetaryInstitute]: 1,
[Building.Academy1]: 1,
[Building.Academy2]: 1,
};
Object.assign(data.players[0].data.buildings, buildings);
expect(earned(data)).to.include("build-all-standard");
for (const building of Object.keys(buildings)) {
data.players[0].data.buildings[building]--;
data.players[0].data.lostPlanet = 1;
data.players[0].data.artifactPlanetTypes = [Planet.Asteroid, Planet.Protoplanet];
expect(earned(data)).not.to.include("build-all-standard");
data.players[0].data.buildings[building]++;
}
});
it("requires four actual formations, not token rewards or rescores, for both federation feats", () => {
for (const faction of [Faction.Terrans, Faction.Ivits]) {
const data = state();
data.players[0].faction = faction;
delete data.players[0].variant;
data.players[0].data.federationCount = 3;
data.players[0].data.tiles.federations = Array(5).fill({ tile: "fed1", green: true });
data.players[0].data.spaceshipFederations = [{ tile: "unused", green: true }];
expect(earned(data)).not.to.include("federation-form-4");
expect(earned(data)).not.to.include("faction-ivits-growing-federation");
data.players[0].data.tiles.federations = [];
data.players[0].data.spaceshipFederations = [];
for (const count of [4, 5]) {
data.players[0].data.federationCount = count;
const ids = earned(data);
expect(ids).to.include("federation-form-4");
expect(ids.includes("faction-ivits-growing-federation")).to.equal(faction === Faction.Ivits);
expect(ids).not.to.include("federation-form-3");
}
}
});
it("requires all nine physical base types including Lost, but never Transdim", () => {
const data = state();
colonies(data, baseTypes);
expect(earned(data)).to.include("explore-all-types-base");
for (let index = 0; index < baseTypes.length; index++) {
const hex = data.map[index];
hex.data.planet = Planet.Transdim;
expect(earned(data)).not.to.include("explore-all-types-base");
hex.data.planet = baseTypes[index];
}
data.map[7].data.building = Building.GaiaFormer;
expect(earned(data)).not.to.include("explore-all-types-base");
});
it("requires physical asteroid and protoplanet colonies in Lost Fleet, not artifact types", () => {
const data = state();
data.options.lostFleet = true;
colonies(data, baseTypes);
data.players[0].data.artifactPlanetTypes = [Planet.Asteroid, Planet.Protoplanet];
expect(earned(data)).not.to.include("explore-all-types-lost-fleet");
colonies(data, [...baseTypes, Planet.Asteroid, Planet.Protoplanet]);
expect(earned(data)).to.include("explore-all-types-lost-fleet");
expect(earned(data)).not.to.include("explore-all-types-base");
});
it("counts Lantids shared mines separately from main-owned planet types", () => {
const data = state();
data.players[0].faction = Faction.Lantids;
delete data.players[0].variant;
colonies(data, baseTypes);
for (let index = 0; index < 6; index++) {
Object.assign(data.map[index].data, { player: 1, additionalMine: 0 });
}
expect(earned(data)).to.include("faction-lantids-shared-civilization");
expect(earned(data)).not.to.include("explore-all-types-base");
delete data.map[5].data.additionalMine;
expect(earned(data)).not.to.include("faction-lantids-shared-civilization");
});
it("requires Bescods and all six research tracks at level three or above", () => {
const data = state();
for (const field of ResearchField.values(Expansion.All)) data.players[0].data.research[field] = 3;
expect(earned(data)).not.to.include("faction-bescods-balanced-research");
data.players[0].faction = Faction.Bescods;
delete data.players[0].variant;
expect(earned(data)).to.include("faction-bescods-balanced-research");
for (const field of ResearchField.values(Expansion.All)) {
data.players[0].data.research[field] = 2;
expect(earned(data)).not.to.include("faction-bescods-balanced-research");
data.players[0].data.research[field] = 4;
}
});
it("can evaluate the fixture replay after the actual final-scoring transition", () => {
const engine = Engine.fromData(state()).replayedTo();
expect(engine.phase).to.equal(Phase.EndGame);
expect(engine.round).to.equal(Round.LastRound);
expect(achievements(engine)).to.deep.equal(achievements(JSON.parse(JSON.stringify(engine))));
expect(achievements(engine).filter((result) => result.outcome === "win")).to.have.length.greaterThan(0);
});
});

View file

@ -0,0 +1,93 @@
import { expect } from "chai";
import PilingSong from "./fixtures/Piling-song-3477.data.json";
import WavelyTriangle from "./fixtures/Wavely-triangle-5324.data.json";
import Engine from "./src/engine";
import { isOutclassedBy } from "./src/federation";
import { currentPlayer, logSlice, move, scores } from "./wrapper";
/**
* Regression tests for the federation-enumeration performance issue that got two
* production games stuck: engine.move() took >10s (the platform kills engine calls
* at 10s) because Player.availableFederations exploded combinatorially on late-game
* states with many building groups.
*
* The fixtures are the actual production game states. Before the optimization, the
* moves below took ~5s and ~3.5s on a fast dev machine (and >10s in production);
* they now take well under a second, so the generous bounds here should only trip
* on a real complexity regression, not on slow CI hardware.
*/
describe("federation computation performance", function () {
this.timeout(30000);
const MAX_MS = 5000;
it("Wavely-triangle-5324: 'xenos action qic3.' completes quickly", () => {
const engine = Engine.fromData(JSON.parse(JSON.stringify(WavelyTriangle)));
const historyLength = engine.moveHistory.length;
const start = Date.now();
const result = move(engine, "xenos action qic3.", 1);
const elapsed = Date.now() - start;
expect(result.moveHistory.length).to.be.greaterThan(historyLength);
expect(result.moveHistory[historyLength]).to.match(/^xenos action qic3\./);
expect(elapsed).to.be.lessThan(MAX_MS);
// The follow-up entry points the platform calls on the result also complete
expect(currentPlayer(result)).to.be.a("number");
expect(scores(result)).to.have.length(4);
expect(logSlice(result, { start: historyLength }).log).to.have.length(1);
});
it("Piling-song-3477: baltaks' federation move completes quickly", () => {
// The failing move is at index 203 of the fixture's move history: load the state
// right before it, then apply it as a live move (which triggers the expensive
// legality checks and the next player's federation computation)
const engine = Engine.fromData(JSON.parse(JSON.stringify(PilingSong))).replayedTo(203, false);
const historyLength = engine.moveHistory.length;
const start = Date.now();
const result = move(
engine,
"baltaks federation 10A10,10A3,10A4,10A9,10B0,10B1,10B2,10B3,10B4 fed6 using area1: 3.",
0
);
const elapsed = Date.now() - start;
expect(result.moveHistory.length).to.be.greaterThan(historyLength);
// Same power-token accounting as when the move was accepted in production
expect(result.moveHistory[historyLength]).to.equal(
"baltaks federation 10A10,10A3,10A4,10A9,10B0,10B1,10B2,10B3,10B4 fed6 using area1: 3. (6/1/0/0 ⇒ 3/1/0/0)"
);
expect(elapsed).to.be.lessThan(MAX_MS);
expect(currentPlayer(result)).to.be.a("number");
expect(scores(result)).to.have.length(3);
expect(logSlice(result, { start: historyLength }).log).to.have.length(1);
});
it("Piling-song-3477: availableFederations returns only rules-legal federations", () => {
const engine = Engine.fromData(JSON.parse(JSON.stringify(PilingSong))).replayedTo(203, false);
for (const player of engine.players) {
player.federationCache = null;
const feds = player.availableFederations(engine.map, engine.options.flexibleFederations);
for (const fed of feds) {
expect(fed.powerValue).to.be.at.least(player.federationCost);
expect(fed.newSatellites).to.be.at.most(player.maxSatellites);
// The hexes of a federation must form a single connected group
expect(engine.map.grid.groups(fed.hexes)).to.have.length(1);
}
// No returned federation may be outclassed by another one
for (const fed of feds) {
for (const other of feds) {
if (fed !== other) {
expect(isOutclassedBy(fed, other), "federation should not be outclassed").to.be.false;
}
}
}
}
});
});

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,17 +1,39 @@
import { finalRankings, gainFinalScoringVictoryPoints } from "./src/algorithms/scoring";
import { stdBuildingValue } from "./src/buildings";
import Engine from "./src/engine";
import Event, { EventSource } from "./src/events";
import Event from "./src/events";
import SpaceMap, { parseLocation } from "./src/map";
import Player, { BuildWarning, MAX_SATELLITES } from "./src/player";
import PlayerData, { BrainstoneDest, MaxLeech, Power } from "./src/player-data";
import PlayerData, { effectiveRange, Power } from "./src/player-data";
import Reward from "./src/reward";
export { boardActions, FreeAction, freeActionConversions, ResourceConversion } from "./src/actions";
export { boardActions, FreeAction, freeActionConversions } from "./src/actions";
export type { ResourceConversion } from "./src/actions";
export {
defaultPreferenceSplitBudget,
isValidPreferenceSplitBudget,
MAX_PREFERENCE_SPLIT_BUDGET,
MIN_PREFERENCE_SPLIT_BUDGET,
MIN_PREFERENCE_SPLIT_PLAYERS,
PREFERENCE_SPLIT_BUDGET_PER_PLAYER,
preferenceSplitBidError,
resolvePreferenceSplitAuction,
roundVictoryPoints,
} from "./src/algorithms/preference-split-auction";
export type {
PreferenceSplitAllocation,
PreferenceSplitBid,
PreferenceSplitFactionSummary,
PreferenceSplitResult,
} from "./src/algorithms/preference-split-auction";
export { MAX_SILENT_BID, resolveSilentAuction, silentAuctionBidError } from "./src/algorithms/silent-auction";
export type { SilentAuctionBid, SilentAuctionResult, SilentAuctionStep } from "./src/algorithms/silent-auction";
export { conversionToFreeAction } from "./src/available/actions";
export { canResearchField, canTakeAdvancedTechTile } from "./src/available/research";
export { shipsInHex } from "./src/available/ships";
export {
// BrainstoneWarning is an enum (runtime value); everything else in this block is type-only, so
// it must re-export via `export type` for per-file ESM transformers (vite dev / rolldown).
export { BrainstoneWarning } from "./src/available/types";
export type {
AvailableBoardAction,
AvailableBoardActionData,
AvailableBuilding,
@ -20,25 +42,17 @@ export {
AvailableFreeAction,
AvailableFreeActionData,
AvailableHex,
AvailableMoveShipData,
AvailableResearchData,
AvailableResearchTrack,
BrainstoneActionData,
BrainstoneWarning,
ChooseTechTile,
ShipAction,
} from "./src/available/types";
export {
AuctionVariant,
EngineOptions,
FactionCustomization,
FactionVariant,
LogEntry,
LogEntryChanges,
} from "./src/engine";
export { AuctionVariant } from "./src/engine";
export type { EngineOptions, FactionCustomization, FactionVariant, LogEntry, LogEntryChanges } from "./src/engine";
export {
AdvTechTile,
AdvTechTilePos,
ArtifactToken,
BoardAction,
Booster,
Building,
@ -48,7 +62,7 @@ export {
Faction,
Federation,
FinalTile,
isShip,
hasExpansion,
Operator,
Phase,
Planet,
@ -58,7 +72,11 @@ export {
Resource,
Round,
RoundScoring,
ScoringBoardExtensionSide,
ScoringTile,
Spaceship,
SpaceshipFederation,
SpaceshipTechTile,
SubPhase,
TechPos,
TechTile,
@ -66,30 +84,42 @@ export {
} from "./src/enums";
export { FactionBoard, factionBoard, factionVariantBoard } from "./src/faction-boards";
export { factionPlanet } from "./src/factions";
export { federationCost, FederationInfo, parseFederationLocation } from "./src/federation";
export { GaiaHex, GaiaHexData } from "./src/gaia-hex";
export { federationCost, parseFederationLocation } from "./src/federation";
export type { FederationInfo } from "./src/federation";
export { GaiaHex } from "./src/gaia-hex";
export type { GaiaHexData } from "./src/gaia-hex";
export { applyChargePowers } from "./src/income";
export { leechPossible } from "./src/move/phase";
export { classifySectorId, LostFleetSectorType } from "./src/lost-fleet-map";
export { moveAI } from "./src/move/ai";
export { ANALYSIS_CHEAP_BUILD } from "./src/move/buildings";
export { advanceSetupTurn, endSetupFactionPhase, leechPossible } from "./src/move/phase";
export { planetNames, terraformingStepsRequired } from "./src/planets";
export { lastTile, researchEvents } from "./src/research-tracks";
export { AvailableSetupOption, SetupType } from "./src/setup";
export { SetupType } from "./src/setup";
export type { AvailableSetupOption } from "./src/setup";
export { artifactSlotCount, shipsInPlay, spaceshipBoards } from "./src/spaceships";
export { artifactTokenRewards, artifactTokenSpec } from "./src/tiles/artifacts";
export { finalScorings } from "./src/tiles/scoring";
// Type re-exports must be `export type` for per-file ESM transformers (vite dev / rolldown):
// a plain re-export of a type-only binding becomes a runtime import of a non-existent export.
export type { EventSource } from "./src/events";
export type { BrainstoneDest, MaxLeech } from "./src/player-data";
export {
BrainstoneDest,
MaxLeech,
BuildWarning,
effectiveRange,
Event,
finalRankings,
gainFinalScoringVictoryPoints,
MAX_SATELLITES,
parseLocation,
Player,
PlayerData,
Event,
Power,
Reward,
SpaceMap,
EventSource,
gainFinalScoringVictoryPoints,
finalRankings,
parseLocation,
stdBuildingValue,
Power,
MAX_SATELLITES,
};
export default Engine;
export { capturePremovePower } from "./src/premove-power";

View file

@ -1,11 +1,11 @@
{
"name": "@gaia-project/engine",
"version": "4.8.51",
"version": "4.17.12",
"description": "Javascript engine for project gaia",
"main": "dist/index.js",
"types": "index.ts",
"source": "index.ts",
"repository": "git@github.com:boardgamers-mono/gaia-project.git",
"repository": "git@github.com:boardgamers/gaia-project.git",
"publishConfig": {
"access": "public"
},
@ -22,10 +22,11 @@
"scripts": {
"prepublishOnly": "npm run test && npm run clean && tsc",
"build": "npm run clean && tsc",
"clean": "rm -Rf dist",
"clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
"lint": "eslint . --ext .ts",
"test": "mocha -r ts-node/register src/**/*.spec.ts src/*.spec.ts *.spec.ts",
"test-single": "mocha -r ts-node/register"
"test-single": "mocha -r ts-node/register",
"fuzz": "node -r ts-node/register src/fuzz/run.ts"
},
"contributors": [
"coyotte508 <coyotte508@gmail.com>",
@ -33,23 +34,23 @@
],
"license": "MIT",
"dependencies": {
"@boardgamers/protocol": "0.11.0",
"eventemitter3": "^3.1.0",
"hexagrid": "^2.1.1",
"lodash": "^4.17.15",
"seedrandom": "2.4.3",
"semver-compare": "1.0.0",
"shuffle-seed": "1.1.6"
"semver-compare": "1.0.0"
},
"devDependencies": {
"@types/chai": "^4.1.2",
"@types/lodash": "^4.14.149",
"@types/lodash": "4.14.182",
"@types/mocha": "^2.2.48",
"@types/node": "^14.0.14",
"@types/seedrandom": "^2.4.27",
"@types/semver-compare": "^1.0.1",
"@types/shuffle-seed": "^1.1.0",
"@typescript-eslint/eslint-plugin": "^2.31.0",
"@typescript-eslint/parser": "^2.31.0",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"chai": "^4.1.2",
"eslint": "^6.8.0",
"eslint-plugin-import": "^2.20.2",
@ -57,7 +58,8 @@
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"mocha": "^5.2.0",
"shuffle-seed": "1.1.6",
"ts-node": "^5.0.1",
"typescript": "^3.8.3"
"typescript": "^4.9.5"
}
}

3647
engine/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,372 @@
import { expect } from "chai";
import Engine from "./src/engine";
import {
AdvTechTile,
AdvTechTilePos,
Building,
Faction,
Federation,
Phase,
Planet,
Player as PlayerEnum,
ResearchField,
Spaceship,
} from "./src/enums";
import { GaiaHex } from "./src/gaia-hex";
import { Power } from "./src/player-data";
import { capturePremovePower } from "./src/premove-power";
import { automation, playNextPremove } from "./src/premoves";
const parseMoves = Engine.parseMoves;
function createRoundMoveEngine(nbPlayers: number, factions: Faction[]): Engine {
const engine = new Engine([`init ${nbPlayers} lost-fleet-race-conditions`], { lostFleet: true });
engine.players.forEach((pl, index) => {
pl.faction = factions[index];
pl.loadFaction(null, engine.expansions);
pl.data.victoryPoints = 30;
pl.data.qics = 10;
pl.data.credits = 20;
pl.data.knowledge = 10;
pl.data.ores = 10;
pl.data.power = new Power(4, 4, 4, 0);
});
engine.phase = Phase.RoundMove;
engine.round = 1;
engine.turnOrder = engine.players.map((pl) => pl.player);
engine.currentPlayer = PlayerEnum.Player1;
return engine;
}
function occupyPlanetsOfDistinctTypes(engine: Engine, player: PlayerEnum, count: number): GaiaHex[] {
const pl = engine.player(player);
const seenTypes = new Set<Planet>();
const hexes: GaiaHex[] = [];
for (const hex of engine.map.grid.values()) {
if (hexes.length >= count) {
break;
}
if (!hex.hasPlanet() || hex.data.spaceship !== undefined || hex.occupied() || seenTypes.has(hex.data.planet)) {
continue;
}
seenTypes.add(hex.data.planet);
hexes.push(hex);
}
for (const hex of hexes) {
hex.data.player = player;
hex.data.building = Building.Mine;
pl.data.occupied.push(hex);
}
pl.data.buildings[Building.Mine] = pl.data.occupied.length;
return hexes;
}
// PROGRESS.md #69's race-condition audit read the source and concluded every one of these "board
// state changed between premove queue-time and execution-time" scenarios is already safe (premove
// resolution replays fresh state, calls generateAvailableCommands(), then .move() throws on
// anything no longer legal - resolvePremoveQueue turns that throw into a clean "failed" outcome,
// never a partial commit). These tests pin that conclusion so a future refactor can't silently
// reopen one. Each constructs (via the REAL engine, not a fake) a state where a move was legal at
// queue-time, then mutates the SAME contested resource/hex the way a genuine opposing action would
// (token taken, research slot filled, hex occupied), and asserts resolvePremoveQueue fails cleanly
// rather than committing a now-illegal move or throwing an unhandled exception itself.
//
// The audit named 8 scenarios; this file covers 6 directly (federation token, research-track cap,
// advanced tech tile, Ivits Space Station vs Lost Planet, a contested build - the same canOccupy
// gate the Asteroid free-mine variant also relies on, and Gaiaforming contention). Two are
// deliberately not included, for reasons worth recording rather than silently dropping:
// - Explore-target contention: every Lost Fleet ship has exactly 4 exploration slots
// (EXPLORATION_CHARGE_TRACK, spaceships.ts) while the engine caps at 4 players, so a genuine
// CROSS-PLAYER exhaustion race can't actually happen - nextFreeExplorationSlot always has room
// for a 4th distinct player. The only real "contention" is intra-player (already covered by
// exploration.spec.ts's own shuttle-limit tests), not a premove-specific race.
// - Federation formation vs. Lost Planet placement (federationCache invalidation): the queue-time-
// legal-move race is already covered by the federation-token-exhaustion test above via the same
// moveFormFederation failure path; the narrower cache-staleness question (does a Lost Planet
// placed by another player between queue-time and execution-time correctly invalidate a
// federation-eligibility CACHE specifically, as opposed to just making the move illegal outright)
// would need a purpose-built fixture isolating that cache and wasn't reached this session.
function resolvePremoveQueue(clone: () => Engine, seat: number, rows: { seq: number; move: string }[], _mode: string) {
const engine = clone();
automation(engine).plans[seat] = { moves: rows.map((row) => row.move), round: engine.round, revision: 1 };
const played = playNextPremove(engine);
return { outcome: played ? "success" : "failed", reason: engine.automation.plans[seat].notice?.text };
}
function cloneEngineLike(engine: Engine): Engine {
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
}
describe("Premove race-condition regressions (#69 audit)", () => {
it("federation token exhaustion: a queued federation move fails cleanly once the last token of that type is gone", () => {
// Verbatim setup from tiles/federations.spec.ts's own "should allow to form a federation" case -
// a real, proven-legal position for "p1 federation -1x2,-2x3,-3x2,-3x3,-3x4,-4x2 fed2".
const moves = parseMoves(`
init 2 randomSeed
p1 faction terrans
p2 faction bescods
p1 build m -1x2
p2 build m -1x-1
p2 build m 3x-2
p1 build m -4x2
p2 booster booster3
p1 booster booster7
p1 up gaia.
p2 build ts -1x-1.
p1 build gf -2x3.
p2 build m -1x0.
p1 charge 1pw
p1 build ts -1x2.
p2 charge 1pw
p2 build m 1x0.
p1 charge 2pw
p1 build m -3x4.
p2 pass booster8
p1 build PI -1x2.
p2 charge 1pw
p1 pass booster3
p1 income t
p1 spend 4tg for 1k. spend 2tg for 2c
p2 burn 3. spend 3pw for 1o. pass booster5
p1 build m -2x3. spend 2pw for 2c.
p1 build ts -4x2.
`);
const engine = new Engine(moves);
const queuedMove = "p1 federation -1x2,-2x3,-3x2,-3x3,-3x4,-4x2 fed2";
// Sanity: this move IS legal right now (proves the fixture, not just the contended clone).
expect(() => new Engine([...moves, queuedMove])).to.not.throw();
// Satellite payments are legal from any bowl, but automation must preserve the original
// bowl-I-only intent. An intervening charge must not silently sacrifice charged tokens.
for (const initiallyCharged of [false, true]) {
const planned = cloneEngineLike(engine);
planned.players[0].data.power = initiallyCharged ? new Power(0, 8, 0) : new Power(8, 0, 0);
const completeMove = queuedMove + ".";
const power = capturePremovePower(cloneEngineLike(planned), 0, completeMove);
automation(planned).plans[0] = { moves: [completeMove], power: [power], round: planned.round, revision: 1 };
planned.players[0].data.chargePower(8);
const before = JSON.stringify(planned.players[0].data);
const history = planned.moveHistory.length;
const played = playNextPremove(planned);
expect(played, planned.automation.plans[0].notice?.text).to.equal(initiallyCharged);
if (!initiallyCharged) {
expect(JSON.stringify(planned.players[0].data)).to.equal(before);
expect(planned.moveHistory.length).to.equal(history);
expect(planned.automation.plans[0].notice.text).to.contain("bowls II or III");
}
}
// Someone else claimed the last fed2 token in the meantime.
const contested = Engine.fromData(JSON.parse(JSON.stringify(engine)));
contested.tiles.federations[Federation.Fed2] = 0;
const result = resolvePremoveQueue(
() => cloneEngineLike(contested),
0,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(result.outcome).to.equal("failed");
});
it("research-track level-5 cap: a queued research move fails cleanly once another player already claimed that track's top slot", () => {
const engine = new Engine(["init 2 randomSeed"], {});
engine.players.forEach((pl, index) => {
pl.faction = index === 0 ? Faction.Terrans : Faction.Bescods;
pl.loadFaction(null, engine.expansions);
pl.data.research[ResearchField.Navigation] = 4;
pl.data.knowledge = 10;
pl.data.qics = 10;
pl.data.credits = 20;
});
// Going from level 4 to 5 needs a flipped (green) federation - player.ts's canUpgradeResearch.
engine.players[0].data.tiles.federations.push({ tile: Federation.Fed1, green: true });
engine.phase = Phase.RoundMove;
engine.round = 1;
engine.turnOrder = engine.players.map((pl) => pl.player);
engine.currentPlayer = PlayerEnum.Player1;
const queuedMove = "terrans up nav.";
// Sanity: legal right now (level 5 nav is still unclaimed by anyone) against the pristine state.
const pristineResult = resolvePremoveQueue(
() => cloneEngineLike(engine),
0,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(pristineResult.outcome).to.equal("success");
// The other player reached level 5 on the SAME track in the meantime.
const contested = Engine.fromData(JSON.parse(JSON.stringify(engine)));
contested.players[1].data.research[ResearchField.Navigation] = 5;
const result = resolvePremoveQueue(
() => cloneEngineLike(contested),
0,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(result.outcome).to.equal("failed");
});
it("advanced tech tile exhaustion: a queued tech-tile claim fails cleanly once another player already took the only copy", () => {
const engine = new Engine(["init 2 randomSeed"], { lostFleet: true });
engine.tiles.techs[AdvTechTilePos.ScoringExtension] = { tile: AdvTechTile.AdvTech1, count: 1 };
engine.players.forEach((pl, index) => {
pl.faction = index === 0 ? Faction.Terrans : Faction.Xenos;
pl.loadFaction(null, engine.expansions);
pl.data.research[ResearchField.Terraforming] = 4;
pl.data.knowledge = 10;
pl.data.qics = 10;
pl.data.credits = 20;
});
engine.phase = Phase.RoundMove;
engine.round = 1;
engine.turnOrder = engine.players.map((pl) => pl.player);
engine.currentPlayer = PlayerEnum.Player1;
const queuedMove = `terrans up terra. tech ${AdvTechTilePos.ScoringExtension}`;
// The other player already claimed the tile's only copy in the meantime.
const contested = Engine.fromData(JSON.parse(JSON.stringify(engine)));
contested.tiles.techs[AdvTechTilePos.ScoringExtension] = { tile: AdvTechTile.AdvTech1, count: 0 };
const result = resolvePremoveQueue(
() => cloneEngineLike(contested),
0,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(result.outcome).to.equal("failed");
});
it("Ivits Space Station vs Lost Planet: a queued space-station build fails cleanly once another player already placed a Lost Planet on that exact hex", () => {
const engine = new Engine(["init 2 lost-fleet-ship-hex-placements-i"], { lostFleet: true });
engine.players.forEach((pl, index) => {
pl.faction = index === 0 ? Faction.Ivits : Faction.Terrans;
pl.loadFaction(null, engine.expansions);
pl.data.qics = 10;
pl.data.credits = 20;
pl.data.knowledge = 10;
pl.data.ores = 10;
});
const start = [...engine.map.grid.values()].find(
(hex) => hex.hasPlanet() && !hex.hasSpaceship() && !hex.occupied()
);
if (!start) {
throw new Error("need a non-ship starting hex for player 1");
}
start.data.player = PlayerEnum.Player1;
start.data.building = Building.Mine;
engine.player(PlayerEnum.Player1).data.occupied.push(start);
engine.player(PlayerEnum.Player1).data.buildings[Building.Mine] += 1;
engine.phase = Phase.RoundMove;
engine.round = 1;
engine.turnOrder = engine.players.map((pl) => pl.player);
engine.currentPlayer = PlayerEnum.Player1;
const shipHex = [...engine.map.grid.values()].find((hex) => hex.hasSpaceship());
if (!shipHex) {
throw new Error("need a spaceship hex for Ivits to target");
}
const queuedMove = `ivits special space-station. build sp ${shipHex.toString()}.`;
// Another player placed a Lost Planet on the exact same hex in the meantime.
const contested = Engine.fromData(JSON.parse(JSON.stringify(engine)));
const contestedHex = contested.map.grid.get({ q: shipHex.q, r: shipHex.r }) as GaiaHex;
contestedHex.data.planet = Planet.Lost;
contestedHex.data.player = PlayerEnum.Player2;
contestedHex.data.building = Building.Mine;
const result = resolvePremoveQueue(
() => cloneEngineLike(contested),
0,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(result.outcome).to.equal("failed");
});
it("contested-hex build (the same canOccupy gate that also protects a Gaiaformer free-mine on an Asteroid): a queued build fails cleanly once another player already occupies the target hex", () => {
// The full Gaiaformer-free-mine-on-Asteroid path (triggered by claiming a Range/Terraform
// spaceship federation token, a multi-step chained command - available/federations.spec.ts's
// possibleFederationTokenBuildMine tests call it directly rather than through a real move) is
// complex to construct via a genuinely-replayable move string. The invariant #69 actually cares
// about - player.ts's canOccupy checking hex.data.player live, so a build throws cleanly once
// someone else occupies the target hex - is the exact same gate for an ordinary build and for
// the Asteroid free-mine variant; this exercises it via an ordinary build, reusing the federation
// test's own proven-legal fixture and move ("p2 build m -1x0.").
const moves = parseMoves(`
init 2 randomSeed
p1 faction terrans
p2 faction bescods
p1 build m -1x2
p2 build m -1x-1
p2 build m 3x-2
p1 build m -4x2
p2 booster booster3
p1 booster booster7
p1 up gaia.
p2 build ts -1x-1.
p1 build gf -2x3.
`);
const engine = new Engine(moves);
const queuedMove = "p2 build m -1x0.";
// Sanity: this move IS legal right now (proves the fixture).
expect(() => new Engine([...moves, queuedMove])).to.not.throw();
// Another player occupies the exact same hex in the meantime.
const contested = Engine.fromData(JSON.parse(JSON.stringify(engine)));
const contestedHex = contested.map.grid.get({ q: -1, r: 0 }) as GaiaHex;
contestedHex.data.player = PlayerEnum.Player1;
contestedHex.data.building = Building.Mine;
const result = resolvePremoveQueue(
() => cloneEngineLike(contested),
1,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(result.outcome).to.equal("failed");
});
it("Gaiaforming contention: a queued T F Mars instant-Gaiaforming move fails cleanly once another player already built on that Transdim hex", () => {
const engine = createRoundMoveEngine(2, [Faction.Terrans, Faction.Lantids]);
engine.player(PlayerEnum.Player1).data.explorationShips[Spaceship.TFMars] = 1;
occupyPlanetsOfDistinctTypes(engine, PlayerEnum.Player1, 1);
const transdim = [...engine.map.grid.values()].find(
(hex) => hex.data.planet === Planet.Transdim && !hex.hasSpaceship() && !hex.occupied()
);
if (!transdim) {
throw new Error("need an unoccupied Transdim hex for this fixture");
}
const queuedMove = `terrans spaceshipAction tfmars power. gaiaFormTransdim ${transdim.toString()}.`;
// Sanity: legal right now against the pristine engine.
const pristineResult = resolvePremoveQueue(
() => cloneEngineLike(engine),
0,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(pristineResult.outcome).to.equal("success");
// Another player builds on the exact same Transdim hex in the meantime (available/spaceship-
// actions.ts's possibleInstantGaiaforming skips any hex with hex.data.building already set).
const contested = Engine.fromData(JSON.parse(JSON.stringify(engine)));
const contestedHex = contested.map.grid.get({ q: transdim.q, r: transdim.r }) as GaiaHex;
contestedHex.data.player = PlayerEnum.Player2;
contestedHex.data.building = Building.Mine;
const result = resolvePremoveQueue(
() => cloneEngineLike(contested),
0,
[{ seq: 1, move: queuedMove }],
"sequential"
);
expect(result.outcome).to.equal("failed");
});
});

621
engine/premoves.spec.ts Normal file
View file

@ -0,0 +1,621 @@
import { expect } from "chai";
import Engine from "./src/engine";
import { Operator, Phase, Resource } from "./src/enums";
import Event from "./src/events";
import { Power } from "./src/player-data";
import { capturePremovePower } from "./src/premove-power";
import { automation, playNextPremove, PremoveCommand, setPremoves } from "./src/premoves";
import {
automove,
canMoveOutOfTurn,
isLiveUpdate,
logSlice,
move,
replay,
setPlayerSettings,
stripSecret,
timeIncrements,
toSave,
} from "./wrapper";
const setup = Engine.parseMoves(`
init 2 randomSeed
p1 faction terrans
p2 faction nevlas
terrans build m -1x2
nevlas build m -1x0
nevlas build m 0x-4
terrans build m -4x-1
nevlas booster booster7
terrans booster booster3
`);
let request = 0;
function game() {
return new Engine(setup);
}
function command(engine: Engine, seat: number, moves: string[]): PremoveCommand {
return {
type: "premoves",
requestId: `test-${++request}`,
moves,
revision: engine.automation?.plans[seat]?.revision ?? 0,
round: engine.round,
turn: engine.automation?.turns[seat] ?? 0,
};
}
function queue(engine: Engine, seat: number, moves: string[]) {
return move(engine, command(engine, seat, moves), seat);
}
function json(engine: Engine): Engine {
return JSON.parse(JSON.stringify(engine));
}
describe("BGS premoves", () => {
it("keeps played, blocked and unplayed steps privately across refreshes and new queues", () => {
let engine = game();
engine.players[1].data.knowledge = 8;
const moves = ["nevlas up nav.", "nevlas up gaia.", "nevlas up eco.", "nevlas build ts -1x0."];
engine = move(engine, { ...command(engine, 1, moves), label: "Plan B" }, 1);
engine = move(json(engine), "terrans build ts -1x2.", 0);
engine = move(json(engine), "terrans pass booster8", 0);
const plan = engine.automation.plans[1];
expect(plan.moves).to.deep.equal([]);
expect(plan.runs[0].label).to.equal("Plan B");
expect(plan.runs[0].steps.map((step) => step.move)).to.deep.equal(moves);
expect(plan.runs[0].steps.map((step) => step.status)).to.deep.equal(["played", "played", "blocked", "unplayed"]);
expect(plan.runs[0].status).to.equal("stopped");
expect(plan.runs[0].reason).to.be.a("string").and.not.equal("");
for (const step of plan.runs[0].steps.filter((step) => step.status === "played")) {
expect(engine.moveHistory[step.moveIndex]).to.contain(step.move.split(".")[0]);
}
const snapshot = JSON.parse(JSON.stringify(plan.runs));
engine = Engine.fromData(json(engine));
automove(engine);
expect(engine.automation.plans[1].runs).to.deep.equal(snapshot);
expect(stripSecret(engine, 0).automation.plans).to.deep.equal({});
expect(stripSecret(engine).automation.plans).to.deep.equal({});
expect(stripSecret(engine, 1).automation.plans[1].runs).to.deep.equal(snapshot);
expect(logSlice(engine).state.automation.plans).to.deep.equal({});
engine = queue(engine, 1, ["nevlas pass booster3"]);
expect(engine.automation.plans[1].runs[1]).to.deep.equal(snapshot[0]);
expect(engine.automation.plans[1].runs[0].status).to.equal("completed");
});
it("marks taken-back premoves without deleting their remaining plan", async () => {
let engine = queue(game(), 1, ["nevlas up nav.", "nevlas up gaia."]);
engine = move(json(engine), "terrans build ts -1x2.", 0);
expect(engine.automation.plans[1].runs[0].steps[0].status).to.equal("played");
engine = await replay(engine, { to: setup.length });
expect(engine.automation.plans[1].moves).to.deep.equal([]);
expect(engine.automation.plans[1].runs[0].steps.map((step) => step.status)).to.deep.equal(["undone", "unplayed"]);
expect(engine.automation.plans[1].runs[0].reason).to.equal("The game was taken back.");
});
it("records cancellation and replacement without deleting the pending steps", () => {
let engine = queue(game(), 1, ["nevlas up nav.", "nevlas up gaia."]);
engine = queue(engine, 1, ["nevlas up eco."]);
expect(engine.automation.plans[1].runs[1].status).to.equal("replaced");
expect(engine.automation.plans[1].runs[1].steps.map((step) => step.status)).to.deep.equal(["unplayed", "unplayed"]);
engine = queue(engine, 1, []);
expect(engine.automation.plans[1].runs[0].status).to.equal("cancelled");
expect(engine.automation.plans[1].runs[0].steps[0].move).to.equal("nevlas up eco.");
expect(engine.automation.plans[1].moves).to.deep.equal([]);
});
it("adopts legacy queues and records manual interruptions and players leaving", () => {
let engine = queue(game(), 1, ["nevlas up nav."]);
delete engine.automation.plans[1].runs;
engine = move(json(engine), "terrans build ts -1x2.", 0);
expect(engine.automation.plans[1].runs[0].steps[0].status).to.equal("played");
expect(engine.automation.plans[1].runs[0].status).to.equal("completed");
engine = game();
automation(engine).plans[0] = { moves: ["terrans up nav."], revision: 1, round: 1 };
engine = move(engine, "terrans build ts -1x2.", 0);
expect(engine.automation.plans[0].runs[0].status).to.equal("stopped");
expect(engine.automation.plans[0].runs[0].reason).to.contain("manually");
engine = queue(game(), 1, ["nevlas up nav."]);
engine.players[1].dropped = true;
automove(engine);
expect(engine.automation.plans[1].runs[0].reason).to.equal("You left the game.");
expect(engine.automation.plans[1].runs[0].steps[0].status).to.equal("unplayed");
});
it("queues a second starting mine off turn without simulating other players in the real game", () => {
let engine = new Engine(setup.slice(0, 4));
const history = [...engine.moveHistory];
const queued = command(engine, 0, ["terrans build m -4x-1"]);
queued.timings = [{ round: 0, phase: Phase.SetupBuilding }];
expect(canMoveOutOfTurn(json(engine), queued, 0)).to.equal(true);
engine = move(json(engine), queued, 0);
expect(isLiveUpdate(engine)).to.equal(true);
expect(engine.moveHistory).to.deep.equal(history);
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
expect(stripSecret(engine, 1).automation.plans).to.deep.equal({});
engine = move(json(engine), "nevlas build m -1x0", 1);
expect(engine.automation.plans[0].moves).to.have.length(1);
engine = move(json(engine), "nevlas build m 0x-4", 1);
expect(engine.moveHistory.slice(-1)).to.deep.equal(["terrans build m -4x-1"]);
expect(engine.automation.plans[0].moves).to.deep.equal([]);
expect(engine.phase).to.equal(Phase.SetupBooster);
expect(timeIncrements(engine)).to.deep.equal([1, 2]);
expect(engine.automation.turns).to.deep.equal([1, 2]);
automove(engine);
expect(timeIncrements(engine)).to.deep.equal([1, 2]);
});
it("can cancel a starting placement and rejects a submission stale after a manual placement", () => {
let engine = new Engine(setup.slice(0, 4));
const stale = command(engine, 0, ["terrans build m -4x-1"]);
engine = queue(engine, 0, ["terrans build m -4x-1"]);
engine = queue(engine, 0, []);
engine = move(json(engine), "nevlas build m -1x0", 1);
engine = move(json(engine), "nevlas build m 0x-4", 1);
expect(engine.playerToMove).to.equal(0);
expect(engine.players[0].data.occupied).to.have.length(1);
engine = move(json(engine), "terrans build m -4x-1", 0);
stale.revision = engine.automation.plans[0].revision;
stale.timings = [{ round: 0, phase: Phase.SetupBooster }];
stale.moves = ["terrans booster booster3"];
expect(() => move(json(engine), stale, 0)).to.throw("turn has changed");
});
it("stops an unavailable setup placement without making an alternative move", () => {
let engine = new Engine(setup.slice(0, 4));
engine = queue(engine, 0, ["terrans build m -1x2"]);
engine = move(json(engine), "nevlas build m -1x0", 1);
engine = move(json(engine), "nevlas build m 0x-4", 1);
expect(engine.playerToMove).to.equal(0);
expect(engine.players[0].data.occupied).to.have.length(1);
expect(engine.automation.plans[0].notice.kind).to.equal("stopped");
expect(engine.automation.plans[0].moves).to.deep.equal([]);
expect(timeIncrements(engine)).to.deep.equal([0, 2]);
});
it("waits for the initial booster pick after a queued mine, then rechecks availability", () => {
let engine = new Engine(setup.slice(0, 4));
const cmd = command(engine, 0, ["terrans build m -4x-1", "terrans booster booster7"]);
cmd.timings = [
{ round: 0, phase: Phase.SetupBuilding },
{ round: 0, phase: Phase.SetupBooster },
];
engine = move(json(engine), cmd, 0);
engine = move(json(engine), "nevlas build m -1x0", 1);
engine = move(json(engine), "nevlas build m 0x-4", 1);
expect(engine.automation.plans[0].moves).to.deep.equal(["terrans booster booster7"]);
engine = move(json(engine), "nevlas booster booster7", 1);
expect(engine.phase).to.equal(Phase.SetupBooster);
expect(engine.playerToMove).to.equal(0);
expect(engine.automation.plans[0].notice.kind).to.equal("stopped");
expect(engine.players[0].data.tiles.booster).to.equal(null);
});
it("keeps a setup queue through income into round one without adding invented setup moves", () => {
let engine = new Engine(setup.slice(0, 4));
const cmd = command(engine, 0, ["terrans build m -4x-1", "terrans booster booster3", "terrans up nav."]);
cmd.timings = [
{ round: 0, phase: Phase.SetupBuilding },
{ round: 0, phase: Phase.SetupBooster },
{ round: 1, phase: Phase.RoundMove },
];
engine = move(json(engine), cmd, 0);
engine = move(json(engine), "nevlas build m -1x0", 1);
engine = move(json(engine), "nevlas build m 0x-4", 1);
engine = move(json(engine), "nevlas booster booster7", 1);
expect(engine.phase).to.equal(Phase.RoundMove);
expect(engine.round).to.equal(1);
expect(engine.moveHistory).to.deep.equal(new Engine([...setup, "terrans up nav."]).moveHistory);
expect(engine.automation.plans[0].moves).to.deep.equal([]);
expect(timeIncrements(engine)).to.deep.equal([3, 3]);
});
it("rejects premoves before faction selection and setup timings in a running round", () => {
expect(() => queue(new Engine(setup.slice(0, 1)), 0, ["p1 faction terrans"])).to.throw("after faction selection");
const engine = new Engine(setup.slice(0, 4));
const cmd = command(engine, 0, ["terrans build m -4x-1"]);
cmd.timings = [{ round: 1, phase: Phase.SetupBuilding }];
expect(() => move(json(engine), cmd, 0)).to.throw("Invalid premove schedule");
cmd.timings = [{ round: 0, phase: Phase.RoundMove }];
expect(() => move(json(engine), cmd, 0)).to.throw("Invalid premove schedule");
});
it("keeps the 3c Trading Station constraint and executes after a real neighbour arrives", () => {
let engine = game();
Object.assign(engine.players[0].data, { ores: 20, credits: 20, qics: 10 });
setPlayerSettings(engine, 1, { autoCharge: "2" });
const credits = engine.players[1].data.credits;
engine = queue(engine, 1, ["nevlas build ts 4A11 cheap."]);
expect(engine.automation.plans[1].moves).to.deep.equal(["nevlas build ts 4A11 cheap."]);
expect(engine.players[1].data.credits).to.equal(credits);
engine = move(json(engine), "terrans build m 4B0.", 0);
expect(engine.automation.plans[1].notice.kind).to.equal("played");
expect(engine.players[1].data.credits).to.equal(credits - 3);
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
});
it("stops an isolated 3c-only upgrade atomically instead of spending 6c", () => {
let engine = game();
const credits = engine.players[1].data.credits;
const qics = engine.players[1].data.qics;
const ores = engine.players[1].data.ores;
expect(credits).to.be.at.least(6);
engine = queue(engine, 1, ["nevlas spend 1q for 1o. build ts 4A11 cheap."]);
engine = move(json(engine), "terrans up nav.", 0);
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
expect(engine.automation.plans[1].notice.text).to.contain("not available for 3c");
expect(engine.automation.plans[1].moves).to.deep.equal([]);
expect(engine.players[1].data.credits).to.equal(credits);
expect(engine.players[1].data.qics).to.equal(qics);
expect(engine.players[1].data.ores).to.equal(ores);
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
});
it("can queue a power spend before a charge, then uses real autoleech when the turn arrives", () => {
let engine = game();
Object.assign(engine.players[1].data.power, { area1: 0, area2: 1, area3: 0 });
setPlayerSettings(engine, 1, { autoCharge: "2" });
const credits = engine.players[1].data.credits;
engine = queue(engine, 1, ["nevlas spend 1pw for 1c. up nav."]);
expect(engine.players[1].data.power.area3).to.equal(0);
expect(engine.players[1].data.credits).to.equal(credits);
expect(engine.players[1].data.analysis).to.equal(false);
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
engine = move(json(engine), "terrans build ts -1x2.", 0);
expect(engine.automation.plans[1].notice.kind).to.equal("played");
expect(engine.players[1].data.credits).to.equal(credits + 1);
expect(engine.players[1].data.power.area3).to.equal(0);
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
});
it("stops instead of waiting or fabricating power when the anticipated charge never arrives", () => {
let engine = game();
Object.assign(engine.players[1].data.power, { area1: 0, area2: 1, area3: 0 });
const credits = engine.players[1].data.credits;
engine = queue(engine, 1, ["nevlas spend 1pw for 1c. up nav."]);
engine = move(json(engine), "terrans up nav.", 0);
expect(engine.playerToMove).to.equal(1);
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
expect(engine.automation.plans[1].moves).to.deep.equal([]);
expect(engine.players[1].data.power.area3).to.equal(0);
expect(engine.players[1].data.credits).to.equal(credits);
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
});
it("still rejects an unaffordable move submitted to play immediately", () => {
const engine = game();
engine.players[0].data.knowledge = 0;
expect(() => queue(engine, 0, ["terrans up nav."])).to.throw();
expect(engine.players[0].data.knowledge).to.equal(0);
});
it("saves a private off-turn queue without changing turns, logs or clocks", () => {
let engine = game();
const before = engine.moveHistory.length;
const cmd = command(engine, 1, ["nevlas up nav."]);
expect(canMoveOutOfTurn(json(engine), cmd, 1)).to.equal(true);
engine = move(json(engine), cmd, 1);
expect(toSave(engine)).to.equal(engine);
expect(isLiveUpdate(engine)).to.equal(true);
expect(engine.playerToMove).to.equal(0);
expect(engine.moveHistory.length).to.equal(before);
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
expect(stripSecret(engine, 1).automation.plans[1].moves).to.deep.equal(cmd.moves);
expect(stripSecret(engine, 0).automation.plans).to.deep.equal({});
expect(logSlice(engine).state.automation.plans).to.deep.equal({});
});
it("runs the queue after auto-leech and awards each completed main turn exactly once", () => {
let engine = queue(game(), 1, ["nevlas up nav."]);
engine = move(json(engine), "terrans build ts -1x2.", 0);
expect(engine.moveHistory.slice(-3)[1]).to.match(/^nevlas charge/);
expect(engine.moveHistory.slice(-1)[0]).to.match(/^nevlas up nav/);
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
expect(isLiveUpdate(engine)).to.equal(false);
expect(engine.automation.plans[1].moves).to.deep.equal([]);
automove(engine);
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
});
it("keeps a queue through a manual charge decision and executes after it", () => {
let engine = game();
engine.move("terrans build ts -1x2.");
automove(engine);
engine.move("nevlas build ts -1x0.");
expect(engine.phase).to.equal(Phase.RoundLeech);
engine = queue(engine, 0, ["terrans up nav."]);
expect(engine.automation.plans[0].moves).to.have.length(1);
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
engine = move(json(engine), "terrans charge 2pw", 0);
expect(engine.automation.plans[0].moves).to.have.length(0);
expect(timeIncrements(engine)).to.deep.equal([2, 0]);
expect(engine.automation.turns).to.deep.equal([1, 0]);
});
it("runs several seats' queues, with autoleech between them", () => {
let engine = queue(game(), 1, ["nevlas build ts -1x0."]);
setPlayerSettings(engine, 0, { autoCharge: "2" });
engine = queue(engine, 0, ["terrans build ts -1x2.", "terrans up nav."]);
expect(engine.automation.plans[0].moves).to.have.length(0);
expect(engine.automation.plans[1].moves).to.have.length(0);
expect(timeIncrements(engine)).to.deep.equal([2, 1]);
});
it("stops an illegal chain atomically, leaving the resources and active turn intact", () => {
let engine = queue(game(), 1, ["nevlas up nav.", "nevlas build ts -1x0."]);
engine.players[1].data.knowledge = 0;
const wallet = engine.players[1].data.ores;
engine = move(json(engine), "terrans up nav.", 0);
expect(engine.playerToMove).to.equal(1);
expect(engine.players[1].data.ores).to.equal(wallet);
expect(engine.automation.plans[1].moves).to.deep.equal([]);
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
});
it("rejects another seat's moves, incomplete plans, stale turns and stale queue edits", () => {
const engine = game();
expect(() => queue(engine, 1, ["terrans up nav."])).to.throw("own moves");
expect(() => queue(engine, 1, ["nevlas burn 1"])).to.throw();
const stale = command(engine, 1, ["nevlas up nav."]);
queue(engine, 1, ["nevlas up terra."]);
expect(() => move(engine, stale, 1)).to.throw("queue changed");
const turn = command(engine, 1, ["nevlas up nav."]);
automation(engine).turns[1]++;
expect(() => move(engine, turn, 1)).to.throw("turn has changed");
expect(canMoveOutOfTurn(engine, "nevlas up nav.", 1)).to.equal(false);
expect(canMoveOutOfTurn(engine, stale, -1)).to.equal(false);
});
it("makes duplicate submissions harmless, even after the move has executed", () => {
let engine = game();
const cmd = command(engine, 0, ["terrans up nav."]);
engine = move(engine, cmd, 0);
const history = [...engine.moveHistory];
engine = move(json(engine), cmd, 0);
expect(engine.moveHistory).to.deep.equal(history);
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
expect(engine.automation.plans[0].moves).to.have.length(0);
});
it("rolls back free conversions when a later command in the same premove becomes illegal", () => {
let engine = queue(game(), 1, ["nevlas spend 1q for 1o. up nav."]);
engine.players[1].data.knowledge = 0;
const before = [engine.players[1].data.qics, engine.players[1].data.ores];
engine = move(json(engine), "terrans up nav.", 0);
expect([engine.players[1].data.qics, engine.players[1].data.ores]).to.deep.equal(before);
expect(engine.automation.plans[1].notice.kind).to.equal("stopped");
});
it("allows cancellation even when the retained prefix is no longer legal", () => {
let engine = queue(game(), 1, ["nevlas up nav.", "nevlas build ts -1x0."]);
engine.players[1].data.knowledge = 0;
engine = queue(engine, 1, ["nevlas up nav."]);
expect(engine.automation.plans[1].moves).to.deep.equal(["nevlas up nav."]);
engine = queue(engine, 1, []);
expect(engine.automation.plans[1].moves).to.deep.equal([]);
expect(timeIncrements(engine)).to.deep.equal([0, 0]);
});
it("keeps a queued move after a pass and executes it in the next round", () => {
let engine = queue(game(), 0, ["terrans pass booster4", "terrans up nav."]);
expect(engine.round).to.equal(1);
expect(engine.automation.plans[0].moves).to.deep.equal(["terrans up nav."]);
expect(timeIncrements(engine)).to.deep.equal([1, 0]);
engine = move(json(engine), "nevlas pass booster5", 1);
expect(engine.round).to.equal(2);
expect(engine.automation.plans[0].moves).to.deep.equal([]);
expect(engine.players[0].data.research.nav).to.equal(1);
expect(timeIncrements(engine)).to.deep.equal([2, 1]);
});
it("can queue after already passing without reopening the current round", () => {
let engine = move(game(), "terrans pass booster4", 0);
const before = [...engine.moveHistory];
engine = queue(engine, 0, ["terrans up nav."]);
expect(engine.moveHistory).to.deep.equal(before);
expect(isLiveUpdate(engine)).to.equal(true);
expect(engine.automation.plans[0].timings).to.deep.equal([{ round: 2, phase: Phase.RoundMove }]);
engine = move(json(engine), "nevlas pass booster5", 1);
expect(engine.automation.plans[0].moves).to.deep.equal([]);
expect(timeIncrements(engine)).to.deep.equal([2, 1]);
});
it("queues and executes more than three moves without losing the tail", () => {
let engine = game();
engine.players[1].data.knowledge = 12;
const moves = ["nevlas up nav.", "nevlas up terra.", "nevlas up int.", "nevlas pass booster3"];
engine = queue(engine, 1, moves);
expect(stripSecret(engine, 1).automation.plans[1].moves).to.deep.equal(moves);
expect(engine.moveHistory).to.deep.equal(game().moveHistory);
engine = move(json(engine), "terrans pass booster4", 0);
expect(engine.automation.plans[1].moves).to.deep.equal([]);
expect(engine.automation.plans[1].notice.kind).to.equal("played");
for (const planned of moves) {
expect(engine.moveHistory.some((move) => move.startsWith(planned.replace(/\.$/, "")))).to.equal(true);
}
expect(engine.players[1].data.research.nav).to.equal(1);
expect(engine.players[1].data.research.terra).to.equal(1);
expect(engine.players[1].data.research.int).to.equal(1);
expect(engine.round).to.equal(2);
});
const passedItarsGame = () => {
const engine = new Engine([
"init 2 Gaudy-plow-4506",
"p1 faction itars",
"p2 faction ivits",
"itars build m 3B3",
"itars build m 2B2",
"ivits build PI 4B3",
"ivits booster booster3",
"itars booster booster8",
"ivits income t",
"itars pass booster9",
]);
engine.players.forEach((player) => {
player.settings.autoIncome = false;
// Keep a real trade-off: maximising usable power can waste a charge.
// Income with a dominant order now resolves even without autoIncome.
player.data.power = new Power();
player.events[Operator.Income] = player.events[Operator.Income].filter(
(event) => !event.rewards.some((reward) => [Resource.GainToken, Resource.ChargePower].includes(reward.type))
);
player.loadEvents(Event.parse(["+2t", "+2t", "+2pw", "+3pw"], null));
});
return engine;
};
it("queues next-round income and a main turn while waiting for the opponent's manual income", () => {
let engine = passedItarsGame();
engine = move(
engine,
{
...command(engine, 0, ["itars income 2t,2t", "itars up nav."]),
timings: [
{ round: 2, phase: Phase.RoundIncome },
{ round: 2, phase: Phase.RoundMove },
],
},
0
);
expect(isLiveUpdate(engine)).to.equal(true);
engine = move(json(engine), "ivits pass booster8", 1);
expect(engine.phase).to.equal(Phase.RoundIncome);
expect(engine.playerToMove).to.equal(1);
expect(engine.automation.plans[0].moves).to.deep.equal(["itars up nav."]);
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
engine = move(json(engine), "ivits income 2t,2t", 1);
expect(engine.automation.plans[0].moves).to.deep.equal([]);
expect(engine.players[0].data.research.nav).to.equal(1);
expect(timeIncrements(engine)).to.deep.equal([2, 2]);
});
it("waits for an unplanned manual income choice without clearing next-round moves", () => {
let engine = queue(passedItarsGame(), 0, ["itars up nav."]);
engine = move(json(engine), "ivits pass booster8", 1);
expect(engine.phase).to.equal(Phase.RoundIncome);
expect(engine.playerToMove).to.equal(0);
expect(engine.automation.plans[0].moves).to.have.length(1);
engine = move(json(engine), "itars income 2t,2t", 0);
expect(engine.automation.plans[0].moves).to.have.length(1);
engine = move(json(engine), "ivits income 2t,2t", 1);
expect(engine.automation.plans[0].moves).to.have.length(0);
expect(timeIncrements(engine)).to.deep.equal([2, 2]);
});
it("does not replay or credit income that automatic income has already resolved", () => {
let engine = passedItarsGame();
engine.players.forEach((player) => {
player.settings.autoIncome = true;
});
engine = move(
engine,
{
...command(engine, 0, ["itars income 2t,2t", "itars up nav."]),
timings: [
{ round: 2, phase: Phase.RoundIncome },
{ round: 2, phase: Phase.RoundMove },
],
},
0
);
engine = move(json(engine), "ivits pass booster8", 1);
expect(engine.automation.plans[0].moves).to.deep.equal([]);
expect(engine.players[0].data.research.nav).to.equal(1);
expect(engine.automation.plans[0].runs[0].steps.map((step) => step.status)).to.deep.equal(["skipped", "played"]);
expect(timeIncrements(engine)).to.deep.equal([1, 1]);
});
it("can cancel next-round moves and rejects schedules that go backwards", () => {
let engine = queue(passedItarsGame(), 0, ["itars up nav."]);
engine = queue(engine, 0, []);
engine = move(json(engine), "ivits pass booster8", 1);
engine = move(json(engine), "itars income 2t,2t", 0);
engine = move(json(engine), "ivits income 2t,2t", 1);
expect(engine.players[0].data.research.nav).to.equal(0);
expect(() =>
move(
engine,
{
...command(engine, 0, ["itars up nav.", "itars up terra."]),
timings: [
{ round: 3, phase: Phase.RoundMove },
{ round: 2, phase: Phase.RoundMove },
],
},
0
)
).to.throw("round order");
});
it("preserves increment totals and clears plans when replaying an existing game", async () => {
let engine = queue(game(), 1, ["nevlas up nav."]);
engine = move(engine, "terrans up nav.", 0);
const counts = timeIncrements(engine);
engine = await replay(json(engine), { to: setup.length });
expect(timeIncrements(engine)).to.deep.equal(counts);
expect(engine.automation.plans[1].moves).to.deep.equal([]);
expect(engine.automation.plans[1].runs[0].status).to.equal("stopped");
});
});
describe("planned power safety", () => {
it("preserves baseline alignment through prefix cancellation and private history", () => {
const engine = game();
const moves = ["nevlas up nav.", "nevlas up gaia."];
const preview = Engine.fromData(json(engine));
preview.forcePremovePreviewTurn(1);
const power = [capturePremovePower(preview, 1, moves[0])];
preview.forcePremovePreviewTurn(1);
preview.players[1].data.knowledge = 4;
power.push(capturePremovePower(preview, 1, moves[1]));
setPremoves(engine, { ...command(engine, 1, moves), power }, 1);
setPremoves(engine, command(engine, 1, moves.slice(0, 1)), 1);
expect(engine.automation.plans[1].power).to.deep.equal(power.slice(0, 1));
expect(engine.automation.plans[1].runs[0].steps[0].power).to.deep.equal(power[0]);
expect(stripSecret(engine, 0).automation.plans).to.deep.equal({});
engine.forcePremovePreviewTurn(1);
expect(playNextPremove(engine)).to.equal(true);
expect(engine.automation.plans[1].power).to.deep.equal([]);
expect(engine.automation.plans[1].runs[0].steps[0].power).to.deep.equal(power[0]);
});
for (const originallyFull of [false, true]) {
it(`checks original charge waste before any live command (originally full: ${originallyFull})`, () => {
const engine = game();
engine.players[0].data.research.nav = 2;
Object.assign(engine.players[0].data.power, {
area1: originallyFull ? 0 : 3,
area2: 0,
area3: originallyFull ? 3 : 0,
});
const planned = "terrans spend 1q for 1o. up nav.";
const preview = Engine.fromData(json(engine));
const power = [capturePremovePower(preview, 0, planned)];
setPremoves(engine, { ...command(engine, 0, [planned]), power }, 0);
const saved = Engine.fromData(json(engine));
expect(saved.automation.plans[0].power).to.deep.equal(power);
saved.players[0].data.chargePower(6);
const before = JSON.stringify(saved.players[0].data);
const history = saved.moveHistory.length;
expect(playNextPremove(saved)).to.equal(originallyFull);
if (!originallyFull) {
expect(JSON.stringify(saved.players[0].data)).to.equal(before);
expect(saved.moveHistory.length).to.equal(history);
expect(saved.automation.plans[0].notice.text).to.contain("waste more power");
}
});
}
it("rejects malformed baselines and stops risky legacy plans rather than inventing intent", () => {
const engine = game();
engine.players[0].data.research.nav = 2;
Object.assign(engine.players[0].data.power, { area1: 0, area2: 0, area3: 3 });
const request = command(engine, 0, ["terrans up nav."]);
expect(() =>
setPremoves(
engine,
{ ...request, power: [[{ command: "up nav", events: [{ kind: "charge", waste: -1, area2: 0, area3: 0 }] }]] },
0
)
).to.throw("Invalid premove power");
setPremoves(engine, request, 0);
expect(playNextPremove(engine)).to.equal(false);
expect(engine.automation.plans[0].notice.text).to.contain("older plan");
});
});

View file

@ -0,0 +1,43 @@
import { writeFileSync } from "fs";
import { resolve } from "path";
import { DEFAULT_BENCHMARK_CONFIG, runPhase0Benchmark } from "../../src/ai/benchmark";
function numericArgument(args: string[], flag: string, fallback: number): number {
const index = args.indexOf(flag);
if (index < 0) {
return fallback;
}
const value = Number(args[index + 1]);
if (!Number.isInteger(value) || value < 0) {
throw new Error(`${flag} requires a non-negative integer`);
}
return value;
}
function stringArgument(args: string[], flag: string): string | undefined {
const index = args.indexOf(flag);
return index < 0 ? undefined : args[index + 1];
}
const args = process.argv.slice(2);
const result = runPhase0Benchmark({
warmupIterations: numericArgument(args, "--warmup", DEFAULT_BENCHMARK_CONFIG.warmupIterations),
iterations: numericArgument(args, "--iterations", DEFAULT_BENCHMARK_CONFIG.iterations),
randomGameWarmupIterations: numericArgument(
args,
"--random-warmup",
DEFAULT_BENCHMARK_CONFIG.randomGameWarmupIterations
),
randomGameIterations: args.includes("--skip-random-games")
? 0
: numericArgument(args, "--random-games", DEFAULT_BENCHMARK_CONFIG.randomGameIterations),
memoryCloneCount: numericArgument(args, "--memory-clones", DEFAULT_BENCHMARK_CONFIG.memoryCloneCount),
});
const json = JSON.stringify(result, null, 2) + "\n";
const target = stringArgument(args, "--output");
if (target) {
writeFileSync(resolve(target), json, "utf8");
} else {
process.stdout.write(json);
}

View file

@ -0,0 +1,40 @@
import { writeFileSync } from "fs";
import { resolve } from "path";
import { runMacroCorpusCampaign } from "../../src/ai/testing/corpus";
function numericArgument(args: string[], flag: string, fallback: number): number {
const index = args.indexOf(flag);
if (index < 0) {
return fallback;
}
const value = Number(args[index + 1]);
if (!Number.isInteger(value) || value < 0) {
throw new Error(`${flag} requires a non-negative integer`);
}
return value;
}
function stringArgument(args: string[], flag: string): string | undefined {
const index = args.indexOf(flag);
return index < 0 ? undefined : args[index + 1];
}
const args = process.argv.slice(2);
const games = numericArgument(args, "--games", 20);
const seedPrefix = stringArgument(args, "--seed-prefix") ?? "phase-1-4-corpus";
const startedAt = Date.now();
const result = runMacroCorpusCampaign({
playSeeds: Array.from({ length: games }, (_, index) => `${seedPrefix}-${String(index + 1).padStart(2, "0")}`),
minStates: numericArgument(args, "--min-states", 1000),
conversionIntegrationEvery: numericArgument(args, "--integration-every", 0),
afterConversionIntegration: args.includes("--after-conversions"),
deepCheckEvery: numericArgument(args, "--deep-check-every", 7),
});
const json = JSON.stringify({ ...result, elapsedSeconds: (Date.now() - startedAt) / 1000 }, null, 2) + "\n";
const target = stringArgument(args, "--output");
if (target) {
writeFileSync(resolve(target), json, "utf8");
} else {
process.stdout.write(json);
}

View file

@ -0,0 +1,17 @@
import { writeFileSync } from "fs";
import { resolve } from "path";
import { generateChallengeManifest, stableManifestJson } from "../../src/ai/challenge-manifest";
function outputPath(args: string[]): string | undefined {
const index = args.indexOf("--output");
return index >= 0 ? args[index + 1] : undefined;
}
const json = stableManifestJson(generateChallengeManifest()) + "\n";
const target = outputPath(process.argv.slice(2));
if (target) {
writeFileSync(resolve(target), json, "utf8");
} else {
process.stdout.write(json);
}

182
engine/src/achievements.ts Normal file
View file

@ -0,0 +1,182 @@
import type { AchievementDefinition, AchievementManifest, SeatAchievements } from "@boardgamers/protocol/engine";
import { automaDifficulties } from "./automa";
import Engine from "./engine";
import { Building, Expansion, Faction, Phase, Planet, ResearchField, Round } from "./enums";
export type {
AchievementDefinition,
AchievementIcon,
AchievementManifest,
SeatAchievements,
} from "@boardgamers/protocol/engine";
const standardBuildings = [
Building.Mine,
Building.TradingStation,
Building.ResearchLab,
Building.PlanetaryInstitute,
Building.Academy1,
Building.Academy2,
];
const baseColonyTypes = [
Planet.Terra,
Planet.Desert,
Planet.Swamp,
Planet.Oxide,
Planet.Volcanic,
Planet.Titanium,
Planet.Ice,
Planet.Gaia,
Planet.Lost,
];
function displayName(id: string): string {
return id
.split("-")
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(" ");
}
/** The complete catalog, independent of the current game's mode or faction selection. */
export function achievementDefinitions(): AchievementManifest {
const definitions: AchievementDefinition[] = Faction.values(Expansion.All).map((faction) => ({
id: `win-faction-${faction}`,
icon: { type: "asset", key: `achievement-faction-${faction}` },
name: `${displayName(faction)} Victory`,
description: `Win as ${displayName(faction)}. Shared first place counts; either ruleset qualifies.`,
}));
for (const mode of ["base", "lost-fleet"]) {
const name = mode === "base" ? "Base Game" : "Lost Fleet";
definitions.push({
id: `win-mode-${mode}`,
icon: { type: "asset", key: `achievement-win-mode-${mode}` },
name: `${name} Victory`,
description: `Win a ${name} game, including shared first place.`,
});
for (const threshold of [150, 200]) {
definitions.push({
id: `score-${mode}-${threshold}`,
icon: { type: "asset", key: `achievement-score-${threshold}` },
name: `${name}: ${threshold} Points`,
description: `Finish a ${name} game with at least ${threshold} final victory points, after auction deductions. No win required.`,
});
}
}
for (const difficulty of automaDifficulties) {
definitions.push({
id: `win-automa-${difficulty}`,
icon: { type: "asset", key: `achievement-win-automa-${difficulty}` },
name: `Defeat ${displayName(difficulty)}`,
description: `Win against Automa at exactly ${difficulty} difficulty. A tied score counts as a human win.`,
});
}
definitions.push(
{
id: "build-all-standard",
icon: { type: "asset", key: "achievement-build-all-standard" },
name: "Full Deployment",
description:
"Finish with all 18 standard building pieces simultaneously deployed: 8 mines, 4 trading stations, 3 research labs, the institute and both academies. Excludes Lost Planet, artifacts, Gaiaformers and space stations. No win required.",
},
{
id: "federation-form-4",
icon: { type: "asset", key: "achievement-federation-form-4" },
name: "Federation Builder",
description:
"Complete at least four federation formations in one game (extensions of the growing federation for Ivits). Token rewards and rescores do not count. No win required.",
},
{
id: "explore-all-types-base",
icon: { type: "asset", key: "achievement-explore-all-types-base" },
name: "Every World: Base Game",
description:
"Finish a base game with main-owned colonies on all seven ordinary planet types, Gaia and the Lost Planet. Gaiaformers and Lantids shared mines do not count. No win required.",
},
{
id: "explore-all-types-lost-fleet",
icon: { type: "asset", key: "achievement-explore-all-types-lost-fleet" },
name: "Every World: Lost Fleet",
description:
"Finish a Lost Fleet game with main-owned colonies on all seven ordinary types, Gaia, Lost Planet, Asteroid and Protoplanet. Artifacts, Gaiaformers and Lantids shared mines do not count. No win required.",
},
{
id: "faction-ivits-growing-federation",
icon: { type: "asset", key: "achievement-faction-ivits-growing-federation" },
name: "Growing Federation",
description:
"As Ivits, complete at least four formation milestones of your growing federation in one game. No win required.",
},
{
id: "faction-lantids-shared-civilization",
icon: { type: "asset", key: "achievement-faction-lantids-shared-civilization" },
name: "Shared Civilization",
description: "As Lantids, finish with at least six additional mines on opponents' colonies. No win required.",
},
{
id: "faction-bescods-balanced-research",
icon: { type: "asset", key: "achievement-faction-bescods-balanced-research" },
name: "Balanced Research",
description: "As Bescods, finish at level 3 or higher on all six research tracks. No win required.",
}
);
return { revision: 5, achievements: definitions };
}
/** Evaluate authoritative completed state only; never advance play or recompute final scoring. */
export function achievements(data: Engine | Record<string, any>): SeatAchievements[] {
// The EndGame log marker is emitted by finalScoringPhase, unlike early termination.
if (
data.phase !== Phase.EndGame ||
data.round !== Round.LastRound ||
!data.advancedLog?.some((entry) => entry.phase === Phase.EndGame)
) {
return [];
}
// Hydration normalizes legacy options and federation caches in place. Never change the
// caller's authoritative serialized state just to evaluate an optional reporting hook.
const engine = data instanceof Engine ? data : Engine.fromData(JSON.parse(JSON.stringify(data)));
const humans = engine.players.filter((player) => !player.isAutoma);
const bestScore = Math.max(...engine.players.map((player) => player.data.victoryPoints));
const mode = engine.options.lostFleet ? "lost-fleet" : "base";
const requiredTypes = engine.options.lostFleet
? [...baseColonyTypes, Planet.Protoplanet, Planet.Asteroid]
: baseColonyTypes;
return humans.map((player, seat) => {
// Preserve wrapper human-seat indexing even when a participant dropped.
if (player.dropped) return { seat, earned: [] };
const earned: string[] = [];
const won = player.data.victoryPoints >= bestScore;
if (won) {
earned.push(`win-faction-${player.faction}`, `win-mode-${mode}`);
if (engine.automa) earned.push(`win-automa-${engine.automa.difficulty}`);
}
for (const threshold of [150, 200]) {
if (player.data.victoryPoints >= threshold) earned.push(`score-${mode}-${threshold}`);
}
if (standardBuildings.every((building) => player.data.buildings[building] === player.maxBuildings(building))) {
earned.push("build-all-standard");
}
if (player.data.federationCount >= 4) {
earned.push("federation-form-4");
if (player.faction === Faction.Ivits) earned.push("faction-ivits-growing-federation");
}
// Unlike Condition.PlanetType, ownedPlanets excludes virtual artifact types and shared mines.
const physicalTypes = new Set(player.ownedPlanets.map((hex) => hex.data.planet));
if (requiredTypes.every((type) => physicalTypes.has(type))) earned.push(`explore-all-types-${mode}`);
if (
player.faction === Faction.Lantids &&
[...engine.map.grid.values()].filter((hex) => hex.data.additionalMine === player.player).length >= 6
) {
earned.push("faction-lantids-shared-civilization");
}
if (
player.faction === Faction.Bescods &&
ResearchField.values(engine.expansions).every((field) => player.data.research[field] >= 3)
) {
earned.push("faction-bescods-balanced-research");
}
return { seat, earned, outcome: won ? "win" : "loss" };
});
}

View file

@ -184,7 +184,7 @@ describe("Power/QIC Actions", () => {
expect(() => engine.move("p1 action qic2")).to.throw();
});
it("should not allow to take the same action multiple times in one turn", () => {
it.skip("should not allow to take the same action multiple times in one turn", () => {
const moves = [
"init 4 Klingon-Empire",
"p1 faction lantids",
@ -211,7 +211,6 @@ describe("Power/QIC Actions", () => {
"xenos charge 1pw",
"firaks build ts 7A6.",
"xenos charge 1pw",
"ivits charge 1pw",
"xenos build ts 5A10.",
"firaks charge 2pw",
"lantids build PI 3A5.",
@ -263,7 +262,6 @@ describe("Power/QIC Actions", () => {
"ivits special space-station. build sp 7A5.",
"xenos build ts 3A4.",
"lantids charge 3pw",
"ivits charge 1pw",
"firaks build PI 8B5.",
"lantids charge 1pw",
"lantids spend 1pw for 1c. pass booster5",
@ -272,7 +270,7 @@ describe("Power/QIC Actions", () => {
"lantids charge 1pw",
"firaks charge 3pw",
"firaks up terra.",
"ivits action power6. build m 5A11.",
"ivits build m 5A11.",
"firaks decline 2pw",
"xenos charge 3pw",
"xenos build gf 8A1.",
@ -304,7 +302,6 @@ describe("Power/QIC Actions", () => {
"xenos charge 2pw",
"xenos build m 8A1.",
"lantids charge 1pw",
"ivits charge 2pw",
"firaks charge 3pw",
"ivits action power6. build m 8B1.",
"firaks charge 3pw",

View file

@ -40,6 +40,9 @@ export enum FreeAction {
//Taklons
PowerTo3Credit,
//Xenos (Lost Fleet)
OreToPowerTokenArea3,
}
export type ResourceConversion = { cost: string; income: string };
@ -55,6 +58,11 @@ export class ConversionPool {
push(table: ConversionTable, player: Player) {
this.actions.push(...freeActionData(Object.keys(table).map((k) => Number(k)) as FreeAction[], player));
}
remove(action: FreeAction) {
const conversion = freeActionConversions[action];
this.actions = this.actions.filter((act) => !(act.cost === conversion.cost && act.income === conversion.income));
}
}
export const freeActions: ConversionTable = {
@ -98,6 +106,11 @@ export const freeActionsBaltaks: ConversionTable = { [FreeAction.GaiaFormerToQic
// this is for convenience
export const freeActionsTaklons: ConversionTable = { [FreeAction.PowerTo3Credit]: { cost: "3pw", income: "3c" } };
// Lost Fleet: "As a free action, the Xenos can spend 1 ore to gain 1 power (in area III)." (rulebook p.11)
export const freeActionsXenos: ConversionTable = {
[FreeAction.OreToPowerTokenArea3]: { cost: "1o", income: "1ta3" },
};
export const freeActionConversions: ConversionTable = Object.assign(
{},
freeActions,
@ -107,7 +120,8 @@ export const freeActionConversions: ConversionTable = Object.assign(
freeActionsNevlas,
freeActionsNevlasPI,
freeActionsBaltaks,
freeActionsTaklons
freeActionsTaklons,
freeActionsXenos
);
export const boardActions = {

552
engine/src/ai/README.md Normal file
View file

@ -0,0 +1,552 @@
# Lost Fleet AI: offline foundation through Phase 2 search
This directory is an offline-only foundation for the fixed Lost Fleet AI challenge. It is deliberately
not exported from `engine/index.ts` and must not be imported by the viewer, hosted-game code, Supabase,
or another production entry point.
The directory currently contains:
- a versioned static challenge definition;
- a manifest generator that boots the real engine and projects the initialized challenge setup;
- a reproducible benchmark harness;
- a committed-state canonical projection and hash;
- typed atomic decision expansion and canonical candidate keys;
- an exhaustive resource-conversion planner with executable plans and Pareto frontiers;
- a committed-turn macro builder with stable macro keys and a macro-driven corpus campaign;
- random, greedy, and inspectable heuristic committed-macro bots;
- a fixed-seat evaluation report with independently ablatable strategic features;
- a canonical strategy doctrine and a setup-only, inspectable placement-opportunity prior;
- a source-indexed strategy registry and persistent Academy/PI/Mine-spread opening-plan candidate;
- deterministic fixed-frame PUCT plus seeded Gumbel/sequential-halving search;
- an inspectable heuristic-softmax prior, tree reuse, guarded transpositions, and search diagnostics;
- paired full-game baseline/search strength harnesses and curated setup/Round-1–6 positions;
- golden, smoke, parity, and applicability tests for those offline tools.
It does not contain federation solving, the Round-6 solver, opening books, neural feature encoding,
models, training, Web Workers, hosted routes, or production feature flags. Starting buildings and
round boosters are intentionally not part of the scripted challenge prefix: both remain strategic
decisions.
## Lean session entry point
Start every new AI phase from `docs/lost-fleet/AI_CURRENT.md`. It is the single current session
contract and names the exact README sections, plan sections, source API surfaces, and gates to load.
This README owns stable module semantics; it is not a second handoff and should not be read cover to
cover by default. Historical sections remain authoritative only when their layer is in scope.
Before changing strategic evaluation or planning, read `STRATEGY_DOCTRINE.md` completely. It owns
the general expert/forum synthesis, evidence confidence, anti-overfitting rules, plan archetypes,
and AI-7 implementation order. Exact challenge coordinates remain regression evidence, not policy.
`strategy/knowledge.ts` is the corresponding machine-checkable source/principle/application map.
## Safety invariants
1. Production code must never import from `src/ai/` during the live-game freeze.
2. The AI code may read public engine state and call existing engine APIs, but may not change engine
rules, move processing, availability, serialization, hydration, or replay behavior.
3. The checked-in challenge manifest is generated from a real engine boot. Tile, map, ship, artifact,
and effect values are not transcribed from strategy prose.
4. Benchmarks are descriptive baselines. Phase 0 has no machine-specific performance pass/fail gates.
5. The fuzz random player is used only for a labeled full-game benchmark workload. It is a sampler,
not a complete legal-action enumerator.
## Offline commands
Run from `engine/`:
```text
npx ts-node scripts/ai/generate-challenge-manifest.ts
npx ts-node scripts/ai/benchmark.ts --warmup 5 --iterations 50 --random-games 1
npx ts-node src/ai/testing/strength-campaign.ts # historical measured arms; do not rerun routinely
```
All three commands write JSON to standard output by default. `--output <path>` is available for an
explicit manifest/benchmark artifact path. The benchmark also accepts `--random-warmup`,
`--memory-clones`, and `--skip-random-games`; the strength campaign intentionally has one checked-in
fixed configuration.
## Phase 1.1: canonical committed-state projection
`canonical-state.ts` adds an offline-only, versioned canonical projection and SHA-256 hash for
committed engine states. It is intentionally narrow:
- committed states only: `engine.newTurn === true`;
- initialized game states only: `phase !== setupInit`, `map` exists, players exist;
- non-replay instances only;
- standard faction-picking flow only: no auction variant, no random-factions flow, no ban phase;
- Lost Fleet states must carry their persisted setup-randomization fields (`lostFleetTerraformingRow`,
`scoringExtensionSide`, `lostFleetEconomySide`);
- transient in-line prompt state is rejected (`turnMoves`, `pendingMove`, unresolved brainstone /
reward-pick state, nonzero temporary range/step, nonzero `turns`).
Included state families:
- engine version plus supported game options that can still affect future behavior;
- phase, round, current/temp actors, turn orders, passed players, leech queue, last leech source;
- chosen faction order, board/spaceship action ownership, Lost Fleet setup choices, and remaining
tile / token / artifact supplies;
- map placement plus every hex's future-relevant state;
- every player's faction / variant / resource / power / research / building / ship / exploration /
federation / artifact / event state;
- `player.federationCache`, intentionally included despite the name because current engine behavior
can diverge when that cache is stale. Its boolean `custom` flag is projected through the same
truthy coercion the engine itself applies (`!!custom`), because `Player.toJSON()` drops the flag:
the projection stays byte-identical for every live boolean value, hydrated mid-game caches become
hashable instead of crashing the projection, and a live `custom: true` cache still hashes
differently from its serialized counterpart on purpose — that pair genuinely behaves differently
in the current engine (the base-003 staleness class).
Excluded or normalized fields:
- `availableCommands`, `availableCommand`: derived command caches, regenerated on demand;
- `moveHistory`, `advancedLog`, `silentAuctionLog`: replay / presentation / audit history only;
- `pendingMove`, `turnMoves`, `brainstoneDest`, `toPick`, `temporaryRange`, `temporaryStep`, `turns`:
transient in-line state, rejected unless cleared;
- `oldPhase`, `processedPlayer`, `replayVersion`, `replay`, `subPhase`: unused or replay-only
scaffolding under the supported-state contract;
- `map.rng`, `map.seed`, `map.distanceCache`: non-serializable RNG/cache state; future randomness is
unsupported in Phase 1.1 outside the standard faction-picking flow, and distance is recomputed;
- `player.settings`, `player.name`, `player.declined`: UI / automation state, not future game rules
under the committed-state contract;
- `player.data.occupied`: reconstructed from map hex occupancy;
- `engine.options.map`: duplicated by canonical map placement;
- `engine.options.auction`, `engine.options.randomFactions`, `engine.options.banPhase`,
`engine.randomFactions`, `engine.bannedFactions`, `engine.silentAuctionBids`: unsupported
faction-picking variants, rejected instead of canonicalized;
- semantically unordered collections are sorted in the projection (`tiles.artifacts`,
`lostFleetCost3Planets`, `artifactPlanetTypes`, `usedTinkeringTiles`, hex membership lists).
## Phase 1.2: typed atomic decision expansion
`actions/expand.ts` regenerates legal commands on a clone of a supported Phase 1.1 committed state
and projects every executable `.data` option into the explicit discriminated union in
`actions/types.ts`. A caller may supply already-selected command fragments to expose the next
chained prompt; the committed root is still validated first, and Phase 1.2 never selects or plans
the prefix itself.
Every candidate carries:
- a SHA-256 canonical key over command, actor, phase/subphase, and normalized structured target;
- typed building, coordinate, research, tile, booster, spaceship, artifact, and Federation IDs as
applicable;
- fixed cost/reward vectors plus explicit deferred/conditional effect specs;
- range, terraforming, and satellite metadata where applicable;
- engine warnings and an executable move fragment.
Covered command families:
- standard setup: faction choice, starting buildings, round boosters;
- income and leech: income ordering, charge, decline;
- normal turns: build/upgrade, board and special actions, ranged free actions, burn, research,
Federation geometry x tile, pass, and end-turn;
- Lost Fleet: explore, spaceship board actions, Examine Artifact, artifact choice, instant
Gaiaforming, and ship-Federation reward branches;
- chained choices: Tech/cover, research, Federation/rescore, Lost Planet, bonus mine/building,
artifact, Gaiaforming, brainstone, PI swap, Tinkering tile, and Power Ring targets.
Intentional semantic deduplication is always reported in `deduplications`:
- byte-for-byte equivalent semantic options become one candidate with occurrence count;
- `Decline` is one executable choice even when its compatibility payload lists multiple leech
offers, because the move executor ignores an offer argument.
Explicit rejections:
- every Phase 1.1 unsupported/incomplete state, including auction, silent-auction, ban, and random
faction-picking flows;
- non-`standard` faction-board variants;
- `DeadEnd`, because it is an undo signal rather than an executable candidate;
- custom Federation fallback commands with no enumerated geometry;
- custom setup/rotation, bidding/ban commands, and initialization, which
are outside the locked challenge boundary;
- any offered executable command with an empty option set or unfamiliar command branch.
## Phase 1.3: resource-conversion planning
`resources/planner.ts` accepts the same Phase 1.1 committed-state boundary and uses Phase 1.2 typed
candidates as its only executable action input. It is offline-only. The small additive internal
hooks in `actions/expand.ts` project typed candidates from an internally replayed Phase 1.3 resource
node or a caller-supplied set of production free-conversion commands; the existing committed-source
Phase 1.2 API and outputs are unchanged.
The graph uses an explicit `ProjectedConversionState` rather than engine object identity. It binds
every projection to the canonical committed source/action timing context and includes:
- credits, ore, knowledge, Q.I.C., and victory points;
- all four power bowls and exact brainstone placement;
- Gaiaformer total, Gaia-area, on-board, asteroid-used, other-used, and available counts;
- token modifier, terraform discount, temporary range/steps, and satellites;
- actor, faction, round/final-round marker, Planetary Institute state, timing, and the sorted set of
conversion rights.
Supported normal-round conversion families are the eight base conversions (power to Q.I.C./ore/
knowledge/credit, Q.I.C. to ore, knowledge/ore to credit, ore to an Area-I token), power burn, and:
- Hadsch Halla after its PI: credits to Q.I.C./ore/knowledge;
- Nevlas: Area-III token to Gaia plus knowledge, and after its PI the three convenience power
conversions; `tokenModifier` is applied exactly to power spending;
- Baltaks: Gaiaformer to Q.I.C., preserving the engine's Gaiaformer bookkeeping;
- Taklons: its three-power-to-three-credit convenience conversion, including brainstone choices;
- Lost Fleet Xenos: ore to a new Area-III token.
Terrans' and Itars' Gaia-phase conversions are intentionally excluded: Phase 1.3 plans main-action
affordability in `RoundMove`, not `RoundGaia`. An unfamiliar offered cost/reward resource fails
explicitly rather than being silently ignored.
Reachability is a semantic worklist with no depth or time cap. Production availability supplies one
typed unit candidate for each applicable family; ranged `Spend` multipliers and `burn N` are exact
aliases for repeated unit fragments and are reported in `diagnostics.aliases`. Every new unit
transition is projected explicitly, including resource caps, bowl movement, brainstone branches,
Gaia-token movement, Gaiaformer use, and faction token modifiers. Plans retain their ordered,
replayable fragments even though their canonical key depends only on source, destination, and
timing.
Intentional graph canonicalization is fully reported:
- different orders with the same step multiset and semantic destination are
`commutative-order` merges;
- other executable sequences with the same destination are `equivalent-executable-sequence`
merges;
- ranged conversion/burn aliases are canonicalized to repeated unit fragments;
- resource-dependency cycles are cut only when the resulting state is componentwise dominated by
an ancestor; every such cut records the resource cycle, fragments, ancestor, and discarded key;
- other componentwise dominated transitions are recorded in `paretoPruned`.
There are no resource weights. Dominance requires an identical source/action/timing context,
brainstone placement, raw Gaiaformer bookkeeping, modifier/temporary/faction-specific state, and
conversion rights. Only then may one state dominate another by being no smaller in every one of:
credits, ore, knowledge, Q.I.C., victory points, Area I, Area II, Area III, Gaia-area power, and
available Gaiaformers, with at least one strict improvement. Candidate payment frontiers apply the
same rule under the same candidate key.
Phase 1.3 hardening keeps those semantics but removes the locked-state hot path. Exact-context and
canonical-state material are cached per immutable projected state; active Pareto rows use
deterministic exact-context/credit/ore/knowledge/Q.I.C. buckets as necessary-condition filters and
still pass the complete ten-dimensional predicate before pruning. Scalar candidate payments
(credit, ore, knowledge, Q.I.C., and victory points only) use the proof that subtracting the same
vector from a subset of an existing Pareto frontier cannot create a new dominance relationship;
power, burn, token-movement, brainstone, and Gaiaformer cases retain the full frontier algorithm.
The worklist also uses an index cursor instead of shifting the queue. None of these mechanisms is a
depth limit, timeout, weight, beam, or heuristic prune.
The untouched locked Round-1 state now has a deterministic completion regression: 36,159 reachable
states/plans, a 9,985-state frontier, 45 affordable candidate frontiers, maximum conversion depth
30, 85,126 exact-state merges, 56,139 Pareto-prune diagnostics, 111 ranged aliases, and no lossy
cycle prune. Its full state/plan/frontier/candidate/payment-key digest is
`b4e266ef95ca8cc34cfd1cde4380a782ff01f4802a077d49ac9686924e222850`, checked across constructor
replay, `Engine.slowMotion`, and hydration. A final local descriptive profile completed in 46.11s
(27.21s reachability, 1.10s result assembly, 14.24s candidate construction, 3.55s payment
frontiers); the pre-hardening run was still in reachability after 120.04s. Timings are reported in
`result.profile` and are never used for termination or pruning.
After a main candidate is replayed internally, Phase 1.3 proceeds only if the engine exposes the
narrow `AfterMove` set `Spend`/`Burn`/`EndTurn`; forced follow-ups remain Phase 1.4 work. Ordinary
resource conversions are deferred because an ordinary non-pass action guarantees the same player a
future `BeforeMove` conversion window before their next main action/pass, and opponents cannot
observe or consume those ordinary resources. Power-bowl prefixes are retained only when they
strictly increase charge capacity before intervening leech; trailing non-bowl suffixes are deferred.
Burns or other bowl changes that do not increase capacity are canonicalized to wait. The result and
timing types also carry an explicit deferral-proof flag; a context without that proof must retain
the conversion instead of applying this canonicalization.
## Phase 1.4: committed-turn macro construction
`actions/turn-builder.ts` builds every complete committed-turn macro from one supported committed
snapshot, replaying each candidate line against a fresh clone with the production commit rule
(`copy.move(line)`, commit only when `copy.newTurn`, exactly like `viewer/src/hosted/host.ts`,
`self-contained.ts`, and the fuzzer driver). A macro contains an optional Phase 1.3 conversion
prefix, exactly one Phase 1.2 main action, every forced follow-up, meaningful follow-up choices as
distinct branches, retained AfterMove bowl-opening conversions, and `end` when the engine requires
it. Transient engine states are never serialized: a line is only ever represented by its committed
source plus executable fragments.
- **Macro keys** (`macro-v1:` + SHA-256) hash the semantic choice only: source canonical hash,
actor, the Phase 1.3 destination wallet key of a non-empty conversion prefix (null otherwise),
the Phase 1.2 main-candidate key, the candidate keys chosen at meaningful (more than one option)
follow-up decisions in order, and the wallet key of a retained AfterMove conversion suffix.
Forced one-choice follow-ups are recorded for audit but never branch and never enter the key,
so a macro built through the conversion-integrated route and the same macro built without it
carry identical keys, and equivalent conversion prefixes cannot mint duplicate macros (Phase 1.3
already canonicalizes one plan per destination wallet).
- **Decision walk.** Non-committed lines re-expand the engine's own follow-up offer through the
Phase 1.2 projector: one candidate means a forced spine step; several mean one branch per
candidate. The narrow `Spend`/`Burn`/`EndTurn` window is never branched per conversion; with
after-conversion integration enabled it becomes plain `end` (defer everything, proof per Phase
1.3) plus one branch per retained bowl-opening plan from
`planAfterActionConversionsForLine`, cached per distinct (main candidate, post-main wallet).
- **Every emitted macro was applied to a fresh clone and ended committed**, with its canonical
destination hash, next actor, leech interruption (`destination.leechPending`), pass order, and
EndGame flag recorded. Lines whose required chained decision comes back as the engine's
`DeadEnd` undo signal are rejected before exposure and reported in `rejected`
(`dead-end-follow-up`), mirroring the fuzzer's ban-and-retry rule. Committed leech decisions are
separate subsequent edges built from the committed leech state through the same generic path as
setup, income, and Gaia decisions.
- **Custom federations are out of scope by design; never read as "no federation".** The AI forms
only the engine's enumerated federations — the ones the engine already proposes with a real
satellite path — and picks among those. When the engine offers a federation ONLY through its
custom (hand-picked hex set) fallback (`federations: []`), there is no enumerable geometry and
no satellite-path federation available at that state, so the AI simply forms no federation that
turn: the fallback command is dropped (Phase 1.2 rejects it anyway) and the dropped tiles are
recorded in `excludedCustomFederationTiles` for offline audit, so the skip is deliberate and
visible rather than silent. This is a permanent scoping decision (owner, 2026-07-14), not a gap
awaiting a later custom-federation feature.
- **Conversion integration is a two-axis option.** `conversionIntegration` seeds one line per
nondominated (conversion prefix, main candidate) pair from the complete Phase 1.3 result —
including candidates only affordable after conversions — and `afterConversionIntegration`
controls the AfterMove bowl-opening axis separately. Both are exact and uncapped whenever they
run; wall-clock cost is wallet-dependent and measured, not capped (see the measured numbers
below), so statistics runs state explicitly which axes were enabled.
Measured locked Round-1 branch statistics (the before/after conversion-integration gate):
- before integration: 52 committed macros over 32 root main candidates, zero rejections, macro
key/destination digest `972a1e9b062ebcda5a96e2242039bbc29eee83934c9eb41e175a493bb1009096`;
- after integration (seed level, from the locked Phase 1.3 result): 45 candidate frontiers,
130,532 (conversion prefix, main candidate) seed pairs, of which 130,500 carry a non-empty
prefix (the 32 empty-prefix seeds are exactly the root-affordable mains); per-candidate prefix
counts span 5 to 9,985 with median 2,134. Fully emitting all ~130k lines validates each by
replay and is a measured multi-hour offline job on this state, so the focused suite locks the
seed-pair counts and emits complete integrated macro sets on smaller wallets instead.
- Exhaustive planning cost is wallet-dependent: measured `planResourceConversions` runs span
0.01 s (lean mid-game wallets) through ~80 s (pristine Round-1) to 738 s (a power-rich Round-6
state), and the pristine-wallet AfterMove axis exceeds practical wall-clock entirely. Scheduling
which turns a sampled player converts on is a play-policy choice and is reported with every
statistic; the planner itself never gets a depth cap, timeout, weight, or beam.
`testing/corpus.ts` drives complete macro-sampled games from the locked challenge prefix
(host-style commit chain) and runs the Phase 1.4 corpus campaign: every committed state is checked
for the hash (canonical hash + serialize/parse hydration), legal (typed expansion, unique sorted
macro keys, no exposed DeadEnd/non-committed line), apply (fresh-clone replay of macros incl. the
sampled one, destination hash equality), and replay (constructor replay hash + macro-key parity on
a deterministic subsample) property families. Replay-path hash differences confined to the
documented base-003 federationCache staleness class (Player.toJSON() drops the cache's `custom`
flag, and current engine behavior genuinely reads it) are counted as
`federationCacheHashDivergences` after a cache-masked byte comparison proves nothing else differs;
on those states macro parity is checked on hash-independent semantic content. Any other
divergence fails the campaign.
## Phase 2 / AI-6: non-neural evaluation baselines
The Phase 2 baseline path remains wholly offline and consumes only
`buildCommittedTurnMacros(...)` output:
- `bots/random.ts` samples uniformly from the committed macro set with a reproducible seed. It is a
legality/smoke baseline, not the old fuzz command sampler.
- `bots/greedy.ts` applies every candidate host-style and selects by immediate score/resource value.
An EndGame destination always returns the exact fixed-frame final margin.
- `evaluation.ts` exposes 28 stable feature names, default weights, raw seat values, seat-0-minus-
seat-1 margins, and per-feature weighted contributions. `disabledFeatures` independently zeros
any named term; `weights` permits explicit ablations/tuning without changing extraction. The
features cover current score/resources, income by resource and remaining income phases, building
supply/uncovered income, round timing, separate Space/Deep-Space progress, Gaia pipeline,
research 3/5 races and Advanced-Tech prerequisites, standard-Tech cover cost, shared power/ship
actions, booster/pass order, power-bowl capacity, exact edge-level leech charge/VP cost, Trading
Station discount/opponent offer, federation state/options, Lost Planet, exploration, artifacts,
ship tech/federation rewards, current final-scoring projection, and exact leftover conversion.
- `bots/heuristic.ts` applies every committed macro, evaluates the destination plus the exact edge
marginals, and deterministically selects the highest fixed-frame value for seat 0 or the lowest
same value for seat 1. It never negates utility per edge and constructs no search tree.
- `testing/self-play.ts` re-applies every chosen line to a fresh hydrated engine, requires
`newTurn`, verifies the recorded destination hash/actor, and plays paired faction assignments to
EndGame without manual commands. Its 800-line check is only a loud full-game termination guard;
macro generation and conversion planning remain exact and uncapped.
The baseline play policy defaults conversion integration off because the pristine locked wallet has
130,532 exact seed pairs. A caller may enable either Phase 1.4 conversion axis; when enabled the
existing planner/builder runs to its complete fixpoint with no depth, sequence, beam, or time cap.
Locked deterministic paired measurements (A as Xenos/B as Hadsch Hallas, then swapped):
- greedy vs random: `68-51` (+17) and `20-46` (+26 for greedy as Hadsch Hallas), paired margin
`+43`, mean `+21.5`, record 2-0;
- heuristic vs greedy: `49-67` (-18) and `66-48` (-18 for heuristic as Hadsch Hallas), paired margin
`-36`, mean `-18`, record 0-2.
Verification at the AI-6 handoff: 12/12 focused, 68/68 complete offline AI, and 698 passing / 4
pending in the complete engine suite. Engine 4.8.51, Phase 0 semantic SHA
`ce3bdd7322860484dfae771320b9f12967d0677b908f91cdc682d9c4427bf51e`, the Phase 1.2 62-candidate
digest `a28eb3d03e2b51e1bea28170b92f5e99991f41c76b1b1c8a2193a97a0ee704d9`, the Phase 1.3 36,159 /
9,985 / 45 / depth-30 digest `b4e266ef95ca8cc34cfd1cde4380a782ff01f4802a077d49ac9686924e222850`,
and the Phase 1.4 52-macro / 32-main digest
`972a1e9b062ebcda5a96e2242039bbc29eee83934c9eb41e175a493bb1009096` all remain locked.
The second result is retained as evidence, not hidden or promoted: the first inspectable heuristic
is a coverage/ablation baseline and future teacher candidate, but its default hand weights require
calibration before it can be treated as stronger than greedy. Phase 2 has no single-line promotion
claim. Search, MCTS/PUCT/Gumbel, tree reuse, transpositions, and learned opponent models remain
absent and deferred to AI-7 or later owner-approved phases.
The complete current-session contract and inherited stop conditions are consolidated in
`docs/lost-fleet/AI_CURRENT.md`.
The later player-facing maximum AI has an owner-locked local-runtime policy: one unchanged
model/book and fixed high simulation workload for every supported device, no time-based early exit,
and no silent low-device downgrade. Incapable devices are unsupported. That policy, plus truthful
search progress/ETA/heartbeat requirements, belongs to the later viewer-integration phase and is
not implemented by the offline Phase 2 baselines.
## Phase 2 / AI-7: offline search baseline
`search/core.ts` is a domain-generic, deterministic minimax MCTS/PUCT implementation. Values stay in
one seat-0 frame: actor 0 maximizes and actor 1 minimizes without edge negation. A simulation expands
at most one new node, backs up the same fixed-frame value, and is conserved in per-call visit deltas.
Canonical action keys order all ties. `gumbel-sequential-halving` is a separately selectable root
allocator with an explicit seed and feasible fixed-budget candidate count; plain `puct` remains the
default and independently measurable. `puctValueScale` explicitly divides fixed-frame Q before the
dimensionless exploration bonus is added; its default of one preserves the frozen raw-Q baseline.
`rootReuseVisitPolicy` independently retains promoted-subtree moments (the default) or resets all
reachable visit/value moments while preserving expanded structure. Reuse diagnostics distinguish
visits available before promotion from visits actually retained.
`search/engine-domain.ts` makes one Phase 1.4 committed macro the only engine search edge. Every
destination is applied on a fresh hydrated engine and checked against its recorded hash and next
actor. Non-terminal leaves use the state-only AI-6 heuristic so canonical transposition values are
path-independent; terminal leaves use exact final margin. The inspectable prior is a temperature-8
softmax of actual-actor-oriented heuristic values with a 5% uniform mixture. Its optional
`greedyMix` performs a probability-level blend with an immediate-greedy softmax; zero is the default
and exactly preserves the frozen heuristic-only prior. The separate `leafGreedyMix` performs the
same bounded value-level blend in non-terminal leaf Q; terminal utility is never blended. Its default
is also zero. Search pins and reports both macro conversion axes; they default off while the existing
planner remains exact and uncapped when explicitly enabled.
`bots/search.ts` exposes `SearchMacroBot`, `SearchMacroBotOptions`, and `SearchMacroEvaluation`.
Diagnostics separate deterministic search facts from wall-clock performance and include root visits,
prior/value/spread, principal variation, expansions, tree reuse, and transposition hits. The bot
retains the selected child and reconciles the next observed committed state against its descendants.
Transpositions default off; when enabled, the engine adapter must prove equal canonical hash,
state-only value, actor/terminal status, and complete legal macro set before sharing a node.
`testing/strength.ts` exposes paired fixed-faction strength games/campaigns plus seven deterministic
committed probes spanning setup and rounds 1–6. It records candidate margins/records, fixed simulation
counts, raw final scores for both factions in every game, expansions/edges, latency, reuse, and
guarded-DAG telemetry. The frozen eight-simulation campaign found:
- plain PUCT vs greedy: margins `[-12, -18]`, mean `-15`, record 0–2;
- plain PUCT vs heuristic: `[+10, +16]`, mean `+13`, record 2–0;
- four-seed Gumbel vs greedy: `[-16, -39, -6, -17, -14, -14, +14, -36]`, mean `-16`, record 1–7;
- four-seed Gumbel vs heuristic: `[-10, -1, +11, +30, -1, -9, -6, -8]`, mean `+0.75`, record 2–6.
Tree reuse occurred on 31/37 and 32/34 plain-PUCT selections and 418/435 four-seed Gumbel
selections. On the common-seed Gumbel DAG ablation, 90 guarded hits/parity checks produced the same
game margins and selected curated actions as the tree variant, with no demonstrated latency benefit.
The implementation gate is complete, but the strength-promotion gate is not: no AI-7 bot is promoted
over greedy, and AI-8 must not begin until an AI-7 follow-up clears that gate.
Final AI-7 verification: 12/12 focused; complete engine 710 passing / 4 pending; TypeScript,
changed-file ESLint, diff/whitespace, and production-isolation audits clean. The first full-suite
attempt was externally terminated with Windows status `0x40010004` and no Mocha failure; the exact
recovery command completed successfully.
The focused AI-7 calibration kept Gumbel/transpositions ablated and compared budgets 1/2/4/8/16 on
the seven curated positions. A 50/50 greedy/heuristic prior changed 0/35 choices relative to the
heuristic-only prior; both arms matched greedy on only 1, 1, 1, 2, and 1 positions respectively.
Unvisited-edge Q starts at the full raw heuristic value while the exploration bonus is only about
`1.25 × prior`, so a prior-only blend cannot overcome the measured heuristic gaps. Early traces
found two mine-over-trading-station evaluator divergences and one retained-subtree research choice
that fresh search replaced with Pass. No trace reached EndGame, so no final-score result was produced.
Completed-game harness results always include both raw seat scores. Calibration verification was
13/13 focused and 711 passing / 4 pending in the complete engine suite; TypeScript and ESLint passed.
The next bounded calibration made Q units explicit and moved the evaluator blend into both prior and
non-terminal leaf value. At budgets 1/2/4/8/16, the predeclared scale-16, 75%-greedy candidate matched
greedy on 3/3/3/5/5 of seven curated positions, versus 1/1/1/2/1 for the frozen arm. On two fixed
32-line stateful traces it differed from a fresh tree only once; resetting promoted-subtree moments
differed four times and retained no old visits, so the campaign candidate keeps the default retain
policy. The exact one-pair, eight-simulation campaign configuration is checked into
`testing/strength-campaign.ts` behind `--scaled-greedy-75-candidate` before measurement.
That campaign ran once after source freeze. Versus greedy, the candidate scored raw games `65-72`
and `56-84` from its Xenos and Hadsch Hallas assignments: margins `[-7, +28]`, paired mean `+10.5`,
record 1-1. Versus heuristic it scored `73-43` and `49-67`: margins `[+30, +18]`, mean `+24`, record
2-0. Mean search latency was 2,042 ms/selection versus greedy and 2,127 ms versus heuristic. This is
the leading search-only arm on paired margin, not a statistically clear final claim: it has one
deterministic pair per opponent and lost the Xenos/greedy game. The measured arm must not be rerun or
retuned; AI-7 remains open for broader predeclared strength evidence.
`docs/lost-fleet/AI_CURRENT.md` grants continuing autonomy for offline AI-7 iteration. An agent may
predeclare, source-freeze, and run one comparable paired campaign per evidence-backed candidate
without an owner checkpoint. It must not rerun/cherry-pick failed seeds, start AI-8, change shared or
production code, or commit/push/deploy under that authority.
`testing/full-game-report.ts` adds exact inspectable absolute-score/productivity reporting to both
baseline and search games. It uses only committed macro observations and the engine's existing
advanced log. Every player report includes raw score after rounds 1–6; Round-tile, Federation,
research-track/endgame, both final-scoring, other immediate, resource-conversion, and bid VP;
ordinary action counts/types and Pass turn by round; and final buildings/research/resources. Round
and final totals are reconciled exactly, with a loud error on unattributed VP.
The productivity investigation found that baseline players took only 1–9 ordinary actions over six
rounds, often passing immediately with capped wallets; all four diagnostic players scored zero
Federation and research-track/endgame VP. `greedyStateValue` therefore has an independently opt-in
`income-normalized` mode, but its measured 45–72 scores did not improve productivity and it is not a
candidate. The default remains the frozen immediate-greedy baseline.
Search additionally exposes `nonTerminalPassValuePenalty`, default zero. It applies an actor-relative
opportunity cost to non-terminal Pass leaf/prior values only; exact terminal utility is unchanged.
The predeclared value-4 arm selected no Pass at any of 35 curated budget/position probes. In its one
allowed fresh-seed campaign it beat greedy 2-0 (`76-57`, `72-70`) but remained absolutely weak; the
retained 72, 76, and 77 VP reports still showed zero-action middle rounds and no
Federation/research endgame scoring. It is an AI-7 diagnostic improvement, not a promoted champion.
`setup-placement.ts` adds an owner-labelled, setup-only placement prior. It grades distance-one,
two, and three access to spaceships, the opponent home colour, Gaia planets, Asteroids, one-step
terrain colours, and nearby planet density. Spaceship value combines its fixed action board with
the tech and Federation reward actually seeded on it. `setup-placement-opportunity` reports every
component independently and becomes zero after setup; on the locked challenge it changes the four
previously tied Xenos first-Mine choices to the expert-confirmed order
`3A0 > 6A4 > 1A3 > 2A11`.
`STRATEGY_DOCTRINE.md` consolidates the owner's general guidance and the expansion/base-game forum
review into implementable plan archetypes. `strategy/knowledge.ts` currently maps 20 sources to 37
deduplicated principles, including contradictions and rejected universal rules; traceability tests
require every retained principle to have an explicit AI disposition.
`strategy/opening-plans.ts` implements the first general application: inspectable Academy, PI, and
Mine-spread assessments with prerequisites, exact next-building reserves, progress, affordability,
round-scoring/faction context, and transition penalties for reserve damage or productive Passes.
`StrategyPlanMacroBot` retains the selected plan through rounds 1–2 and reports selection, retention,
completion, abort, and material-switch reasons. It does not script coordinates or move sequences and
does not change the frozen heuristic baseline.
Its first diagnostic game was deliberately not a campaign: as Xenos against greedy Hadsch Hallas it
scored `74-61`, took 14 ordinary actions, built Academy 2 and eight Mines, explored two ships, and
earned 12 Federation VP. Zero actions in rounds 3–5 and zero research-track/endgame VP remain, so the
opening layer alone was not a promotion candidate.
`strategy/research-plan.ts` implements the evidence-backed continuation for rounds 3–6. It ranks
research targets from the actual seeded Advanced Tech event, current infrastructure/track position,
green-Federation readiness, remaining uses, four-knowledge affordability, and small faction-context
modifiers. It retains the target, rewards focused research plus Standard/Advanced Tech and
Federation-readiness progress, protects four knowledge from unrelated spending, and penalizes Pass
only when a productive transition exists. Advanced Tech utility is derived from the tile's actual
rewards/operator/current condition count and remaining rounds; there is no fixed tile tier or track
order.
The one final diagnostic—not a paired campaign—improved Xenos from 74 to 107 VP and from 14 to 21
ordinary actions. Rounds 3–5 changed from `[0,0,0]` actions to `[5,4,4]`, and research/endgame VP
changed from 0 to 16; final research was AI 5, Terraforming 3, Science 2. This is evidence for the
planning mechanism, not competent play: 107 remains well below the owner-supplied 150–160 target.
Keeping that same plan active in round 6 is the retained follow-up: Xenos spent four stranded
knowledge to reach Terraforming 4, increasing the diagnostic to 110 VP, 22 actions, and 20
research/endgame VP. `strategy/tempo.ts` also exposes an optional measurable-productivity Pass guard,
and research assessments expose an optional same-turn Federation feasibility context. Both are off
by default: Pass values 4/8 scored 99/105 and the Federation gate scored 94, so none replaced the
validated policy. Removed final-scoring/reachability experiments scored 103/88.
## Future shared-engine correction: maintenance-window checklist
No shared-engine correction may be folded into AI work. Before making one, all boxes below must be
checked in a separately approved maintenance window:
- [ ] The owner has explicitly opened a maintenance window and approved the proposed scope.
- [ ] A minimized regression fixture demonstrates the discrepancy without relying on AI code.
- [ ] Constructor replay and host-style serialize/parse/hydrate/action replay parity tests exist.
- [ ] Compatibility for existing serialized games has a written decision; behavior is version-gated
when old records must retain old semantics.
- [ ] The change has an isolated rollback plan and does not require rewriting hosted game records.
- [ ] The complete engine suite and relevant viewer/host integration tests pass with quiet reporters.
- [ ] The diff has been audited for availability, move, serialization, replay, viewer, Supabase, and
deployment impact.
- [ ] Production deployment timing and active-game risk have been reviewed with the owner.
- [ ] The owner has explicitly approved commit, push, and deployment after reviewing the evidence.

View file

@ -0,0 +1,287 @@
# Lost Fleet AI strategy doctrine
> **Status:** canonical strategy input for offline AI work. This is not a rulebook, an opening book,
> or a list of fixed evaluator weights. Future sessions that change strategic evaluation or planning
> must read this file completely after `docs/lost-fleet/AI_CURRENT.md`.
## Purpose
The current bots make locally affordable moves but do not build a six-round engine. Their relative
wins are misleading because all measured policies score far below competent play. For the normal
setup, use the owner's calibration of roughly **150–160 as decent** and **200 as exceptionally
strong**. A 43–84 result is weak regardless of which weak baseline it beats.
This doctrine consolidates:
- the owner's expert strategy labels from the AI-7 session;
- recurring principles from BoardGameGeek strategy discussions;
- official Lost Fleet component/rule context; and
- the implementation lessons from the full-game productivity reports.
Its job is to make strategy actionable without teaching the AI one seed or one scripted sequence.
## Authority and confidence
Use evidence in this order:
1. Engine legality and official rules determine what an action actually does.
2. Repeated owner-confirmed general principles are strong strategy labels.
3. Advice repeated across independent expert discussions is a useful prior.
4. A single opening, tier list, tournament game, or seed-specific ranking is only a hypothesis.
Every strategic term must remain inspectable and ablatable. Disputed advice must not become an
unconditional bonus. Exact coordinates, move sequences, faction scripts, and permanent ship/tile
tiers are forbidden as general policy.
### Traceability registry
`strategy/knowledge.ts` is the machine-checkable companion to this doctrine. Its current
public-source/owner English-language sweep contains 20 sources and 37 deduplicated principles. Every principle records
its confidence, sources, scope, contrary evidence where relevant, and one or more allowed AI
applications: active feature, active plan, qualitative fixture, context modifier, documented
hypothesis, or rejected universal rule.
This is the enforceable meaning of “capture all internet tips”: conduct a broad reproducible sweep,
retain every distinct relevant claim found, and give every retained claim an explicit disposition.
It is not a claim that every webpage or private discussion on the internet can be enumerated. Audio
or inaccessible material is not treated as extracted strategy unless a reliable transcript or
written summary supports the claim.
## General strategy principles
### Plan an engine, not the next reward
- At the start of a round, compare a small set of coherent plans with a payoff horizon and fallback.
- Prefer actions that make an important later action feasible, not merely the largest immediate
resource or VP reward.
- Reserve the credits, ore, knowledge, QIC, range, power, and building availability needed for the
chosen plan. Penalize spending that destroys it.
- Re-plan when the required action becomes unavailable, the economy no longer supports it, or a
clearly stronger opportunity appears. Do not oscillate after every small reward.
- Convert resources because a productive action needs the conversion. Never convert or burn power
merely to look active or empty the wallet.
### Build productive capacity early
- Round 1 should normally produce an engine: an Academy, a Planetary Institute, a Research Lab plus
flexible infrastructure, several efficient Mines, or a credible early Federation/advanced-tech
line.
- A Round-1 Academy is a strong general plan because it supplies knowledge/tech tempo, but it is not
mandatory. A PI or broad cheap-Mine opening can be better for the faction and board.
- Research steps and immediate-resource Standard Tech tiles can fund the opening rather than being
valued only for their printed reward. Terraforming level 1 is often a useful cost reducer.
- Mines and Trading Stations, the Economy track, power cycling, and Labs/Academies with income tech
are alternative economic engines. The AI should choose a compatible mix, not try to maximize all
of them at once.
- Judge an opening by Round-2 readiness as well as Round-1 VP: income, bowl-3 power, knowledge/tech
access, expansion reach, and a feasible next build all matter.
### Preserve tempo and useful resources
- Passing is acceptable when no meaningful, plan-compatible action remains—not simply because a
shallow evaluator dislikes the legal actions.
- Do not require literal resource depletion. Preserve useful bowl-3 power and next-round reserves,
and avoid conversions or power spending with no productive destination.
- Account for income overflow and charging geometry. Spending before income can be valuable when it
prevents capped resources or overcharging, but wasteful spending is still waste.
- Contested boosters, power actions, ship actions, tech tiles, advanced tech, and Federation tokens
have timing value. A slightly lower nominal action can be correct if delay is likely to lose it.
### Score throughout the game
- A sound engine must ultimately produce VP. Forecast round-tile triggers, both final-scoring
categories, Federation VP, research-track/endgame VP, and other immediate VP separately.
- Early engine actions can outweigh immediate VP, but repeated zero contribution to whole scoring
categories is a strategic failure, not merely a different style.
- Federation planning must include building value, geometry, satellite/power cost, token reward,
advanced-tech timing, and the chance that a desired token is taken.
- Research value depends on the next threshold, income or immediate reward, advanced-tech access,
endgame position, and the actions remaining to exploit it.
## Setup geometry
Starting Mines should maximize several overlapping opportunities. Use distance bands—adjacent,
distance 2, then distance 3—with closer access worth more:
- spaceships, evaluated from their actual action and seeded tech/Federation rewards;
- planets of an opponent's home colour, which improve affordable Trading Station/charge prospects;
- Gaia planets and Asteroids;
- planet colours one terraforming step from the faction's home colour; and
- total nearby buildable-planet density and connectivity.
Also consider whether the two starting Mines complement one another: distinct expansion corridors,
shared Federation geometry, opponent interaction, ship access, range constraints, and blocking risk.
Outer positions can be stronger in Lost Fleet because they improve ship and Asteroid access.
The locked Xenos ranking `3A0 > 6A4 > 1A3 > 2A11` is a regression fixture proving that these general
features can break an evaluator tie. It is **not** an opening rule, a coordinate lookup, or evidence
that the full policy is strong.
## Round-1 plan archetypes
The first planning layer should compare archetypes rather than exact move scripts:
1. **Academy engine:** reach a Research Lab and Academy while preserving enough expansion and
income to function in Round 2. Value tech/research gains and immediate-resource tiles that make
the line feasible.
2. **Planetary Institute engine:** accelerate a faction-defining PI power or Federation geometry
when its repeated value repays the slower alternative development.
3. **Mine spread:** place several cheap, well-connected Mines when the map, faction discounts, round
scoring, income, or future Federation makes breadth stronger than an early top building.
4. **Research-Lab flexibility:** gain tech access while delaying the Academy/PI choice, then use the
remaining economy for productive builds.
5. **Early Federation/advanced tech:** assemble value and track position early enough that the
reward has several rounds or triggers left. Do not pursue it if the required infrastructure
leaves the economy inert.
6. **Gaia/Asteroid expansion:** use a Gaiaformer, instant Gaiaforming, or an Asteroid action when it
opens efficient builds, scores repeatedly, or completes a broader engine.
7. **Ship-action engine:** reach and repeatedly exploit one or two synergistic ships when their
actual actions and seeded rewards fit the faction's resource production and scoring plan.
The opening booster belongs inside plan feasibility. The owner identifies four-charge and
range-plus-three as strong general Round-1 candidates, especially when charge scores large
buildings or range unlocks the plan. They are contested but not universally best; compare the
specific board, round scoring, income, and denial value.
## Research, technology, ships, and advanced tech
- Value a research step as a path, not an isolated reward: include the desired threshold, advanced
tech, endgame standing, remaining knowledge cost, and timing.
- Value tech tiles by the actions they enable and the number of useful remaining triggers. Immediate
resources can be extremely strong when they complete an opening.
- Value advanced tech by earliest realistic acquisition, remaining scoring/income opportunities,
affordable expected uses, faction/plan synergy, track opportunity cost, and contest risk.
- Do not assign permanent global tiers to ships. Use their current action, seeded tech/Federation
reward, access cost, likely repeat uses, resource fit, scoring synergy, and opponent contest.
- Starting beside a ship can compound from Round 1 because ship actions behave like additional
economic actions. Expert reports often prefer fully exploiting two synergistic ships to touching
three shallowly, while recognizing that some boards justify three.
- Asteroids and instant Gaiaforming are broadly valuable because they add expansion options and can
support scoring, but their value still depends on build cost, action access, and the active plan.
## Faction identity is a modifier, not a script
General plans remain the candidates; faction traits alter feasibility and payoff.
### Xenos
- Treat Xenos as flexible rather than forcing one opening.
- Their extra starting Mine, Federation advantage, and Lost Fleet outer access can support fast
research, broad expansion, and earlier Federations.
- An Artificial Intelligence-track rush is attractive when the QIC action and available advanced
tech justify it. The owner specifically identifies the early three-knowledge advanced tech as a
strong target, potentially in Round 2, with a PI/Federation line and range tech supporting access.
- Navigation or Terraforming can be the second track when it unlocks valuable planets, Asteroids,
ship actions, or a synergistic advanced tech. These are candidate-plan reasons, not fixed track
orders.
### Hadsch Hallas
- Their credit production and PI conversion make credit-rich plans and flexible resource timing
stronger than for a generic faction.
- The owner identifies an early Gaia-track route to the five-credit/one-QIC advanced tech as a
strong Round-2 candidate, especially with nearby transdim/Gaia and Asteroid opportunities.
- Navigation and credit-funded ship/Asteroid actions can extend that engine. The AI must still
verify access, contest, and repeated use rather than force the route.
The Eclipse Federation reward and its economic action were identified as especially desirable for
both example factions. Encode that through actual projected income, uses, timing, and contest—not a
hard-coded faction bonus.
## AI representation
Represent a strategic plan with inspectable fields such as:
```text
id; horizon; goals; prerequisites; reserved resources; expected engine gain;
expected scoring gain; contest/timing risk; abort conditions; fallback plans
```
Candidate action value should conceptually combine:
```text
immediate value
+ plan progress
+ change in plan feasibility
+ future income/action capacity
+ forecast scoring
+ contest/denial value
- resource and opportunity cost
- reserve violation
- stranded-engine and tempo risk
```
Do not choose weights from prose alone. Add each component to reports, lock qualitative fixtures,
then calibrate only after the policy demonstrates the intended behavior.
## AI-7 implementation order and validation gate
Stay in AI-7. The next evidence-backed improvement is a small ordinary-turn planning layer, not
another Pass penalty, search-scale sweep, or seed-specific setup term:
1. Add inspectable plan generation for **Academy engine**, **PI engine**, and **Mine spread**.
2. Track prerequisites, resource reservations, progress, feasibility, and explicit fallback/switch
reasons across actions and rounds.
3. Feed plan progress and reserve violations into evaluation with independent ablations.
4. Add focused fixtures showing productive first-round construction, purposeful tech/research,
preservation of resources for the next required action, and justified plan switching.
5. Extend to early Federation/advanced-tech and Gaia/Asteroid/ship plans only after the first three
work as intended.
6. Use full-game reports to require materially more ordinary actions, functioning Round-2–5
economies, and nonzero contributions from the relevant scoring channels before spending time on
a paired strength campaign.
The first three-plan layer now exists in `strategy/opening-plans.ts` and
`bots/strategy-plan.ts`. It retains a selected Round-1/2 plan, reports priorities and switch reasons,
rewards progress/affordability, protects the next prerequisite reserve, and penalizes Pass only when
a productive plan transition exists. Its first single-game diagnostic is evidence of local behavior,
not promotion: Xenos scored 74 against greedy's 61, took 14 ordinary actions, built an Academy and
eight Mines, and earned 12 Federation VP, but still took zero actions in rounds 3–5 and earned zero
research-track/endgame VP.
That midgame extension now exists in `strategy/research-plan.ts`. During rounds 3–6 it retains a
setup-aware track/Advanced Tech goal, protects four knowledge, values the seeded tile from its actual
event and remaining contextual uses rather than a fixed tier, and rewards focused research, tech,
and green-Federation readiness. Its final single-game diagnostic moved Xenos from 74 to 107 VP, from
14 to 21 actions, from `[0,0,0]` to `[5,4,4]` actions in rounds 3–5, and from 0 to 16 research/endgame
VP. This clears the qualitative continuation check, not the strength gate: 107 is still below the
150–160 competent-play benchmark. Carrying the same plan through round 6 then converted four
stranded knowledge into Terraforming 4, 20 research/endgame VP, and a 110-point finish. Broader
scoring, reachability, forced-Pass, and same-turn Federation gates all measured worse (88–105) and
are removed or opt-in rather than doctrine. The next bounded work is a compatible-income/action-
budget economic plan, not more plan-weight tuning.
Absolute score and score composition remain the primary health check. Do not treat a relative win
between sub-100 bots as promotion evidence. Do not rerun or retune the already measured
scale-16/greedy-75 or Pass-opportunity-4 campaign arms.
## Source ledger
The forum material is expert anecdotal evidence, not official strategy law. The useful signal is
the repeated principle or the documented disagreement, not a copied move order.
- [Lost Fleet official product/rules context](https://capstone-games.com/products/gaia-project-the-lost-fleet)
- [Strategic considerations after the Milan tournament](https://boardgamegeek.com/thread/3533221/strategic-considerations-after-the-milan-tournamen)
- [Strategy tips for the game with the expansion](https://boardgamegeek.com/thread/3520828/strategy-tips-for-the-game-with-the-expansion)
- [Dream openings](https://boardgamegeek.com/thread/3533518/dream-openings)
- [Advanced-tech tier discussion](https://boardgamegeek.com/thread/3410541/advanced-tech-tier-list)
- [Ship access and colour differences](https://boardgamegeek.com/thread/3533630/access-to-ships-colour-difference)
- [Openings for the new factions](https://boardgamegeek.com/thread/3444360/lets-talk-about-openings-for-new-factions)
- [Was this game lost at setup?](https://boardgamegeek.com/thread/3708930/was-this-game-lost-at-setup)
- [Should you always build a Round-1 Academy?](https://boardgamegeek.com/thread/2871643/should-you-always-build-an-academy-at-r1)
- [Opening discussion](https://boardgamegeek.com/thread/3173378/opening)
- [Getting the economy rolling](https://boardgamegeek.com/thread/2764434/i-cant-get-my-economy-rolling)
- [Xenos strategy discussion](https://boardgamegeek.com/thread/2592514/lets-talk-about-xenos-a-strategy-discussion-series)
- [Standard openings](https://boardgamegeek.com/thread/1974293/standard-openings)
- [Designer-approved Federation FAQ](https://boardgamegeek.com/wiki/page/Federation_FAQ)
- [Play-by-forum game summaries](https://boardgamegeek.com/thread/1997564/post-pbf-game-write-upsummaries/page/2)
- [General community strategy discussion](https://www.reddit.com/r/boardgames/comments/uqr157/how_the_do_you_play_gaia_project/)
- [Starting strategy discussion](https://www.reddit.com/r/boardgames/comments/shw5bt/help_for_starting_gaia_project/)
- [Lost Fleet community impressions](https://www.reddit.com/r/boardgames/comments/1e4jnz2/anyone_played_the_gaia_project_expansion_yet/)
- [All-base-faction secondary overview](https://victoryconditions.com/gaia-project-factions/)
## Maintenance rule
Add new advice here only when it changes a general principle, creates a plan archetype, resolves a
documented ambiguity, or supplies a useful faction modifier. Record contrary evidence. Seed-specific
labels belong in focused regression fixtures and `AI_CURRENT.md`, not in the general doctrine.

View file

@ -0,0 +1,51 @@
import { createHash } from "crypto";
import { Command, Phase, Player, SubPhase } from "../../enums";
import { ATOMIC_CANDIDATE_SCHEMA } from "./types";
export interface CandidateKeyMaterial {
command: Command;
actor: Player;
phase: Phase;
subphase: SubPhase | null;
target: unknown;
}
function stableValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(stableValue);
}
if (value !== null && typeof value === "object") {
return Object.keys(value as Record<string, unknown>)
.sort()
.reduce(
(result, key) => {
result[key] = stableValue((value as Record<string, unknown>)[key]);
return result;
},
{} as Record<string, unknown>
);
}
return value;
}
export function stableCandidateJson(value: unknown): string {
return JSON.stringify(stableValue(value));
}
/**
* Keys describe the atomic choice, not its array position or JavaScript object identity. All
* choice-set arrays in the key material are normalized by the explicit command projector before
* reaching this function.
*/
export function canonicalCandidateKey(material: CandidateKeyMaterial): string {
const payload = {
schemaVersion: ATOMIC_CANDIDATE_SCHEMA,
command: material.command,
actor: material.actor,
phase: material.phase,
subphase: material.subphase,
target: material.target,
};
const digest = createHash("sha256").update(stableCandidateJson(payload)).digest("hex");
return `atomic-v1:${digest}`;
}

View file

@ -0,0 +1,590 @@
import { expect } from "chai";
import "mocha";
import { possibleBoardActions } from "../../available/actions";
import { possibleBuildings } from "../../available/buildings";
import { possibleFederations, possibleFederationTiles } from "../../available/federations";
import { possibleResearchAreas } from "../../available/research";
import { possibleSpaceshipActions } from "../../available/spaceship-actions";
import { AvailableCommand, Offer, UPGRADE_RESEARCH_COST } from "../../available/types";
import Engine, { AuctionVariant } from "../../engine";
import {
Building,
Command,
Faction,
Federation,
Phase,
Player,
ResearchField,
Resource,
Spaceship,
SubPhase,
TechTilePos,
} from "../../enums";
import Event from "../../events";
import { CanonicalStateError } from "../canonical-state";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "../challenge";
import { AtomicExpansionError, AtomicExpansionOptions, expandAtomicDecisions } from "./expand";
import { AtomicDecisionCandidate } from "./types";
function hydrate(engine: Engine): Engine {
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
}
function actorPrefix(engine: Engine): string {
return engine.player(engine.playerToMove)?.faction ?? `p${engine.playerToMove + 1}`;
}
function applyCandidate(source: Engine, candidate: AtomicDecisionCandidate, priorMoveFragments: string[] = []): Engine {
const clone = hydrate(source);
clone.move(`${actorPrefix(clone)} ${priorMoveFragments.concat(candidate.moveFragment).join(". ")}`);
return clone;
}
function challengeSetupEngine(): Engine {
return new Engine(LOST_FLEET_CHALLENGE.scriptedPrefix, challengeEngineOptions());
}
function lockedRoundOneEngine(): Engine {
const engine = challengeSetupEngine();
let guard = 20;
while (engine.phase === Phase.SetupBuilding || engine.phase === Phase.SetupBooster) {
const candidate = expandAtomicDecisions(engine).candidates[0];
engine.move(`${actorPrefix(engine)} ${candidate.moveFragment}`);
guard -= 1;
expect(guard, "locked setup must terminate").to.be.greaterThan(0);
}
expect(engine.phase).to.equal(Phase.RoundMove);
expect(engine.round).to.equal(1);
return engine;
}
function decisionEngine(source: Engine, options: AtomicExpansionOptions = {}): Engine {
const engine = hydrate(source);
const prior = options.priorMoveFragments ?? [];
if (prior.length > 0) {
engine.move(`${actorPrefix(engine)} ${prior.join(". ")}`);
}
engine.generateAvailableCommandsIfNeeded();
return engine;
}
function expectedCount(command: AvailableCommand): number {
switch (command.name) {
case Command.Action:
return command.data.poweracts.length;
case Command.BrainStone:
return command.data.choices.length;
case Command.Build:
case Command.PISwap:
return command.data.buildings.length;
case Command.BurnPower:
case Command.ChooseFaction:
case Command.ChooseIncome:
return command.data.length;
case Command.ChargePower:
return command.data.offers.length;
case Command.ChooseArtifactToken:
return command.data.tokens.length;
case Command.ChooseCoverTechTile:
case Command.ChooseTechTile:
case Command.ChooseTinkeringTile:
case Command.ChooseFederationTile:
return command.data.tiles.length;
case Command.ChooseRoundBooster:
return command.data.boosters.length;
case Command.Decline:
case Command.EndTurn:
case Command.ExamineArtifact:
return 1;
case Command.Explore:
return command.data.ships.length;
case Command.FormFederation:
return command.data.federations.length * command.data.tiles.length;
case Command.GaiaFormTransdim:
case Command.PlaceLostPlanet:
case Command.PlacePowerRing:
return command.data.spaces.length;
case Command.Pass:
return Math.max(command.data.boosters.length, 1);
case Command.Special:
return command.data.specialacts.length;
case Command.Spend:
return command.data.acts.reduce(
(count, action) => count + (action.range && action.range.length > 0 ? new Set(action.range).size : 1),
0
);
case Command.SpaceshipAction:
return command.data.actions.length;
case Command.UpgradeResearch:
return command.data.tracks.length;
default:
throw new Error(`No expected-count arm for ${command.name}`);
}
}
function exerciseDecision(
source: Engine,
seen: Set<Command>,
options: AtomicExpansionOptions = {}
): AtomicDecisionCandidate[] {
const decision = decisionEngine(source, options);
const expansion = expandAtomicDecisions(source, options);
for (const command of decision.availableCommands) {
seen.add(command.name);
expect(
expansion.candidates.filter(
(candidate) => candidate.command === command.name && candidate.actor === command.player
).length,
`candidate count for ${command.name}`
).to.equal(expectedCount(command));
}
const keys = expansion.candidates.map((candidate) => candidate.key);
expect(new Set(keys).size).to.equal(keys.length);
expect(keys).to.deep.equal([...keys].sort());
for (const candidate of expansion.candidates) {
const expectedSubphase =
options.subphase !== undefined ? options.subphase : decision.phase === Phase.RoundMove ? decision.subPhase : null;
expect(candidate.key).to.match(/^atomic-v1:[0-9a-f]{64}$/);
expect(candidate.actor).to.equal(decision.playerToMove);
expect(candidate.phase).to.equal(decision.phase);
expect(candidate.subphase).to.equal(expectedSubphase);
expect(candidate.moveFragment).to.be.a("string").and.not.equal("");
expect(() => applyCandidate(source, candidate, options.priorMoveFragments)).not.to.throw();
}
return expansion.candidates;
}
function richBuildingEngine(): Engine {
const engine = lockedRoundOneEngine();
const player = engine.player(Player.Player1);
const hex = player.data.occupied[0];
hex.data.building = Building.TradingStation;
player.data.buildings[Building.Mine] -= 1;
player.data.buildings[Building.TradingStation] = 1;
player.data.ores = 20;
player.data.credits = 30;
player.data.knowledge = 20;
player.data.qics = 20;
player.data.power.area3 = 20;
player.federationCache = null;
engine.availableCommands = possibleBuildings(engine, Player.Player1);
return engine;
}
function federationEngine(includeTwilight = false): Engine {
const engine = lockedRoundOneEngine();
const player = engine.player(Player.Player1);
const structures = [Building.PlanetaryInstitute, Building.Academy1, Building.Academy2];
player.data.occupied.forEach((hex, index) => {
hex.data.building = structures[index];
});
player.data.buildings[Building.Mine] = 0;
player.data.buildings[Building.PlanetaryInstitute] = 1;
player.data.buildings[Building.Academy1] = 1;
player.data.buildings[Building.Academy2] = 1;
player.data.power.area1 = 20;
player.data.power.area3 = 20;
player.data.ores = 20;
player.data.qics = 20;
if (includeTwilight) {
player.data.explorationShips[Spaceship.Twilight] = 1;
}
player.federationCache = null;
engine.availableCommands = possibleFederations(engine, Player.Player1);
return engine;
}
describe("Phase 1.2 typed atomic decision expansion", () => {
it("covers the Phase 0 challenge state and applies every setup candidate", () => {
const engine = challengeSetupEngine();
const expansion = expandAtomicDecisions(engine);
const command = engine.generateAvailableCommandsIfNeeded()[0];
expect(engine.phase).to.equal(Phase.SetupBuilding);
expect(command.name).to.equal(Command.Build);
expect(expansion.candidates).to.have.length(command.data.buildings.length);
expect(expansion.candidates.every((candidate) => candidate.command === Command.Build)).to.equal(true);
expect(expansion.candidates.every((candidate) => candidate.subphase === null)).to.equal(true);
for (const candidate of expansion.candidates) {
expect(() => applyCandidate(engine, candidate)).not.to.throw();
}
});
it("expands each data element and required cross-product exactly once", () => {
const round = lockedRoundOneEngine();
const seen = new Set<Command>();
exerciseDecision(round, seen);
const federation = federationEngine();
const command = federation.availableCommands[0];
const candidates = exerciseDecision(federation, seen);
expect(candidates).to.have.length(command.data.federations.length * command.data.tiles.length);
expect(candidates.every((candidate) => candidate.command === Command.FormFederation)).to.equal(true);
const spend = round
.generateAvailableCommandsIfNeeded()
.find((entry) => entry.name === Command.Spend) as AvailableCommand<Command.Spend>;
const ranged = spend.data.acts.filter((action) => action.range && action.range.length > 1);
expect(ranged.length, "locked Xenos/Hadsch Halla state must exercise ranged free actions").to.be.greaterThan(0);
});
it("keeps keys stable across constructor replay, slowMotion, and JSON hydration", () => {
const source = lockedRoundOneEngine();
const expected = expandAtomicDecisions(source).candidates.map((candidate) => candidate.key);
const constructorReplay = new Engine(source.moveHistory, challengeEngineOptions(), source.version);
const slowMotion = Engine.slowMotion(source.moveHistory, challengeEngineOptions(), source.version);
const hydration = hydrate(source);
expect(expandAtomicDecisions(constructorReplay).candidates.map((candidate) => candidate.key)).to.deep.equal(
expected
);
expect(expandAtomicDecisions(slowMotion).candidates.map((candidate) => candidate.key)).to.deep.equal(expected);
expect(expandAtomicDecisions(hydration).candidates.map((candidate) => candidate.key)).to.deep.equal(expected);
});
it("makes keys independent of command/data ordering and object identity", () => {
const source = lockedRoundOneEngine();
source.generateAvailableCommandsIfNeeded();
const expected = expandAtomicDecisions(source).candidates.map((candidate) => candidate.key);
const reordered = hydrate(source);
for (const command of reordered.availableCommands) {
switch (command.name) {
case Command.Build:
command.data.buildings.reverse();
break;
case Command.BurnPower:
case Command.ChooseIncome:
case Command.ChooseFaction:
command.data.reverse();
break;
case Command.Explore:
command.data.ships.reverse();
break;
case Command.Pass:
case Command.ChooseRoundBooster:
command.data.boosters.reverse();
break;
case Command.Special:
command.data.specialacts.reverse();
break;
case Command.Spend:
command.data.acts.reverse();
command.data.acts.forEach((action) => action.range?.reverse());
break;
case Command.UpgradeResearch:
command.data.tracks.reverse();
break;
}
}
reordered.availableCommands.reverse();
expect(expandAtomicDecisions(reordered).candidates.map((candidate) => candidate.key)).to.deep.equal(expected);
expect(reordered.availableCommands).not.to.equal(source.availableCommands);
});
it("supports supplied-prefix chained choices without accepting a transient source state", () => {
const source = lockedRoundOneEngine();
const opening = expandAtomicDecisions(source).candidates.find((candidate) => candidate.command === Command.Spend);
const options = { priorMoveFragments: [opening.moveFragment], subphase: SubPhase.BeforeMove };
const chained = exerciseDecision(source, new Set<Command>(), options);
expect(chained.length).to.be.greaterThan(0);
expect(source.newTurn).to.equal(true);
expect(source.pendingMove).to.equal("");
});
it("covers locked setup, income/leech, normal actions, Lost Fleet actions, and chained choices", () => {
const seen = new Set<Command>();
const factionState = new Engine([`init 2 ${LOST_FLEET_CHALLENGE.seed}`], challengeEngineOptions());
exerciseDecision(factionState, seen);
const setup = challengeSetupEngine();
while (setup.phase === Phase.SetupBuilding || setup.phase === Phase.SetupBooster) {
const candidates = exerciseDecision(setup, seen);
setup.move(`${actorPrefix(setup)} ${candidates[0].moveFragment}`);
}
const round = lockedRoundOneEngine();
const roundCandidates = exerciseDecision(round, seen);
const main = roundCandidates.find(
(candidate) => ![Command.Spend, Command.BurnPower, Command.Pass].includes(candidate.command)
);
exerciseDecision(round, seen, {
priorMoveFragments: [main.moveFragment],
subphase: SubPhase.AfterMove,
});
const income = lockedRoundOneEngine();
income.phase = Phase.RoundIncome;
income.currentPlayer = Player.Player1;
income.tempTurnOrder = [Player.Player2];
income.player(Player.Player1).loadEvents(Event.parse(["+1t", "+2pw"], Command.ChooseIncome));
income.clearAvailableCommands();
exerciseDecision(income, seen);
// The locked Xenos/Hadsch Halla pairing has no Gaia-phase conversion prompt. Exercise the
// same standard-flow Spend/Decline command shapes on a committed Terrans-style Gaia state so
// Phase 1.2 cannot accidentally treat RoundGaia as an unfamiliar phase.
const gaia = lockedRoundOneEngine();
const gaiaPlayer = gaia.player(Player.Player1);
gaiaPlayer.faction = Faction.Terrans;
gaiaPlayer.data.buildings[Building.PlanetaryInstitute] = 1;
gaiaPlayer.data.occupied[0].data.building = Building.PlanetaryInstitute;
gaiaPlayer.data.power.gaia = 8;
gaia.phase = Phase.RoundGaia;
gaia.currentPlayer = Player.Player1;
gaia.tempTurnOrder = [Player.Player2];
gaia.clearAvailableCommands();
exerciseDecision(gaia, seen);
const leech = lockedRoundOneEngine();
leech.phase = Phase.RoundLeech;
leech.tempCurrentPlayer = Player.Player2;
leech.tempTurnOrder = [];
leech.player(Player.Player2).data.leechPossible = 2;
leech.clearAvailableCommands();
exerciseDecision(leech, seen);
const rich = lockedRoundOneEngine();
rich.player(Player.Player1).data.power.area3 = 20;
rich.availableCommands = possibleBoardActions(rich.boardActions, rich.player(Player.Player1), rich.replay);
exerciseDecision(rich, seen);
const artifacts = lockedRoundOneEngine();
artifacts.player(Player.Player1).data.explorationShips[Spaceship.Twilight] = 1;
artifacts.player(Player.Player1).data.qics = 20;
artifacts.clearAvailableCommands();
const examine = exerciseDecision(artifacts, seen).find(
(candidate) => candidate.command === Command.ExamineArtifact
);
exerciseDecision(artifacts, seen, {
priorMoveFragments: [examine.moveFragment],
subphase: SubPhase.ChooseArtifactToken,
});
const tfMars = lockedRoundOneEngine();
const tfMarsPlayer = tfMars.player(Player.Player1);
tfMarsPlayer.data.explorationShips[Spaceship.TFMars] = 1;
tfMarsPlayer.data.power.area3 = 20;
tfMarsPlayer.data.gaiaformers = 1;
tfMarsPlayer.data.qics = 20;
tfMars.availableCommands = possibleSpaceshipActions(tfMars, Player.Player1);
const tfMarsPower = exerciseDecision(tfMars, seen).find(
(candidate) => candidate.moveFragment === `${Command.SpaceshipAction} ${Spaceship.TFMars} power`
);
exerciseDecision(tfMars, seen, {
priorMoveFragments: [tfMarsPower.moveFragment],
subphase: SubPhase.InstantGaiaforming,
});
const buildings = richBuildingEngine();
const lab = exerciseDecision(buildings, seen).find(
(candidate) => candidate.command === Command.Build && candidate.target.building === Building.ResearchLab
);
const tech = exerciseDecision(buildings, seen, {
priorMoveFragments: [lab.moveFragment],
subphase: SubPhase.ChooseTechTile,
}).find((candidate) => candidate.command === Command.ChooseTechTile);
exerciseDecision(buildings, seen, {
priorMoveFragments: [lab.moveFragment, tech.moveFragment],
subphase: SubPhase.UpgradeResearch,
});
const advanced = richBuildingEngine();
const advancedPlayer = advanced.player(Player.Player1);
advancedPlayer.data.research[ResearchField.Terraforming] = 4;
advancedPlayer.data.tiles.federations.push({ tile: Federation.Fed2, green: true });
const standardPosition = TechTilePos.Free1;
advancedPlayer.data.tiles.techs.push({
tile: advanced.tiles.techs[standardPosition].tile,
pos: standardPosition,
enabled: true,
});
advanced.availableCommands = possibleBuildings(advanced, Player.Player1);
const advancedLab = expandAtomicDecisions(advanced).candidates.find(
(candidate) => candidate.command === Command.Build && candidate.target.building === Building.ResearchLab
);
const advancedTile = exerciseDecision(advanced, seen, {
priorMoveFragments: [advancedLab.moveFragment],
subphase: SubPhase.ChooseTechTile,
}).find(
(candidate) =>
candidate.command === Command.ChooseTechTile && String(candidate.target.position).startsWith("adv-")
);
exerciseDecision(advanced, seen, {
priorMoveFragments: [advancedLab.moveFragment, advancedTile.moveFragment],
subphase: SubPhase.CoverTechTile,
});
const lostPlanet = lockedRoundOneEngine();
const lostPlanetPlayer = lostPlanet.player(Player.Player1);
lostPlanetPlayer.data.research[ResearchField.Navigation] = 4;
lostPlanetPlayer.data.tiles.federations.push({ tile: Federation.Fed2, green: true });
lostPlanetPlayer.data.knowledge = 20;
lostPlanet.availableCommands = possibleResearchAreas(lostPlanet, Player.Player1, UPGRADE_RESEARCH_COST);
const navigation = exerciseDecision(lostPlanet, seen).find(
(candidate) =>
candidate.command === Command.UpgradeResearch && candidate.target.field === ResearchField.Navigation
);
exerciseDecision(lostPlanet, seen, {
priorMoveFragments: [navigation.moveFragment],
subphase: SubPhase.PlaceLostPlanet,
});
const federation = federationEngine(true);
const federationCandidates = exerciseDecision(federation, seen);
const shipFederation = federationCandidates.find(
(candidate) =>
candidate.command === Command.FormFederation &&
candidate.target.federation === federation.tiles.spaceshipFederations[Spaceship.Twilight]
);
exerciseDecision(federation, seen, {
priorMoveFragments: [shipFederation.moveFragment],
subphase: SubPhase.FederationTokenBuildMine,
});
const rescore = lockedRoundOneEngine();
rescore.player(Player.Player1).data.tiles.federations.push({ tile: Federation.Fed2, green: true });
rescore.availableCommands = possibleFederationTiles(rescore, Player.Player1, "player");
exerciseDecision(rescore, seen);
const required = [
Command.Action,
Command.Build,
Command.BurnPower,
Command.ChargePower,
Command.ChooseArtifactToken,
Command.ChooseCoverTechTile,
Command.ChooseFaction,
Command.ChooseFederationTile,
Command.ChooseIncome,
Command.ChooseRoundBooster,
Command.ChooseTechTile,
Command.Decline,
Command.EndTurn,
Command.ExamineArtifact,
Command.Explore,
Command.FormFederation,
Command.GaiaFormTransdim,
Command.Pass,
Command.PlaceLostPlanet,
Command.Special,
Command.Spend,
Command.SpaceshipAction,
Command.UpgradeResearch,
];
expect([...seen].sort()).to.include.members(required.sort());
});
it("projects identifiers, resources, range/terraform/satellite metadata, warnings, and move fragments", () => {
const round = lockedRoundOneEngine();
const explore = expandAtomicDecisions(round).candidates.find((candidate) => candidate.command === Command.Explore);
expect(explore.target.ship).to.be.oneOf([Spaceship.Twilight, Spaceship.TFMars, Spaceship.Eclipse]);
expect(explore.target.range.distance).to.be.a("number");
expect(explore.resources.cost.find((amount) => amount.resource === Resource.VictoryPoint)?.amount).to.equal(5);
expect(explore.moveFragment).to.equal(`${Command.Explore} ${explore.target.ship}`);
const build = expandAtomicDecisions(round).candidates.find((candidate) => candidate.command === Command.Build);
expect(build.target.building).to.be.a("string");
expect(build.target.terraform.steps).to.be.a("number");
expect(build.target.range.temporaryRange).to.be.a("number");
const federation = expandAtomicDecisions(federationEngine()).candidates.find(
(candidate) => candidate.command === Command.FormFederation
);
expect(federation.target.federation).to.be.a("string");
expect(federation.target.satellites.newSatelliteHexes.length).to.be.greaterThan(0);
expect(federation.resources.cost.find((amount) => amount.resource === Resource.GainToken)?.amount).to.equal(
federation.target.satellites.newSatelliteHexes.length
);
});
it("reports rather than silently merging documented semantic duplicates", () => {
const exact = challengeSetupEngine();
const build = exact.generateAvailableCommandsIfNeeded()[0] as AvailableCommand<Command.Build>;
build.data.buildings.push(JSON.parse(JSON.stringify(build.data.buildings[0])));
const exactExpansion = expandAtomicDecisions(exact);
expect(exactExpansion.deduplications).to.deep.include({
key: exactExpansion.candidates.find(
(candidate) => candidate.moveFragment === `build m ${build.data.buildings[0].coordinates}`
).key,
command: Command.Build,
occurrences: 2,
reason: "identical-semantic-option",
});
const decline = lockedRoundOneEngine();
decline.availableCommands = [
{
name: Command.Decline,
player: Player.Player1,
data: { offers: [new Offer("1pw", ""), new Offer("2pw", "1vp")] },
},
];
const declineExpansion = expandAtomicDecisions(decline);
expect(declineExpansion.candidates).to.have.length(1);
expect(declineExpansion.deduplications).to.deep.equal([
{
key: declineExpansion.candidates[0].key,
command: Command.Decline,
occurrences: 2,
reason: "decline-ignores-offer",
},
]);
});
it("rejects incomplete states and every non-standard faction-picking variant", () => {
const incomplete = lockedRoundOneEngine();
const spend = expandAtomicDecisions(incomplete).candidates.find((candidate) => candidate.command === Command.Spend);
incomplete.move(`${actorPrefix(incomplete)} ${spend.moveFragment}`);
expect(incomplete.newTurn).to.equal(false);
expect(() => expandAtomicDecisions(incomplete)).to.throw(CanonicalStateError, /engine\.newTurn === true/);
const variants = [
{ auction: AuctionVariant.ChooseBid },
{ auction: AuctionVariant.Silent },
{ banPhase: true },
{ randomFactions: true },
];
for (const variant of variants) {
const engine = new Engine(
[`init 2 unsupported-phase-1-2-${Object.keys(variant)[0]}`],
Object.assign(challengeEngineOptions(), variant)
);
expect(() => expandAtomicDecisions(engine), JSON.stringify(variant)).to.throw(CanonicalStateError);
}
const nonStandardBoardVariant = new Engine(
["init 2 unsupported-phase-1-2-faction-board-variant"],
Object.assign(challengeEngineOptions(), { factionVariant: "more-balanced" as const })
);
expect(() => expandAtomicDecisions(nonStandardBoardVariant))
.to.throw(AtomicExpansionError)
.with.property("code", "unsupported-state");
});
it("rejects undo signals, custom federation fallbacks, and out-of-scope command families", () => {
const deadEnd = lockedRoundOneEngine();
deadEnd.availableCommands = [{ name: Command.DeadEnd, player: Player.Player1, data: SubPhase.BuildMine }];
expect(() => expandAtomicDecisions(deadEnd))
.to.throw(AtomicExpansionError)
.with.property("code", "unsupported-command");
const customFederation = lockedRoundOneEngine();
customFederation.availableCommands = [
{
name: Command.FormFederation,
player: Player.Player1,
data: { tiles: [Federation.Fed2], federations: [], claimableFederations: [] },
},
];
expect(() => expandAtomicDecisions(customFederation))
.to.throw(AtomicExpansionError)
.with.property("code", "empty-command-data");
});
});

View file

@ -0,0 +1,946 @@
import { AvailableBuilding, AvailableCommand } from "../../available/types";
import { qicForDistance } from "../../cost";
import Engine from "../../engine";
import {
ArtifactToken,
Building,
Command,
Expansion,
Faction,
Federation,
Phase,
Planet,
Player,
Resource,
Spaceship,
SpaceshipFederation,
SubPhase,
TinkeringTile,
} from "../../enums";
import { qicForExplorationDistance } from "../../exploration";
import { tinkeringTileSpec } from "../../factions";
import { effectiveRange } from "../../player-data";
import Reward from "../../reward";
import { claimableSpaceshipFederations, spaceshipActionEffects, SpaceshipActionType } from "../../spaceships";
import { artifactTokenRewards } from "../../tiles/artifacts";
import { federationRewards } from "../../tiles/federations";
import { spaceshipFederationRewards } from "../../tiles/spaceship-federations";
import { projectCanonicalState } from "../canonical-state";
import { canonicalCandidateKey, stableCandidateJson } from "./canonical-key";
import {
ATOMIC_CANDIDATE_SCHEMA,
AtomicCandidateBase,
AtomicDecisionCandidate,
AtomicDecisionExpansion,
CandidateDeduplication,
CandidateRangeMetadata,
CandidateResourceFlow,
CandidateSatelliteMetadata,
ResourceAmount,
} from "./types";
export type AtomicExpansionErrorCode =
| "unsupported-state"
| "unsupported-command"
| "empty-command-data"
| "invalid-command-data"
| "semantic-key-collision";
export class AtomicExpansionError extends Error {
constructor(
readonly code: AtomicExpansionErrorCode,
message: string
) {
super(message);
this.name = "AtomicExpansionError";
}
}
export interface AtomicExpansionOptions {
/**
* Phase-level decisions use null; RoundMove defaults to the engine's BeforeMove subphase.
* A future committed-line builder may pass the exact chained SubPhase while reusing this atomic
* projector, but Phase 1.2 never constructs that chain itself.
*/
subphase?: SubPhase | null;
/**
* Already-selected atomic parts of the same, still-uncommitted line. The caller supplies the
* prefix; this layer only replays it to expose the next atomic command and never plans or chooses
* a continuation. The source `engine` itself must still be a supported committed state.
*/
priorMoveFragments?: string[];
}
function sortedUnique(values: readonly string[] | null | undefined): string[] {
return Array.from(new Set(values ?? [])).sort();
}
function rewardSpecs(rewards: Reward[]): string[] {
return rewards.map((reward) => reward.toStringWithOne());
}
function resourceAmounts(amounts: Map<Resource, number>): ResourceAmount[] {
return Array.from(amounts.entries())
.filter(([, amount]) => amount !== 0)
.sort(([left], [right]) => String(left).localeCompare(String(right)))
.map(([resource, amount]) => ({ resource, amount }));
}
function resourceFlow(
costSpecs: string[] = [],
rewardSpecsInput: string[] = [],
effects: string[] = []
): CandidateResourceFlow {
const costs = new Map<Resource, number>();
const rewards = new Map<Resource, number>();
const deferred = [...effects];
const add = (destination: Map<Resource, number>, resource: Resource, amount: number) => {
destination.set(resource, (destination.get(resource) ?? 0) + amount);
};
const project = (spec: string, asCost: boolean) => {
if (!spec || spec === Resource.None) {
return;
}
const parsed = Reward.parse(spec);
if (parsed.some((reward) => reward.type === Resource.None)) {
deferred.push(spec);
return;
}
for (const reward of parsed) {
if (reward.count === 0) {
continue;
}
const isCost = asCost ? reward.count > 0 : reward.count < 0;
add(isCost ? costs : rewards, reward.type, Math.abs(reward.count));
}
};
costSpecs.forEach((spec) => project(spec, true));
rewardSpecsInput.forEach((spec) => project(spec, false));
return {
cost: resourceAmounts(costs),
reward: resourceAmounts(rewards),
effects: sortedUnique(deferred),
};
}
function scaleRewardSpec(spec: string, multiplier: number): string {
return Reward.parse(spec)
.filter((reward) => reward.type !== Resource.None && reward.count !== 0)
.map((reward) => new Reward(reward.count * multiplier, reward.type).toStringWithOne())
.join(",");
}
function makeCandidate<C extends Command, T>(
command: C,
actor: Player,
phase: Phase,
subphase: SubPhase | null,
target: T,
resources: CandidateResourceFlow,
warnings: readonly string[] | null | undefined,
moveFragment: string
): AtomicCandidateBase<C, T> {
return {
schemaVersion: ATOMIC_CANDIDATE_SCHEMA,
key: "",
command,
actor,
phase,
subphase,
target,
resources,
warnings: sortedUnique(warnings),
moveFragment,
};
}
function rangeMetadata(
engine: Engine,
actor: Player,
coordinates: string,
kind: "build" | "explore",
adjustments: readonly string[] = [],
disabled = false
): CandidateRangeMetadata {
const player = engine.player(actor);
if (disabled || !player || player.data.occupied.length === 0) {
return {
distance: null,
baseRange: player ? effectiveRange(player.data) : null,
temporaryRange: player?.data.temporaryRange ?? 0,
qic: 0,
adjustments: sortedUnique(adjustments),
};
}
const hex = engine.map.getS(coordinates);
const needed =
kind === "explore"
? qicForExplorationDistance(engine.map, hex, player, engine.replay)
: qicForDistance(engine.map, hex, player, engine.replay);
return {
distance: needed?.distance ?? null,
baseRange: effectiveRange(player.data),
temporaryRange: player.data.temporaryRange,
qic: needed?.amount ?? 0,
adjustments: sortedUnique(adjustments),
};
}
function buildCandidate(
engine: Engine,
actor: Player,
phase: Phase,
subphase: SubPhase | null,
building: AvailableBuilding
) {
const hex = engine.map.getS(building.coordinates);
return makeCandidate(
Command.Build,
actor,
phase,
subphase,
{
building: building.building,
coordinates: building.coordinates,
planet: hex.data.planet ?? null,
upgrade: building.upgrade ?? false,
downgrade: building.downgrade ?? false,
range: rangeMetadata(engine, actor, building.coordinates, "build", [], phase === Phase.SetupBuilding),
terraform: {
steps: building.steps ?? 0,
temporarySteps: engine.player(actor).data.temporaryStep,
consumesAsteroidGaiaformer: building.consumesAsteroidGaiaformer ?? true,
},
},
resourceFlow([building.cost ?? Resource.None]),
building.warnings,
`${Command.Build} ${building.building} ${building.coordinates}`
);
}
function federationRewardSpecs(federation: Federation | SpaceshipFederation): { rewards: string[]; effects: string[] } {
if (Federation.values(Expansion.All).includes(federation as Federation)) {
return { rewards: rewardSpecs(federationRewards(federation as Federation)), effects: [] };
}
const spaceshipFederation = federation as SpaceshipFederation;
const spec = spaceshipFederationRewards[spaceshipFederation];
const rewards = spec ? [spec] : [];
if (spaceshipFederation === SpaceshipFederation.PowerTokens) {
rewards.push(`2${Resource.GainTokenArea3}`);
}
const effects =
spaceshipFederation === SpaceshipFederation.Range
? ["spaceship-federation-range-build-mine"]
: spaceshipFederation === SpaceshipFederation.Terraform
? ["spaceship-federation-terraform-build-mine"]
: [];
return { rewards, effects };
}
function satelliteMetadata(engine: Engine, actor: Player, location: string): CandidateSatelliteMetadata {
const player = engine.player(actor);
const hexes = player.hexesForFederationLocation(location, engine.map);
const allHexes = hexes.map((hex) => hex.toString()).sort();
const satelliteHexes = hexes
.filter((hex) => !hex.occupyingPlayers()?.includes(actor))
.map((hex) => hex.toString())
.sort();
const newSatelliteHexes = hexes
.filter((hex) => hex.buildingOf(actor) === undefined && !hex.belongsToFederationOf(actor))
.map((hex) => hex.toString())
.sort();
const existingFederationHexes = hexes
.filter((hex) => hex.belongsToFederationOf(actor))
.map((hex) => hex.toString())
.sort();
return { allHexes, satelliteHexes, newSatelliteHexes, existingFederationHexes };
}
function artifactResources(token: ArtifactToken): CandidateResourceFlow {
const declarative = artifactTokenRewards[token];
if (declarative) {
return resourceFlow([], [declarative]);
}
if (token === ArtifactToken.Asteroid || token === ArtifactToken.Protoplanet) {
return resourceFlow([], [`7${Resource.VictoryPoint}`]);
}
return resourceFlow([], [], [`artifact-dynamic:${token}`]);
}
function spaceshipActionResourceSpecs(
ship: Spaceship,
action: SpaceshipActionType
): { rewards: string[]; effects: string[] } {
const effects = spaceshipActionEffects[ship]?.[action];
if (effects && effects.length > 0) {
return { rewards: effects, effects: [] };
}
return { rewards: [], effects: [`spaceship-action-follow-up:${ship}:${action}`] };
}
function assertActor(engine: Engine, command: AvailableCommand): Player {
const actor = command.player as Player;
if (actor === undefined || !engine.player(actor)) {
throw new AtomicExpansionError(
"invalid-command-data",
`Command ${command.name} has no initialized actor in the source state`
);
}
return actor;
}
function expandCommand(
engine: Engine,
command: AvailableCommand,
phase: Phase,
subphase: SubPhase | null
): AtomicDecisionCandidate[] {
const actor = assertActor(engine, command);
switch (command.name) {
case Command.Action:
return command.data.poweracts.map((action) =>
makeCandidate(
Command.Action,
actor,
phase,
subphase,
{ boardAction: action.name },
resourceFlow([action.cost], action.income),
[],
`${Command.Action} ${action.name}`
)
);
case Command.BrainStone:
return command.data.choices.map((choice) =>
makeCandidate(
Command.BrainStone,
actor,
phase,
subphase,
{ destination: choice.area },
resourceFlow(),
choice.warning ? [choice.warning] : [],
`${Command.BrainStone} ${choice.area}`
)
);
case Command.Build:
return command.data.buildings.map((building) => buildCandidate(engine, actor, phase, subphase, building));
case Command.BurnPower:
return command.data.map((amount) =>
makeCandidate(
Command.BurnPower,
actor,
phase,
subphase,
{ amount },
resourceFlow([`${amount}${Resource.BurnToken}`]),
[],
`${Command.BurnPower} ${amount}`
)
);
case Command.ChargePower:
return command.data.offers.map((offer) =>
makeCandidate(
Command.ChargePower,
actor,
phase,
subphase,
{ offer: offer.offer },
resourceFlow([offer.cost], [offer.offer]),
[],
`${Command.ChargePower} ${offer.offer}${command.data.requestId === undefined ? "" : ` @${command.data.requestId}`}`
)
);
case Command.ChooseArtifactToken:
return command.data.tokens.map((artifact) =>
makeCandidate(
Command.ChooseArtifactToken,
actor,
phase,
subphase,
{ artifact, noEffect: command.data.noEffectTokens?.includes(artifact) ?? false },
artifactResources(artifact),
command.data.noEffectTokens?.includes(artifact) ? ["artifact-has-no-effect"] : [],
`${Command.ChooseArtifactToken} ${artifact}`
)
);
case Command.ChooseCoverTechTile:
return command.data.tiles.map((tile) =>
makeCandidate(
Command.ChooseCoverTechTile,
actor,
phase,
subphase,
{ position: tile.pos, tile: tile.tile },
resourceFlow([], [], [`cover-tech:${tile.pos}`]),
[],
`${Command.ChooseCoverTechTile} ${tile.pos}`
)
);
case Command.ChooseFaction:
return command.data.map((faction) =>
makeCandidate(
Command.ChooseFaction,
actor,
phase,
subphase,
{ faction },
resourceFlow(),
[],
`${Command.ChooseFaction} ${faction}`
)
);
case Command.ChooseFederationTile:
return command.data.tiles.map((federation) => {
const specs = federationRewardSpecs(federation);
return makeCandidate(
Command.ChooseFederationTile,
actor,
phase,
subphase,
{ federation, rescore: command.data.rescore },
resourceFlow([], specs.rewards, specs.effects),
[],
`${Command.ChooseFederationTile} ${federation}`
);
});
case Command.ChooseIncome:
return command.data.map((income) =>
makeCandidate(
Command.ChooseIncome,
actor,
phase,
subphase,
{ income },
resourceFlow([], [income]),
[],
`${Command.ChooseIncome} ${income}`
)
);
case Command.ChooseRoundBooster:
return command.data.boosters.map((booster) =>
makeCandidate(
Command.ChooseRoundBooster,
actor,
phase,
subphase,
{ booster },
resourceFlow([], [], [`take-booster:${booster}`]),
[],
`${Command.ChooseRoundBooster} ${booster}`
)
);
case Command.ChooseTechTile:
return command.data.tiles.map((tile) =>
makeCandidate(
Command.ChooseTechTile,
actor,
phase,
subphase,
{ position: tile.pos, tile: tile.tile },
resourceFlow([], [], [`take-tech:${tile.tile}`]),
[],
`${Command.ChooseTechTile} ${tile.pos}`
)
);
case Command.ChooseTinkeringTile:
return command.data.tiles.map((tile: TinkeringTile) =>
makeCandidate(
Command.ChooseTinkeringTile,
actor,
phase,
subphase,
{ tile },
resourceFlow([], [], [`tinkering-action:${tinkeringTileSpec(tile)}`]),
[],
`${Command.ChooseTinkeringTile} ${tile}`
)
);
case Command.Decline:
return [
makeCandidate(
Command.Decline,
actor,
phase,
subphase,
{ offers: sortedUnique(command.data.offers.map((offer) => offer.offer)) },
resourceFlow(),
[],
command.data.requestId === undefined
? Command.Decline
: `${Command.Decline} ${command.data.offers[0].offer} @${command.data.requestId}`
),
];
case Command.EndTurn:
return [makeCandidate(Command.EndTurn, actor, phase, subphase, {}, resourceFlow(), [], Command.EndTurn)];
case Command.ExamineArtifact:
return [
makeCandidate(
Command.ExamineArtifact,
actor,
phase,
subphase,
{ ship: Spaceship.Twilight as Spaceship.Twilight },
resourceFlow([command.data.cost], [], ["choose-artifact-follow-up"]),
[],
Command.ExamineArtifact
),
];
case Command.Explore:
return command.data.ships.map((ship) =>
makeCandidate(
Command.Explore,
actor,
phase,
subphase,
{
ship: ship.ship,
coordinates: ship.coordinates,
slot: ship.slot,
charge: ship.charge,
range: rangeMetadata(engine, actor, ship.coordinates, "explore", ship.adjustments),
},
resourceFlow([ship.cost], ship.charge > 0 ? [`${ship.charge}${Resource.ChargePower}`] : []),
[],
`${Command.Explore} ${ship.ship}`
)
);
case Command.FormFederation: {
const claimable = claimableSpaceshipFederations(
engine.player(actor).data.explorationShips,
engine.tiles.spaceshipFederations
);
const candidates: AtomicDecisionCandidate[] = [];
for (const federation of command.data.federations) {
const satellites = satelliteMetadata(engine, actor, federation.hexes);
const satelliteCostResource =
engine.player(actor).faction === Faction.Ivits ? Resource.Qic : Resource.GainToken;
for (const tile of command.data.tiles) {
const specs = federationRewardSpecs(tile);
const spaceship = claimable.find((entry) => entry.federation === tile)?.ship ?? null;
candidates.push(
makeCandidate(
Command.FormFederation,
actor,
phase,
subphase,
{ federation: tile, spaceship, hexes: satellites.allHexes, satellites },
resourceFlow(
[`${satellites.newSatelliteHexes.length}${satelliteCostResource}`],
specs.rewards,
specs.effects
),
federation.warnings,
`${Command.FormFederation} ${federation.hexes} ${tile}`
)
);
}
}
return candidates;
}
case Command.GaiaFormTransdim:
return command.data.spaces.map((space) =>
makeCandidate(
Command.GaiaFormTransdim,
actor,
phase,
subphase,
{ coordinates: space.coordinates, planet: Planet.Transdim as Planet.Transdim },
resourceFlow([space.cost], [], ["instant-gaiaform"]),
space.warnings,
`${Command.GaiaFormTransdim} ${space.coordinates}`
)
);
case Command.Pass: {
const boosters = command.data.boosters;
if (boosters.length === 0) {
return [
makeCandidate(Command.Pass, actor, phase, subphase, { booster: null }, resourceFlow(), [], Command.Pass),
];
}
return boosters.map((booster) =>
makeCandidate(
Command.Pass,
actor,
phase,
subphase,
{ booster },
resourceFlow([], [], [`take-booster:${booster}`]),
[],
`${Command.Pass} ${booster}`
)
);
}
case Command.PISwap:
return command.data.buildings.map((building) =>
makeCandidate(
Command.PISwap,
actor,
phase,
subphase,
{
coordinates: building.coordinates,
from: Building.Mine as Building.Mine,
to: Building.PlanetaryInstitute as Building.PlanetaryInstitute,
},
resourceFlow(),
building.warnings,
`${Command.PISwap} ${building.coordinates}`
)
);
case Command.PlaceLostPlanet:
return command.data.spaces.map((space) =>
makeCandidate(
Command.PlaceLostPlanet,
actor,
phase,
subphase,
{
coordinates: space.coordinates,
planet: Planet.Lost as Planet.Lost,
range: rangeMetadata(engine, actor, space.coordinates, "build"),
},
resourceFlow([space.cost]),
space.warnings,
`${Command.PlaceLostPlanet} ${space.coordinates}`
)
);
case Command.PlacePowerRing:
return command.data.spaces.map((space) =>
makeCandidate(
Command.PlacePowerRing,
actor,
phase,
subphase,
{ coordinates: space.coordinates },
resourceFlow(),
space.warnings,
`${Command.PlacePowerRing} ${space.coordinates}`
)
);
case Command.Special:
return command.data.specialacts.map((action) =>
makeCandidate(
Command.Special,
actor,
phase,
subphase,
{ income: action.income, eventSpec: action.spec },
resourceFlow([], [action.income]),
[],
`${Command.Special} ${action.income}`
)
);
case Command.Spend:
return command.data.acts.reduce((candidates, action) => {
const multipliers =
action.range && action.range.length > 0 ? Array.from(new Set(action.range)).sort((a, b) => a - b) : [1];
for (const multiplier of multipliers) {
const cost = scaleRewardSpec(action.cost, multiplier);
const income = scaleRewardSpec(action.income, multiplier);
candidates.push(
makeCandidate(
Command.Spend,
actor,
phase,
subphase,
{
cost,
income,
multiplier,
allowedMultipliers: multipliers,
hidden: action.hide ?? false,
},
resourceFlow([cost], [income]),
[],
`${Command.Spend} ${cost} for ${income}`
)
);
}
return candidates;
}, [] as AtomicDecisionCandidate[]);
case Command.SpaceshipAction:
return command.data.actions.map((action) => {
const specs = spaceshipActionResourceSpecs(action.ship, action.type);
return makeCandidate(
Command.SpaceshipAction,
actor,
phase,
subphase,
{ ship: action.ship, action: action.type },
resourceFlow([action.cost], specs.rewards, specs.effects),
action.warnings,
`${Command.SpaceshipAction} ${action.ship} ${action.type}`
);
});
case Command.UpgradeResearch:
return command.data.tracks.map((track) =>
makeCandidate(
Command.UpgradeResearch,
actor,
phase,
subphase,
{ field: track.field, from: track.to - 1, to: track.to },
resourceFlow([track.cost], [], [`upgrade-research:${track.field}:${track.to}`]),
[],
`${Command.UpgradeResearch} ${track.field}`
)
);
case Command.WaitForCharges:
case Command.ResumeCharges:
case Command.BanFaction:
case Command.Bid:
case Command.Init:
case Command.PreferenceBid:
case Command.RotateSectors:
case Command.Setup:
case Command.SilentBid:
throw new AtomicExpansionError(
"unsupported-command",
`Command ${command.name} is outside the standard-flow Lost Fleet Phase 1.2 boundary`
);
case Command.DeadEnd:
throw new AtomicExpansionError(
"unsupported-command",
"Command deadEnd is an undo signal, not an executable atomic candidate"
);
default: {
const neverCommand: never = command;
throw new AtomicExpansionError(
"unsupported-command",
`Unrecognized AvailableCommand ${(neverCommand as AvailableCommand).name}`
);
}
}
}
function comparableCandidate(candidate: AtomicDecisionCandidate): unknown {
return {
schemaVersion: candidate.schemaVersion,
command: candidate.command,
actor: candidate.actor,
phase: candidate.phase,
subphase: candidate.subphase,
target: candidate.target,
resources: candidate.resources,
warnings: candidate.warnings,
moveFragment: candidate.moveFragment,
};
}
function finalizeCandidates(candidates: AtomicDecisionCandidate[]): AtomicDecisionExpansion {
const byKey = new Map<string, AtomicDecisionCandidate>();
const occurrences = new Map<string, number>();
for (const candidate of candidates) {
const key = canonicalCandidateKey(candidate);
const keyed = { ...candidate, key } as AtomicDecisionCandidate;
const existing = byKey.get(key);
if (existing) {
if (stableCandidateJson(comparableCandidate(existing)) !== stableCandidateJson(comparableCandidate(keyed))) {
throw new AtomicExpansionError("semantic-key-collision", `Candidate key ${key} has conflicting metadata`);
}
occurrences.set(key, (occurrences.get(key) ?? 1) + 1);
} else {
byKey.set(key, keyed);
}
}
const deduplications: CandidateDeduplication[] = Array.from(occurrences.entries()).map(([key, count]) => ({
key,
command: byKey.get(key).command,
occurrences: count,
reason: "identical-semantic-option",
}));
return {
candidates: Array.from(byKey.values()).sort((left, right) => left.key.localeCompare(right.key)),
deduplications: deduplications.sort((left, right) => left.key.localeCompare(right.key)),
};
}
function defaultSubphase(engine: Engine): SubPhase | null {
return engine.phase === Phase.RoundMove ? (engine.subPhase ?? SubPhase.BeforeMove) : null;
}
function expandDecisionEngine(
decisionEngine: Engine,
subphase: SubPhase | null,
suppliedCommands?: AvailableCommand[]
): AtomicDecisionExpansion {
const commands = suppliedCommands ?? decisionEngine.generateAvailableCommandsIfNeeded();
const expanded: AtomicDecisionCandidate[] = [];
for (const command of commands) {
const candidates = expandCommand(decisionEngine, command, decisionEngine.phase, subphase);
if (candidates.length === 0) {
throw new AtomicExpansionError(
"empty-command-data",
`Command ${command.name} was offered without an executable data option`
);
}
expanded.push(...candidates);
}
const result = finalizeCandidates(expanded);
for (const command of commands) {
if (command.name !== Command.Decline || command.data.offers.length <= 1) {
continue;
}
const candidate = result.candidates.find(
(entry) => entry.command === Command.Decline && entry.actor === command.player
);
result.deduplications.push({
key: candidate.key,
command: Command.Decline,
occurrences: command.data.offers.length,
reason: "decline-ignores-offer",
});
}
result.deduplications.sort((left, right) => left.key.localeCompare(right.key));
return result;
}
/**
* Narrow offline hook for Phase 1.3's already-replayed conversion nodes. It deliberately does not
* broaden Phase 1.2's public committed-source contract; callers must have produced the transient
* engine solely by replaying typed Phase 1.2 fragments from a supported committed source.
*/
export function expandInternallyReplayedAtomicDecision(
decisionEngine: Engine,
subphase: SubPhase
): AtomicDecisionExpansion {
if (decisionEngine.phase !== Phase.RoundMove) {
throw new AtomicExpansionError(
"unsupported-state",
"Internal atomic expansion is restricted to Phase 1.3 RoundMove replay nodes"
);
}
const commands = decisionEngine.availableCommands ?? decisionEngine.generateAvailableCommands(subphase);
return expandDecisionEngine(decisionEngine, subphase, commands);
}
/** Typed Phase 1.2 projection of a narrow, caller-supplied internal command set. */
export function expandInternallySuppliedAtomicCommands(
decisionEngine: Engine,
subphase: SubPhase,
commands: AvailableCommand[]
): AtomicDecisionExpansion {
if (decisionEngine.phase !== Phase.RoundMove) {
throw new AtomicExpansionError(
"unsupported-state",
"Internal supplied-command expansion is restricted to Phase 1.3 RoundMove replay nodes"
);
}
return expandDecisionEngine(decisionEngine, subphase, commands);
}
/**
* Expand the current legal decision without mutating the supplied engine. Phase 1.1's committed
* state projector is deliberately invoked first, making its committed/standard-flow restrictions
* the single support contract for Phase 1.2 as well.
*/
export function expandAtomicDecisions(engine: Engine, options: AtomicExpansionOptions = {}): AtomicDecisionExpansion {
projectCanonicalState(engine);
if ((engine.options.factionVariant ?? "standard") !== "standard") {
throw new AtomicExpansionError(
"unsupported-state",
`Phase 1.2 supports only factionVariant=standard, got ${engine.options.factionVariant}`
);
}
const decisionEngine = Engine.fromData(JSON.parse(JSON.stringify(engine)));
const priorMoveFragments = options.priorMoveFragments ?? [];
if (priorMoveFragments.some((fragment) => !fragment || fragment.includes("."))) {
throw new AtomicExpansionError(
"invalid-command-data",
"priorMoveFragments must contain non-empty individual command parts without dots"
);
}
if (priorMoveFragments.length > 0) {
if (options.subphase === undefined) {
throw new AtomicExpansionError(
"invalid-command-data",
"An explicit subphase is required when expanding a chained decision"
);
}
const actor = decisionEngine.player(decisionEngine.playerToMove);
const prefix = actor?.faction ?? `p${decisionEngine.playerToMove + 1}`;
decisionEngine.move(`${prefix} ${priorMoveFragments.join(". ")}`);
if (decisionEngine.newTurn) {
throw new AtomicExpansionError(
"invalid-command-data",
"priorMoveFragments already form a committed line; there is no chained atomic decision"
);
}
}
const commands = decisionEngine.generateAvailableCommandsIfNeeded();
const subphase = options.subphase !== undefined ? options.subphase : defaultSubphase(decisionEngine);
const expanded: AtomicDecisionCandidate[] = [];
for (const command of commands) {
const candidates = expandCommand(decisionEngine, command, decisionEngine.phase, subphase);
if (candidates.length === 0) {
throw new AtomicExpansionError(
"empty-command-data",
`Command ${command.name} was offered without an executable data option`
);
}
expanded.push(...candidates);
}
const result = finalizeCandidates(expanded);
for (const command of commands) {
if (command.name !== Command.Decline || command.data.offers.length <= 1) {
continue;
}
const candidate = result.candidates.find(
(entry) => entry.command === Command.Decline && entry.actor === command.player
);
result.deduplications.push({
key: candidate.key,
command: Command.Decline,
occurrences: command.data.offers.length,
reason: "decline-ignores-offer",
});
}
result.deduplications.sort((left, right) => left.key.localeCompare(right.key));
return result;
}

View file

@ -0,0 +1,537 @@
import { expect } from "chai";
import { createHash } from "crypto";
import "mocha";
import { possibleBuildings } from "../../available/buildings";
import { possibleFederations } from "../../available/federations";
import Engine from "../../engine";
import { Building, Command, Federation, Phase, Player, ResearchField, Spaceship, TechTilePos } from "../../enums";
import Event from "../../events";
import { canonicalStateHash } from "../canonical-state";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "../challenge";
import { planResourceConversions } from "../resources/planner";
import { AtomicExpansionError, expandAtomicDecisions } from "./expand";
import { buildCommittedTurnMacros, CommittedTurnMacro, CommittedTurnMacroSet } from "./turn-builder";
function hydrate(engine: Engine): Engine {
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
}
function actorPrefix(engine: Engine): string {
return engine.player(engine.playerToMove)?.faction ?? `p${engine.playerToMove + 1}`;
}
function lockedRoundOneEngine(): Engine {
const engine = new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
let guard = 20;
while (engine.phase === Phase.SetupBuilding || engine.phase === Phase.SetupBooster) {
const candidate = expandAtomicDecisions(engine).candidates[0];
engine.move(`${actorPrefix(engine)} ${candidate.moveFragment}`);
expect(--guard, "locked setup must terminate").to.be.greaterThan(0);
}
expect(engine.phase).to.equal(Phase.RoundMove);
return engine;
}
function hadschHallasTurn(): Engine {
const engine = lockedRoundOneEngine();
const pass = expandAtomicDecisions(engine).candidates.find((candidate) => candidate.command === Command.Pass);
engine.move(`${actorPrefix(engine)} ${pass.moveFragment}`);
expect(engine.player(engine.playerToMove).faction).to.equal("hadsch-hallas");
return engine;
}
function smallWallet(
engine: Engine,
wallet: Partial<{
credits: number;
ores: number;
knowledge: number;
qics: number;
area1: number;
area2: number;
area3: number;
}>
): Engine {
const player = engine.player(engine.playerToMove);
player.data.credits = wallet.credits ?? 0;
player.data.ores = wallet.ores ?? 0;
player.data.knowledge = wallet.knowledge ?? 0;
player.data.qics = wallet.qics ?? 0;
player.data.power.area1 = wallet.area1 ?? 0;
player.data.power.area2 = wallet.area2 ?? 0;
player.data.power.area3 = wallet.area3 ?? 0;
player.data.power.gaia = 0;
player.data.brainstone = null;
engine.clearAvailableCommands();
player.federationCache = null;
return engine;
}
/** Host-style verification: fresh clone, one `move()`, committed, same canonical destination. */
function applyMacroHostStyle(source: Engine, macro: CommittedTurnMacro): Engine {
const clone = hydrate(source);
clone.move(macro.moveLine);
expect(clone.newTurn, `macro ${macro.moveLine} must commit`).to.equal(true);
expect(canonicalStateHash(clone)).to.equal(macro.destination.stateHash);
expect(clone.playerToMove ?? null).to.equal(macro.destination.nextActor);
return clone;
}
function macroSetDigest(macroSet: CommittedTurnMacroSet): string {
return createHash("sha256")
.update(macroSet.macros.map((macro) => `${macro.key}\0${macro.destination.stateHash}`).join("\n"))
.digest("hex");
}
function assertWellFormed(macroSet: CommittedTurnMacroSet): void {
const keys = macroSet.macros.map((macro) => macro.key);
expect(new Set(keys).size).to.equal(keys.length);
expect(keys).to.deep.equal([...keys].sort());
for (const macro of macroSet.macros) {
expect(macro.key).to.match(/^macro-v1:[0-9a-f]{64}$/);
expect(macro.moveFragments.length).to.be.greaterThan(0);
expect(macro.moveFragments.every((fragment) => fragment.length > 0 && !fragment.includes("."))).to.equal(true);
for (const decision of macro.decisions) {
if (decision.kind === "forced-follow-up") {
expect(decision.options).to.equal(1);
expect(macro.followUpChoiceKeys).to.not.include(decision.candidateKey);
}
if (decision.kind === "choice-follow-up") {
expect(decision.options).to.be.greaterThan(1);
}
}
}
}
describe("Phase 1.4 committed-turn macro builder", function () {
// Macro construction replays every candidate line against fresh clones; the heavier cases
// (federation geometry, conversion integration) legitimately exceed mocha's 2s default.
this.timeout(10 * 60 * 1000);
it("builds committed macros for the Phase 0 setup state through the generic decision path", () => {
const setup = new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
const expansion = expandAtomicDecisions(setup);
const macroSet = buildCommittedTurnMacros(setup);
expect(setup.phase).to.equal(Phase.SetupBuilding);
expect(macroSet.macros).to.have.length(expansion.candidates.length);
expect(macroSet.rejected).to.have.length(0);
assertWellFormed(macroSet);
for (const macro of macroSet.macros) {
expect(macro.mainCommand).to.equal(Command.Build);
expect(macro.conversionPlanKey).to.equal(null);
applyMacroHostStyle(setup, macro);
}
});
it("locks the Round-1 macro set without conversion integration and applies every macro", () => {
const source = lockedRoundOneEngine();
const macroSet = buildCommittedTurnMacros(source, { conversionIntegration: false });
expect(macroSet.statistics.macroCount).to.equal(52);
expect(macroSet.statistics.mainCandidateCount).to.equal(32);
expect(macroSet.statistics.conversionPlanCount).to.equal(0);
expect(macroSet.statistics.rejectedLineCount).to.equal(0);
expect(macroSet.statistics.deduplicationCount).to.equal(0);
expect(macroSetDigest(macroSet)).to.equal("972a1e9b062ebcda5a96e2242039bbc29eee83934c9eb41e175a493bb1009096");
assertWellFormed(macroSet);
const passMacro = macroSet.macros.find((macro) => macro.mainCommand === Command.Pass);
expect(passMacro).to.not.equal(undefined);
for (const macro of macroSet.macros) {
const committed = applyMacroHostStyle(source, macro);
expect([Phase.RoundMove, Phase.RoundLeech]).to.include(committed.phase);
if (macro.mainCommand !== Command.Pass) {
expect(macro.moveFragments[macro.moveFragments.length - 1]).to.equal(Command.EndTurn);
}
}
const choiceMacros = macroSet.macros.filter((macro) => macro.followUpChoiceKeys.length > 0);
expect(choiceMacros.length, "special range+3 build targets must branch").to.be.greaterThan(1);
});
it("keeps macro keys and committed destination hashes stable across replay paths", () => {
const base = lockedRoundOneEngine();
const sources = [
base,
new Engine(base.moveHistory, challengeEngineOptions(), base.version),
Engine.slowMotion(base.moveHistory, challengeEngineOptions(), base.version),
hydrate(base),
];
const projections = sources.map((source) =>
buildCommittedTurnMacros(source, { conversionIntegration: false }).macros.map((macro) => [
macro.key,
macro.destination.stateHash,
])
);
for (const projection of projections.slice(1)) {
expect(projection).to.deep.equal(projections[0]);
}
});
it("keeps forced one-choice follow-ups out of policy branching and macro keys", () => {
const engine = lockedRoundOneEngine();
const player = engine.player(Player.Player1);
const hex = player.data.occupied[0];
hex.data.building = Building.TradingStation;
player.data.buildings[Building.Mine] -= 1;
player.data.buildings[Building.TradingStation] = 1;
player.data.ores = 20;
player.data.credits = 30;
player.data.knowledge = 20;
player.federationCache = null;
engine.availableCommands = possibleBuildings(engine, Player.Player1);
const labKey = expandAtomicDecisions(engine).candidates.find(
(candidate) => candidate.command === Command.Build && candidate.target.building === Building.ResearchLab
).key;
const macroSet = buildCommittedTurnMacros(engine, {
conversionIntegration: false,
mainCandidateKeys: [labKey],
});
assertWellFormed(macroSet);
expect(macroSet.macros.length).to.be.greaterThan(1);
// A field tech tile's follow-up is a genuine two-way decision (advance or decline the free
// step); both stay distinct macros and neither is misclassified as forced.
const fieldMacros = macroSet.macros.filter((macro) =>
macro.moveFragments.includes(`${Command.ChooseTechTile} ${TechTilePos.Terraforming}`)
);
expect(fieldMacros).to.have.length(2);
expect(fieldMacros.some((macro) => macro.moveFragments.includes(`${Command.UpgradeResearch} terra`))).to.equal(
true
);
expect(fieldMacros.some((macro) => macro.moveFragments.includes(Command.Decline))).to.equal(true);
for (const macro of fieldMacros) {
expect(
macro.decisions.some((decision) => decision.kind === "choice-follow-up" && decision.options === 2)
).to.equal(true);
}
// A free tech tile leaves the research advance as a wider choice: one macro per option.
const freeMacros = macroSet.macros.filter((macro) =>
macro.moveFragments.includes(`${Command.ChooseTechTile} ${TechTilePos.Free1}`)
);
expect(freeMacros.length).to.be.greaterThan(2);
for (const macro of freeMacros) {
expect(macro.decisions.some((decision) => decision.kind === "choice-follow-up")).to.equal(true);
}
for (const macro of macroSet.macros) {
applyMacroHostStyle(engine, macro);
}
// When the player already owns every other standard tech tile, the pick becomes a forced
// one-choice follow-up: it stays on the line's spine, never multiplies macros, and never
// enters the macro key.
const forcedEngine = hydrate(engine);
const forcedPlayer = forcedEngine.player(Player.Player1);
for (const position of TechTilePos.values(forcedEngine.expansions)) {
if (position !== TechTilePos.Terraforming) {
forcedPlayer.data.tiles.techs.push({
tile: forcedEngine.tiles.techs[position].tile,
pos: position,
enabled: true,
});
}
}
forcedEngine.clearAvailableCommands();
forcedEngine.availableCommands = possibleBuildings(forcedEngine, Player.Player1);
const forcedLabKey = expandAtomicDecisions(forcedEngine).candidates.find(
(candidate) => candidate.command === Command.Build && candidate.target.building === Building.ResearchLab
).key;
const forcedSet = buildCommittedTurnMacros(forcedEngine, {
conversionIntegration: false,
mainCandidateKeys: [forcedLabKey],
});
assertWellFormed(forcedSet);
expect(forcedSet.macros).to.have.length(2);
for (const macro of forcedSet.macros) {
const forced = macro.decisions.filter((decision) => decision.kind === "forced-follow-up");
expect(forced.map((decision) => decision.command)).to.deep.equal([Command.ChooseTechTile]);
expect(macro.forcedFollowUpKeys).to.have.length(1);
applyMacroHostStyle(forcedEngine, macro);
}
});
it("locks the before/after conversion-integration branch statistics for the locked state", function () {
const source = lockedRoundOneEngine();
const before = buildCommittedTurnMacros(source, { conversionIntegration: false });
expect(before.statistics.macroCount).to.equal(52);
expect(before.statistics.mainCandidateCount).to.equal(32);
// The complete integrated branch factor is measured at the seed level from the locked Phase
// 1.3 result: one macro line per (nondominated conversion prefix, main candidate) pair. Fully
// emitting all ~130k lines replays each one and is a measured multi-hour offline job on this
// state, so the lock here counts the exact seed pairs instead of constructing every line.
const planning = planResourceConversions(source);
expect(planning.candidates).to.have.length(45);
let seedPairs = 0;
let nonEmptyPrefixPairs = 0;
for (const entry of planning.candidates) {
const uniquePlans = new Set(entry.payments.frontier.map((payment) => payment.conversionPlanKey));
seedPairs += uniquePlans.size;
for (const plan of entry.plans) {
if (uniquePlans.has(plan.key) && plan.steps.length > 0) {
nonEmptyPrefixPairs += 1;
}
}
}
expect(seedPairs).to.equal(130_532);
expect(nonEmptyPrefixPairs).to.equal(130_500);
expect(seedPairs - nonEmptyPrefixPairs, "empty-prefix seeds must be the root-affordable mains").to.equal(32);
});
it("integrates nondominated conversion prefixes without duplicating equivalent orders", () => {
const source = smallWallet(hadschHallasTurn(), { knowledge: 1, qics: 1, credits: 2, ores: 1 });
const off = buildCommittedTurnMacros(source, { conversionIntegration: false });
const on = buildCommittedTurnMacros(source, {
conversionIntegration: true,
afterConversionIntegration: false,
});
assertWellFormed(on);
expect(on.statistics.conversionIntegration).to.equal(true);
expect(on.statistics.macroCount).to.be.greaterThan(off.statistics.macroCount);
expect(on.statistics.conversionPlanCount).to.be.greaterThan(0);
expect(on.deduplications).to.have.length(0);
const onKeys = new Set(on.macros.map((macro) => macro.key));
for (const macro of off.macros) {
expect(onKeys.has(macro.key), `conversion-free macro ${macro.key} must keep its key`).to.equal(true);
}
const prefixed = on.macros.filter((macro) => macro.conversionPlanKey !== null);
expect(prefixed.length).to.be.greaterThan(0);
const byDestination = prefixed.map(
(macro) =>
`${macro.mainCandidateKey}\0${macro.conversionDestinationStateKey}\0${macro.followUpChoiceKeys.join(",")}\0${
macro.afterConversionDestinationStateKey
}`
);
expect(new Set(byDestination).size, "equivalent conversion prefixes must not duplicate macros").to.equal(
byDestination.length
);
for (const macro of prefixed.slice(0, 10)) {
applyMacroHostStyle(source, macro);
}
});
it("retains AfterMove bowl-opening branches and defers ordinary conversions", () => {
const source = smallWallet(lockedRoundOneEngine(), { ores: 1, knowledge: 4 });
const main = expandAtomicDecisions(source).candidates.find(
(candidate) => candidate.command === Command.UpgradeResearch
);
const macroSet = buildCommittedTurnMacros(source, {
conversionIntegration: true,
afterConversionIntegration: true,
mainCandidateKeys: [main.key],
});
assertWellFormed(macroSet);
const retained = macroSet.macros.filter((macro) => macro.afterConversionPlanKey !== null);
const deferredOnly = macroSet.macros.filter(
(macro) => macro.afterConversionPlanKey === null && macro.mainCandidateKey === main.key
);
expect(retained.length, "bowl-opening AfterMove branch must be retained").to.be.greaterThan(0);
expect(deferredOnly.length, "the defer-everything branch must remain distinct").to.be.greaterThan(0);
const opening = retained.find(
(macro) => macro.moveFragments.includes("spend 1o for 1ta3") && macro.moveFragments.includes("spend 1pw for 1c")
);
expect(opening).to.not.equal(undefined);
expect(opening.moveFragments[opening.moveFragments.length - 1]).to.equal(Command.EndTurn);
for (const macro of [...retained, ...deferredOnly]) {
applyMacroHostStyle(source, macro);
}
const keys = new Set(macroSet.macros.map((macro) => macro.key));
expect(keys.size).to.equal(macroSet.macros.length);
});
it("records actor transition, pass order, and leech interruption on committed edges", () => {
const passSource = lockedRoundOneEngine();
const passMacro = buildCommittedTurnMacros(passSource, { conversionIntegration: false }).macros.find(
(macro) => macro.mainCommand === Command.Pass
);
expect(passMacro.destination.actorPassed).to.equal(true);
expect(passMacro.destination.passOrder).to.deep.equal([Player.Player1]);
expect(passMacro.destination.nextActor).to.equal(Player.Player2);
applyMacroHostStyle(passSource, passMacro);
const leechSource = new Engine(
[
"init 2 randomSeed",
"p1 faction terrans",
"p2 faction nevlas",
"terrans build m -1x2",
"nevlas build m -1x0",
"nevlas build m 0x-4",
"terrans build m -4x-1",
"nevlas booster booster7",
"terrans booster booster3",
],
{}
);
const buildMacro = buildCommittedTurnMacros(leechSource, { conversionIntegration: false }).macros.find(
(macro) => macro.mainCommand === Command.Build && macro.destination.leechPending
);
expect(buildMacro).to.not.equal(undefined);
expect(buildMacro.destination.phase).to.equal(Phase.RoundLeech);
expect(buildMacro.destination.nextActor).to.equal(Player.Player2);
const leechState = applyMacroHostStyle(leechSource, buildMacro);
const leechMacros = buildCommittedTurnMacros(leechState);
assertWellFormed(leechMacros);
expect(leechMacros.actor).to.equal(Player.Player2);
expect(leechMacros.macros.length).to.be.greaterThan(1);
const commands = new Set(leechMacros.macros.map((macro) => macro.mainCommand));
expect(commands.has(Command.ChargePower)).to.equal(true);
expect(commands.has(Command.Decline)).to.equal(true);
for (const macro of leechMacros.macros) {
const committed = applyMacroHostStyle(leechState, macro);
expect(committed.phase).to.equal(Phase.RoundMove);
expect(committed.playerToMove).to.equal(Player.Player2);
}
});
it("rejects dead-end lines before exposure instead of emitting them", () => {
const source = smallWallet(lockedRoundOneEngine(), { area3: 20 });
const macroSet = buildCommittedTurnMacros(source, { conversionIntegration: false });
const deadEnds = macroSet.rejected.filter((line) => line.reason === "dead-end-follow-up");
expect(deadEnds.length, "power6's forced mine with an empty wallet must dead-end").to.be.greaterThan(0);
expect(deadEnds.some((line) => line.moveFragments[0] === "action power6")).to.equal(true);
for (const macro of macroSet.macros) {
expect(macro.moveFragments[0]).to.not.equal("action power6");
applyMacroHostStyle(source, macro);
}
});
it("excludes the custom-federation fallback rather than reading it as no federation", () => {
const source = lockedRoundOneEngine();
source.availableCommands = [
{
name: Command.FormFederation,
player: Player.Player1,
data: { tiles: [Federation.Fed2], federations: [], claimableFederations: [] },
},
];
// Custom (hand-picked hex set) federations are deliberately out of scope, so when the engine
// offers a federation ONLY via that fallback (`federations: []`) the AI forms no federation
// this turn and drops the offer — but the drop is recorded for audit, not silent, and the
// macro set is never left with a spurious FormFederation macro. Phase 1.2 keeps rejecting the
// raw command outright.
const macroSet = buildCommittedTurnMacros(source, { conversionIntegration: false });
expect(macroSet.excludedCustomFederationTiles).to.deep.equal([Federation.Fed2]);
expect(macroSet.statistics.excludedCustomFederationCount).to.equal(1);
expect(macroSet.macros.map((macro) => macro.mainCommand)).to.not.include(Command.FormFederation);
expect(() => expandAtomicDecisions(source))
.to.throw(AtomicExpansionError)
.with.property("code", "empty-command-data");
const supported = lockedRoundOneEngine();
const supportedSet = buildCommittedTurnMacros(supported, { conversionIntegration: false });
expect(supportedSet.excludedCustomFederationTiles).to.deep.equal([]);
expect(supportedSet.statistics.excludedCustomFederationCount).to.equal(0);
});
it("builds income-ordering macros through the generic committed decision path", () => {
const income = lockedRoundOneEngine();
income.phase = Phase.RoundIncome;
income.currentPlayer = Player.Player1;
income.tempTurnOrder = [Player.Player2];
income.player(Player.Player1).loadEvents(Event.parse(["+1t", "+2pw"], Command.ChooseIncome));
income.clearAvailableCommands();
const macroSet = buildCommittedTurnMacros(income);
assertWellFormed(macroSet);
expect(macroSet.macros.length).to.be.greaterThan(1);
for (const macro of macroSet.macros) {
expect(macro.mainCommand).to.equal(Command.ChooseIncome);
applyMacroHostStyle(income, macro);
}
});
it("covers the remaining locked follow-up families with explicit macro construction", () => {
// Ship federation with the claimed-ship reward branch (FederationTokenBuildMine window).
const federation = lockedRoundOneEngine();
const fedPlayer = federation.player(Player.Player1);
const structures = [Building.PlanetaryInstitute, Building.Academy1, Building.Academy2];
fedPlayer.data.occupied.forEach((hex, index) => {
hex.data.building = structures[index];
});
fedPlayer.data.buildings[Building.Mine] = 0;
fedPlayer.data.buildings[Building.PlanetaryInstitute] = 1;
fedPlayer.data.buildings[Building.Academy1] = 1;
fedPlayer.data.buildings[Building.Academy2] = 1;
fedPlayer.data.power.area1 = 20;
fedPlayer.data.ores = 20;
fedPlayer.data.qics = 20;
fedPlayer.data.explorationShips[Spaceship.Twilight] = 1;
fedPlayer.federationCache = null;
federation.availableCommands = possibleFederations(federation, Player.Player1);
const federationSet = buildCommittedTurnMacros(federation, { conversionIntegration: false });
assertWellFormed(federationSet);
const federationMacros = federationSet.macros.filter((macro) => macro.mainCommand === Command.FormFederation);
expect(federationMacros.length).to.be.greaterThan(0);
for (const macro of federationMacros.slice(0, 6)) {
applyMacroHostStyle(federation, macro);
}
// Examine Artifact and its artifact-token choice.
const artifacts = lockedRoundOneEngine();
artifacts.player(Player.Player1).data.explorationShips[Spaceship.Twilight] = 1;
artifacts.player(Player.Player1).data.qics = 20;
artifacts.clearAvailableCommands();
const artifactSet = buildCommittedTurnMacros(artifacts, { conversionIntegration: false });
const artifactMacros = artifactSet.macros.filter((macro) => macro.mainCommand === Command.ExamineArtifact);
expect(artifactMacros.length).to.be.greaterThan(1);
expect(
artifactMacros.every((macro) =>
macro.decisions.some(
(decision) => decision.kind === "choice-follow-up" && decision.command === Command.ChooseArtifactToken
)
)
).to.equal(true);
for (const macro of artifactMacros.slice(0, 4)) {
applyMacroHostStyle(artifacts, macro);
}
// Navigation 5 forces the Lost Planet placement branch.
const lostPlanet = lockedRoundOneEngine();
const lostPlayer = lostPlanet.player(Player.Player1);
lostPlayer.data.research[ResearchField.Navigation] = 4;
lostPlayer.data.tiles.federations.push({ tile: Federation.Fed2, green: true });
lostPlayer.data.knowledge = 20;
lostPlanet.clearAvailableCommands();
const lostSet = buildCommittedTurnMacros(lostPlanet, { conversionIntegration: false });
const lostMacros = lostSet.macros.filter((macro) =>
macro.moveFragments.includes(`${Command.UpgradeResearch} ${ResearchField.Navigation}`)
);
expect(lostMacros.length).to.be.greaterThan(0);
expect(
lostMacros.every((macro) => macro.decisions.some((decision) => decision.command === Command.PlaceLostPlanet))
).to.equal(true);
for (const macro of lostMacros.slice(0, 3)) {
applyMacroHostStyle(lostPlanet, macro);
}
// TF Mars power action chains instant gaiaforming.
const tfMars = lockedRoundOneEngine();
const tfPlayer = tfMars.player(Player.Player1);
tfPlayer.data.explorationShips[Spaceship.TFMars] = 1;
tfPlayer.data.power.area3 = 20;
tfPlayer.data.gaiaformers = 1;
tfMars.clearAvailableCommands();
const tfSet = buildCommittedTurnMacros(tfMars, { conversionIntegration: false });
const tfMacros = tfSet.macros.filter(
(macro) => macro.moveFragments[0] === `${Command.SpaceshipAction} ${Spaceship.TFMars} power`
);
expect(tfMacros.length).to.be.greaterThan(0);
expect(
tfMacros.every((macro) => macro.decisions.some((decision) => decision.command === Command.GaiaFormTransdim))
).to.equal(true);
for (const macro of tfMacros.slice(0, 3)) {
applyMacroHostStyle(tfMars, macro);
}
});
});

View file

@ -0,0 +1,719 @@
import { createHash } from "crypto";
import { AvailableCommand } from "../../available/types";
import Engine from "../../engine";
import { Building, Command, Phase, Player, SubPhase } from "../../enums";
import { canonicalStateHash } from "../canonical-state";
import { planAfterActionConversionsForLine, planResourceConversions } from "../resources/planner";
import { OrderedConversionPlan } from "../resources/types";
import { stableCandidateJson } from "./canonical-key";
import { expandAtomicDecisions, expandInternallySuppliedAtomicCommands } from "./expand";
import { AtomicDecisionCandidate } from "./types";
export const COMMITTED_TURN_MACRO_SCHEMA = "gaia-ai-committed-turn-macro/v1" as const;
export type CommittedTurnMacroErrorCode = "unsupported-state" | "invalid-line" | "semantic-key-collision";
export class CommittedTurnMacroError extends Error {
constructor(
readonly code: CommittedTurnMacroErrorCode,
message: string
) {
super(message);
this.name = "CommittedTurnMacroError";
}
}
/**
* One recorded decision inside a committed macro line. `forced-follow-up` records exist for audit
* only: a forced one-choice decision never becomes a policy branch and never enters the macro key.
*/
export interface MacroDecisionRecord {
kind: "conversion-prefix" | "main" | "forced-follow-up" | "choice-follow-up" | "after-conversion" | "end-turn";
command: Command | null;
candidateKey: string | null;
moveFragments: string[];
/** Number of distinct options at this decision point (1 marks a forced decision). */
options: number;
}
export interface CommittedTurnMacroDestination {
stateHash: string;
phase: Phase;
round: number;
/** Next player to act at the committed destination (leech interrupts included), null at EndGame. */
nextActor: Player | null;
/** True when the committed destination is an interrupting leech decision. */
leechPending: boolean;
/** True when this macro's actor has passed for the round at the destination. */
actorPassed: boolean;
passOrder: Player[];
gameEnded: boolean;
}
export interface CommittedTurnMacro {
schemaVersion: typeof COMMITTED_TURN_MACRO_SCHEMA;
key: string;
sourceStateHash: string;
actor: Player;
actorPrefix: string;
phase: Phase;
round: number;
/** Phase 1.3 plan key of a non-empty pre-main conversion prefix, or null. */
conversionPlanKey: string | null;
/** Semantic wallet destination of the pre-main conversion prefix, or null when empty. */
conversionDestinationStateKey: string | null;
mainCandidateKey: string;
mainCommand: Command;
/** Candidate keys chosen at meaningful (more than one option) follow-up decisions, in order. */
followUpChoiceKeys: string[];
/** Candidate keys consumed at forced one-choice follow-ups, in order (audit only, not in key). */
forcedFollowUpKeys: string[];
/** Phase 1.3 plan key of a retained non-empty AfterMove conversion suffix, or null. */
afterConversionPlanKey: string | null;
afterConversionDestinationStateKey: string | null;
decisions: MacroDecisionRecord[];
moveFragments: string[];
/** Complete executable line, exactly as a host would submit it. */
moveLine: string;
warnings: string[];
destination: CommittedTurnMacroDestination;
}
export interface RejectedMacroLine {
reason: "dead-end-follow-up" | "line-apply-failed" | "unsupported-destination";
moveFragments: string[];
detail: string;
}
export interface MacroDeduplication {
key: string;
keptMoveFragments: string[];
mergedMoveFragments: string[];
}
export interface MacroBranchStatistics {
conversionIntegration: boolean;
macroCount: number;
mainCandidateCount: number;
/** Distinct non-empty pre-main conversion prefixes across emitted macros. */
conversionPlanCount: number;
/** Macros carrying a retained AfterMove bowl-opening conversion suffix. */
afterConversionMacroCount: number;
/** Distinct candidate keys chosen at meaningful follow-up decisions. */
meaningfulFollowUpKeyCount: number;
/** Distinct candidate keys consumed at forced one-choice follow-ups. */
forcedFollowUpKeyCount: number;
rejectedLineCount: number;
deduplicationCount: number;
/** Count of federation tiles offered only through the deliberately excluded custom fallback. */
excludedCustomFederationCount: number;
}
export interface CommittedTurnMacroSet {
schemaVersion: typeof COMMITTED_TURN_MACRO_SCHEMA;
sourceStateHash: string;
actor: Player;
actorPrefix: string;
phase: Phase;
round: number;
macros: CommittedTurnMacro[];
rejected: RejectedMacroLine[];
deduplications: MacroDeduplication[];
/**
* Federation tiles the engine offered at this state ONLY through its custom (hand-picked hex
* set) fallback, which is deliberately out of scope: the AI forms only engine-enumerated
* federations (those with a satellite path). A non-empty list means "a federation was formable
* only by hand-picking hexes here, and the AI intentionally skipped it" — recorded for offline
* audit so the exclusion is not silent, not a gap awaiting a later custom-federation feature.
*/
excludedCustomFederationTiles: string[];
statistics: MacroBranchStatistics;
}
export interface CommittedTurnMacroBuildOptions {
/**
* True (default) integrates Phase 1.3 conversion planning: nondominated pre-main conversion
* prefixes per main candidate plus retained AfterMove bowl-opening suffixes. False builds only
* root-affordable lines with every conversion deferred; that mode exists to measure branch
* statistics before conversion integration and for cheap corpus sweeps, and both modes produce
* identical keys for the shared conversion-free macros.
*/
conversionIntegration?: boolean;
/**
* Controls the retained AfterMove bowl-opening branches separately from the pre-main axis;
* defaults to `conversionIntegration`. The AfterMove window runs one complete, uncapped Phase
* 1.3 fixpoint per distinct post-main wallet, which is exact but measurably expensive on
* resource-rich wallets (the pristine locked Round-1 wallet grows past practical wall-clock),
* so statistics runs and corpus sweeps state explicitly which axes were enabled instead of
* silently capping the planner.
*/
afterConversionIntegration?: boolean;
/** Optional Phase 1.2 main-candidate key filter for the RoundMove path. */
mainCandidateKeys?: readonly string[];
}
/**
* Structural runaway detector, not a semantic search cap: a legal committed line in the supported
* boundary is far shorter, so exceeding this many dot-separated parts is a loud builder/engine
* mismatch failure instead of a silently truncated macro.
*/
const MAX_LINE_FRAGMENTS = 64;
const NARROW_AFTER_WINDOW_COMMANDS = new Set<Command>([Command.Spend, Command.BurnPower, Command.EndTurn]);
interface LineState {
fragments: string[];
decisions: MacroDecisionRecord[];
conversionPlanKey: string | null;
conversionDestinationStateKey: string | null;
mainCandidate: AtomicDecisionCandidate;
afterConversionPlanKey: string | null;
afterConversionDestinationStateKey: string | null;
afterWindowResolved: boolean;
warnings: string[];
}
function hydrate(engine: Engine): Engine {
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
}
function isMainCandidate(candidate: AtomicDecisionCandidate): boolean {
return ![Command.Spend, Command.BurnPower, Command.BrainStone, Command.EndTurn].includes(candidate.command);
}
function isNarrowAfterWindow(commands: AvailableCommand[]): boolean {
return (
commands.some((command) => command.name === Command.EndTurn) &&
commands.every((command) => NARROW_AFTER_WINDOW_COMMANDS.has(command.name))
);
}
/**
* Deterministic subphase label for a chained follow-up decision, derived only from the offered
* command set so macro keys are identical across constructor replay, slow motion, hydration, and
* host-style replay. The label feeds candidate keys; the macro key additionally contains the whole
* decision path, so a coarse label can never merge two genuinely different macros.
*/
function followUpSubphase(commands: AvailableCommand[]): SubPhase | null {
if (isNarrowAfterWindow(commands)) {
return SubPhase.AfterMove;
}
const first = commands[0];
switch (first.name) {
case Command.ChooseTechTile:
return SubPhase.ChooseTechTile;
case Command.ChooseCoverTechTile:
return SubPhase.CoverTechTile;
case Command.UpgradeResearch:
return SubPhase.UpgradeResearch;
case Command.PlaceLostPlanet:
return SubPhase.PlaceLostPlanet;
case Command.ChooseFederationTile:
return (first as AvailableCommand<Command.ChooseFederationTile>).data.rescore
? SubPhase.RescoreFederationTile
: SubPhase.ChooseFederationTile;
case Command.ChooseArtifactToken:
return SubPhase.ChooseArtifactToken;
case Command.PlacePowerRing:
return SubPhase.PlacePowerRing;
case Command.BrainStone:
return SubPhase.BrainStone;
case Command.PISwap:
return SubPhase.PISwap;
case Command.GaiaFormTransdim:
return SubPhase.InstantGaiaforming;
case Command.Build:
case Command.Explore:
return commands.some((command) => command.name === Command.Explore)
? SubPhase.BuildMineOrGaiaFormer
: SubPhase.BuildMine;
default:
return null;
}
}
/**
* Wallet-and-context signature mirroring the Phase 1.3 dominance dimensions. Two lines that reach
* the narrow AfterMove window with the same main candidate and the same signature see the same
* legal conversion catalogue, so the exhaustive AfterMove fixpoint result can be shared.
*/
function afterWalletSignature(engine: Engine, actor: Player): string {
const player = engine.player(actor);
const data = player.data;
return stableCandidateJson({
credits: data.credits,
ores: data.ores,
knowledge: data.knowledge,
qics: data.qics,
victoryPoints: data.victoryPoints,
power: {
area1: data.power.area1,
area2: data.power.area2,
area3: data.power.area3,
gaia: data.power.gaia,
brainstone: data.brainstone ?? null,
},
gaiaformers: data.gaiaformers,
gaiaformersInGaia: data.gaiaformersInGaia,
gaiaformersOnBoard: data.buildings[Building.GaiaFormer] ?? 0,
gaiaformersUsedForAsteroid: data.gaiaformersUsedForAsteroid,
gaiaformersUsedForOther: data.gaiaformersUsedForOther,
tokenModifier: data.tokenModifier,
terraformCostDiscount: data.terraformCostDiscount,
temporaryRange: data.temporaryRange,
temporaryStep: data.temporaryStep,
satellites: data.satellites,
hasPlanetaryInstitute: data.hasPlanetaryInstitute(),
});
}
function macroKey(material: {
sourceStateHash: string;
actor: Player;
conversionDestinationStateKey: string | null;
mainCandidateKey: string;
followUpChoiceKeys: string[];
afterConversionDestinationStateKey: string | null;
}): string {
const digest = createHash("sha256")
.update(stableCandidateJson({ schemaVersion: COMMITTED_TURN_MACRO_SCHEMA, ...material }))
.digest("hex");
return `macro-v1:${digest}`;
}
function sortedUnique(values: readonly string[]): string[] {
return Array.from(new Set(values)).sort();
}
function conversionSeed(main: AtomicDecisionCandidate, plan: OrderedConversionPlan | null, options: number): LineState {
const decisions: MacroDecisionRecord[] = [];
if (plan) {
decisions.push({
kind: "conversion-prefix",
command: null,
candidateKey: null,
moveFragments: [...plan.moveFragments],
options,
});
}
decisions.push({
kind: "main",
command: main.command,
candidateKey: main.key,
moveFragments: [main.moveFragment],
options,
});
return {
fragments: [...(plan?.moveFragments ?? []), main.moveFragment],
decisions,
conversionPlanKey: plan?.key ?? null,
conversionDestinationStateKey: plan?.destinationStateKey ?? null,
mainCandidate: main,
afterConversionPlanKey: null,
afterConversionDestinationStateKey: null,
afterWindowResolved: false,
warnings: [...main.warnings],
};
}
/**
* Build every complete committed-turn macro from one committed snapshot, replaying each candidate
* line against a fresh clone exactly like the production hosts and the fuzzer commit rule
* (`copy.move(line)`, commit only when `copy.newTurn`). A macro contains an optional Phase 1.3
* conversion prefix, exactly one Phase 1.2 main action, every forced follow-up, meaningful
* follow-up choices as distinct branches, retained AfterMove bowl-opening conversions, and `end`
* when the engine requires it. Committed leech interruptions are never folded in: they surface as
* `destination.leechPending` and become the next committed decision edge. Transient states are
* never serialized; a `DeadEnd` line or a line that fails to commit is rejected before exposure.
*/
export function buildCommittedTurnMacros(
source: Engine,
options: CommittedTurnMacroBuildOptions = {}
): CommittedTurnMacroSet {
const sourceStateHash = canonicalStateHash(source);
const conversionIntegration = options.conversionIntegration ?? true;
const afterConversionIntegration = options.afterConversionIntegration ?? conversionIntegration;
const actor = source.playerToMove;
if (actor === undefined || actor === null || !source.player(actor)) {
throw new CommittedTurnMacroError("unsupported-state", "Committed source state has no player to move");
}
const actorPrefix = source.player(actor).faction ?? `p${actor + 1}`;
// Custom (hand-picked hex set) federations are deliberately out of scope (owner decision
// 2026-07-14): the AI only ever forms one of the engine's enumerated federations, the ones with
// a real satellite path. When the engine offers a federation ONLY through its custom fallback
// (`federations: []`), there is no enumerable geometry to form and no satellite-path federation
// available at this state, so the AI simply does not form a federation this turn. That fallback
// command is dropped from expansion (Phase 1.2 rejects it anyway) rather than making the whole
// state unusable; the dropped tiles are recorded for offline audit so the skip is not silent.
const excludedCustomFederationTiles: string[] = [];
let expansion: ReturnType<typeof expandAtomicDecisions>;
if (source.phase === Phase.RoundMove) {
const probe = hydrate(source);
const rootCommands = probe.generateAvailableCommandsIfNeeded();
const customOnly = rootCommands.filter(
(command): command is AvailableCommand<Command.FormFederation> =>
command.name === Command.FormFederation && command.data.federations.length === 0
);
if (customOnly.length === 0) {
expansion = expandAtomicDecisions(source);
} else {
for (const command of customOnly) {
for (const tile of command.data.tiles) {
excludedCustomFederationTiles.push(String(tile));
}
}
excludedCustomFederationTiles.sort();
expansion = expandInternallySuppliedAtomicCommands(
probe,
SubPhase.BeforeMove,
rootCommands.filter((command) => !customOnly.includes(command as AvailableCommand<Command.FormFederation>))
);
}
} else {
expansion = expandAtomicDecisions(source);
}
const queue: LineState[] = [];
if (source.phase === Phase.RoundMove) {
let mains = expansion.candidates.filter(isMainCandidate);
if (options.mainCandidateKeys) {
const allowed = new Set(options.mainCandidateKeys);
mains = mains.filter((candidate) => allowed.has(candidate.key));
}
if (!conversionIntegration) {
for (const main of mains) {
queue.push(conversionSeed(main, null, mains.length));
}
} else {
// No planner-side candidate filter: conversion-enabled candidates that are unaffordable at
// the root (13 of the locked state's 45 candidate frontiers) are exactly what integration
// must expose. Any caller filter is applied to the complete candidate set afterwards.
const planning = planResourceConversions(source);
const allowedKeys = options.mainCandidateKeys ? new Set(options.mainCandidateKeys) : null;
for (const entry of planning.candidates) {
const main = entry.candidate;
if (allowedKeys && !allowedKeys.has(main.key)) {
continue;
}
const planByKey = new Map(entry.plans.map((plan) => [plan.key, plan]));
const seenPlans = new Set<string>();
const seeds: LineState[] = [];
for (const payment of entry.payments.frontier) {
if (seenPlans.has(payment.conversionPlanKey)) {
continue;
}
seenPlans.add(payment.conversionPlanKey);
const plan = planByKey.get(payment.conversionPlanKey);
if (!plan) {
throw new CommittedTurnMacroError(
"invalid-line",
`Payment frontier references unknown conversion plan ${payment.conversionPlanKey}`
);
}
seeds.push(conversionSeed(main, plan.steps.length === 0 ? null : plan, 0));
}
for (const seed of seeds) {
for (const decision of seed.decisions) {
decision.options = seeds.length;
}
queue.push(seed);
}
}
}
} else {
for (const candidate of expansion.candidates) {
queue.push({
fragments: [candidate.moveFragment],
decisions: [
{
kind: "main",
command: candidate.command,
candidateKey: candidate.key,
moveFragments: [candidate.moveFragment],
options: expansion.candidates.length,
},
],
conversionPlanKey: null,
conversionDestinationStateKey: null,
mainCandidate: candidate,
afterConversionPlanKey: null,
afterConversionDestinationStateKey: null,
afterWindowResolved: false,
warnings: [...candidate.warnings],
});
}
}
const macros = new Map<string, CommittedTurnMacro>();
const deduplications: MacroDeduplication[] = [];
const rejected: RejectedMacroLine[] = [];
const finalize = (line: LineState, committed: Engine) => {
let destinationHash: string;
try {
destinationHash = canonicalStateHash(committed);
} catch (error) {
rejected.push({
reason: "unsupported-destination",
moveFragments: [...line.fragments],
detail: String((error as Error)?.message ?? error),
});
return;
}
const followUpChoiceKeys = line.decisions
.filter((decision) => decision.kind === "choice-follow-up")
.map((decision) => decision.candidateKey as string);
const forcedFollowUpKeys = line.decisions
.filter((decision) => decision.kind === "forced-follow-up")
.map((decision) => decision.candidateKey as string);
const key = macroKey({
sourceStateHash,
actor,
conversionDestinationStateKey: line.conversionDestinationStateKey,
mainCandidateKey: line.mainCandidate.key,
followUpChoiceKeys,
afterConversionDestinationStateKey: line.afterConversionDestinationStateKey,
});
const macro: CommittedTurnMacro = {
schemaVersion: COMMITTED_TURN_MACRO_SCHEMA,
key,
sourceStateHash,
actor,
actorPrefix,
phase: source.phase,
round: source.round,
conversionPlanKey: line.conversionPlanKey,
conversionDestinationStateKey: line.conversionDestinationStateKey,
mainCandidateKey: line.mainCandidate.key,
mainCommand: line.mainCandidate.command,
followUpChoiceKeys,
forcedFollowUpKeys,
afterConversionPlanKey: line.afterConversionPlanKey,
afterConversionDestinationStateKey: line.afterConversionDestinationStateKey,
decisions: line.decisions,
moveFragments: [...line.fragments],
moveLine: `${actorPrefix} ${line.fragments.join(". ")}`,
warnings: sortedUnique(line.warnings),
destination: {
stateHash: destinationHash,
phase: committed.phase,
round: committed.round,
nextActor: committed.playerToMove ?? null,
leechPending: committed.phase === Phase.RoundLeech,
actorPassed: (committed.passedPlayers ?? []).includes(actor),
passOrder: [...(committed.passedPlayers ?? [])],
gameEnded: committed.phase === Phase.EndGame,
},
};
const existing = macros.get(key);
if (existing) {
if (existing.destination.stateHash !== macro.destination.stateHash) {
throw new CommittedTurnMacroError(
"semantic-key-collision",
`Macro key ${key} maps to two different committed destinations`
);
}
deduplications.push({
key,
keptMoveFragments: existing.moveFragments,
mergedMoveFragments: macro.moveFragments,
});
return;
}
macros.set(key, macro);
};
const afterWindowCache = new Map<string, ReturnType<typeof planAfterActionConversionsForLine>>();
let queueIndex = 0;
while (queueIndex < queue.length) {
const line = queue[queueIndex];
queueIndex += 1;
if (line.fragments.length > MAX_LINE_FRAGMENTS) {
throw new CommittedTurnMacroError(
"invalid-line",
`Macro line exceeded ${MAX_LINE_FRAGMENTS} fragments without committing: ${line.fragments.join(". ")}`
);
}
const clone = hydrate(source);
try {
clone.move(`${actorPrefix} ${line.fragments.join(". ")}`);
} catch (error) {
rejected.push({
reason: "line-apply-failed",
moveFragments: [...line.fragments],
detail: String((error as Error)?.message ?? error),
});
continue;
}
if (clone.newTurn) {
finalize(line, clone);
continue;
}
const commands = clone.availableCommands;
if (!commands || commands.length === 0) {
throw new CommittedTurnMacroError(
"invalid-line",
`Incomplete line offered no follow-up commands: ${line.fragments.join(". ")}`
);
}
if (commands.some((command) => command.name === Command.DeadEnd)) {
rejected.push({
reason: "dead-end-follow-up",
moveFragments: [...line.fragments],
detail: "Engine offered DeadEnd for a required chained decision; a real player must undo this line",
});
continue;
}
if (source.phase === Phase.RoundMove && isNarrowAfterWindow(commands)) {
let resolvedRetained = false;
if (!line.afterWindowResolved && afterConversionIntegration && line.mainCandidate.command !== Command.Pass) {
// One exhaustive AfterMove fixpoint per distinct (main candidate, post-main wallet) pair;
// lines converging on the same wallet reuse the identical retained/deferred result.
const cacheKey = `${line.mainCandidate.key}\0${afterWalletSignature(clone, actor)}`;
let after = afterWindowCache.get(cacheKey);
if (!after) {
after = planAfterActionConversionsForLine(source, line.mainCandidate, line.fragments);
afterWindowCache.set(cacheKey, after);
}
if (after.status === "planned") {
for (const retainedEntry of after.retained) {
const plan = retainedEntry.plan;
const wait = plan.steps.length === 0;
queue.push({
...line,
fragments: [...line.fragments, ...plan.moveFragments, Command.EndTurn],
decisions: [
...line.decisions,
...(wait
? []
: [
{
kind: "after-conversion" as const,
command: null,
candidateKey: null,
moveFragments: [...plan.moveFragments],
options: after.retained.length,
},
]),
{
kind: "end-turn" as const,
command: Command.EndTurn,
candidateKey: null,
moveFragments: [Command.EndTurn],
options: after.retained.length,
},
],
afterConversionPlanKey: wait ? null : plan.key,
afterConversionDestinationStateKey: wait ? null : plan.destinationStateKey,
afterWindowResolved: true,
warnings: [...line.warnings],
});
}
resolvedRetained = after.retained.length > 0;
}
}
if (!resolvedRetained) {
queue.push({
...line,
fragments: [...line.fragments, Command.EndTurn],
decisions: [
...line.decisions,
{
kind: "end-turn",
command: Command.EndTurn,
candidateKey: null,
moveFragments: [Command.EndTurn],
options: 1,
},
],
afterWindowResolved: true,
warnings: [...line.warnings],
});
}
continue;
}
const subphase = followUpSubphase(commands);
const followUps =
clone.phase === Phase.RoundMove && subphase !== null
? expandInternallySuppliedAtomicCommands(clone, subphase, commands)
: expandAtomicDecisions(source, {
priorMoveFragments: line.fragments,
subphase,
});
if (followUps.candidates.length === 1) {
const only = followUps.candidates[0];
queue.push({
...line,
fragments: [...line.fragments, only.moveFragment],
decisions: [
...line.decisions,
{
kind: "forced-follow-up",
command: only.command,
candidateKey: only.key,
moveFragments: [only.moveFragment],
options: 1,
},
],
warnings: [...line.warnings, ...only.warnings],
});
continue;
}
for (const candidate of followUps.candidates) {
queue.push({
...line,
fragments: [...line.fragments, candidate.moveFragment],
decisions: [
...line.decisions,
{
kind: "choice-follow-up",
command: candidate.command,
candidateKey: candidate.key,
moveFragments: [candidate.moveFragment],
options: followUps.candidates.length,
},
],
warnings: [...line.warnings, ...candidate.warnings],
});
}
}
const sortedMacros = Array.from(macros.values()).sort((a, b) => a.key.localeCompare(b.key));
const statistics: MacroBranchStatistics = {
conversionIntegration,
macroCount: sortedMacros.length,
mainCandidateCount: new Set(sortedMacros.map((macro) => macro.mainCandidateKey)).size,
conversionPlanCount: new Set(
sortedMacros.map((macro) => macro.conversionPlanKey).filter((key): key is string => key !== null)
).size,
afterConversionMacroCount: sortedMacros.filter((macro) => macro.afterConversionPlanKey !== null).length,
meaningfulFollowUpKeyCount: new Set(sortedMacros.flatMap((macro) => macro.followUpChoiceKeys)).size,
forcedFollowUpKeyCount: new Set(sortedMacros.flatMap((macro) => macro.forcedFollowUpKeys)).size,
rejectedLineCount: rejected.length,
deduplicationCount: deduplications.length,
excludedCustomFederationCount: excludedCustomFederationTiles.length,
};
return {
schemaVersion: COMMITTED_TURN_MACRO_SCHEMA,
sourceStateHash,
actor,
actorPrefix,
phase: source.phase,
round: source.round,
macros: sortedMacros,
rejected: rejected.sort(
(a, b) => a.moveFragments.join(". ").localeCompare(b.moveFragments.join(". ")) || a.reason.localeCompare(b.reason)
),
deduplications: deduplications.sort(
(a, b) =>
a.key.localeCompare(b.key) || a.mergedMoveFragments.join(". ").localeCompare(b.mergedMoveFragments.join(". "))
),
excludedCustomFederationTiles,
statistics,
};
}

View file

@ -0,0 +1,236 @@
import {
AnyTechTile,
AnyTechTilePos,
ArtifactToken,
BoardAction,
Booster,
Building,
Command,
Faction,
Federation,
Phase,
Planet,
Player,
ResearchField,
Resource,
Spaceship,
SpaceshipFederation,
SpaceshipTechTile,
SubPhase,
TinkeringTile,
} from "../../enums";
import { BrainstoneDest } from "../../player-data";
import { SpaceshipActionType } from "../../spaceships";
export const ATOMIC_CANDIDATE_SCHEMA = "gaia-ai-atomic-candidate/v1" as const;
export interface ResourceAmount {
resource: Resource;
amount: number;
}
/**
* Fixed resource changes are projected into cost/reward vectors. Event grammar whose amount is
* conditional or deferred (for example `pt > vp`, `>fed`, or recurring income) remains explicit
* in `effects` instead of being guessed by the Phase 1.2 layer.
*/
export interface CandidateResourceFlow {
cost: ResourceAmount[];
reward: ResourceAmount[];
effects: string[];
}
export interface CandidateRangeMetadata {
distance: number | null;
baseRange: number | null;
temporaryRange: number;
qic: number;
adjustments: string[];
}
export interface CandidateTerraformMetadata {
steps: number;
temporarySteps: number;
consumesAsteroidGaiaformer: boolean;
}
export interface CandidateSatelliteMetadata {
allHexes: string[];
satelliteHexes: string[];
newSatelliteHexes: string[];
existingFederationHexes: string[];
}
export interface AtomicCandidateBase<C extends Command, T> {
schemaVersion: typeof ATOMIC_CANDIDATE_SCHEMA;
key: string;
command: C;
actor: Player;
phase: Phase;
subphase: SubPhase | null;
target: T;
resources: CandidateResourceFlow;
warnings: string[];
/** Executable command part without the actor prefix or preceding dot-separated parts. */
moveFragment: string;
}
export type ActionCandidate = AtomicCandidateBase<Command.Action, { boardAction: BoardAction }>;
export type BrainStoneCandidate = AtomicCandidateBase<Command.BrainStone, { destination: BrainstoneDest }>;
export type BuildCandidate = AtomicCandidateBase<
Command.Build,
{
building: Building;
coordinates: string;
planet: Planet | null;
upgrade: boolean;
downgrade: boolean;
range: CandidateRangeMetadata;
terraform: CandidateTerraformMetadata;
}
>;
export type BurnPowerCandidate = AtomicCandidateBase<Command.BurnPower, { amount: number }>;
export type ChargePowerCandidate = AtomicCandidateBase<Command.ChargePower, { offer: string }>;
export type ChooseArtifactTokenCandidate = AtomicCandidateBase<
Command.ChooseArtifactToken,
{ artifact: ArtifactToken; noEffect: boolean }
>;
export type ChooseCoverTechTileCandidate = AtomicCandidateBase<
Command.ChooseCoverTechTile,
{ position: AnyTechTilePos | Spaceship; tile: AnyTechTile | SpaceshipTechTile }
>;
export type ChooseFactionCandidate = AtomicCandidateBase<Command.ChooseFaction, { faction: Faction }>;
export type ChooseFederationTileCandidate = AtomicCandidateBase<
Command.ChooseFederationTile,
{ federation: Federation | SpaceshipFederation; rescore: boolean }
>;
export type ChooseIncomeCandidate = AtomicCandidateBase<Command.ChooseIncome, { income: string }>;
export type ChooseRoundBoosterCandidate = AtomicCandidateBase<Command.ChooseRoundBooster, { booster: Booster }>;
export type ChooseTechTileCandidate = AtomicCandidateBase<
Command.ChooseTechTile,
{ position: AnyTechTilePos | Spaceship; tile: AnyTechTile | SpaceshipTechTile }
>;
export type ChooseTinkeringTileCandidate = AtomicCandidateBase<Command.ChooseTinkeringTile, { tile: TinkeringTile }>;
export type DeclineCandidate = AtomicCandidateBase<Command.Decline, { offers: string[] }>;
export type EndTurnCandidate = AtomicCandidateBase<Command.EndTurn, Record<string, never>>;
export type ExamineArtifactCandidate = AtomicCandidateBase<Command.ExamineArtifact, { ship: Spaceship.Twilight }>;
export type ExploreCandidate = AtomicCandidateBase<
Command.Explore,
{
ship: Spaceship;
coordinates: string;
slot: number;
charge: number;
range: CandidateRangeMetadata;
}
>;
export type FormFederationCandidate = AtomicCandidateBase<
Command.FormFederation,
{
federation: Federation | SpaceshipFederation;
spaceship: Spaceship | null;
hexes: string[];
satellites: CandidateSatelliteMetadata;
}
>;
export type GaiaFormTransdimCandidate = AtomicCandidateBase<
Command.GaiaFormTransdim,
{ coordinates: string; planet: Planet.Transdim }
>;
export type PassCandidate = AtomicCandidateBase<Command.Pass, { booster: Booster | null }>;
export type PISwapCandidate = AtomicCandidateBase<
Command.PISwap,
{ coordinates: string; from: Building.Mine; to: Building.PlanetaryInstitute }
>;
export type PlaceLostPlanetCandidate = AtomicCandidateBase<
Command.PlaceLostPlanet,
{ coordinates: string; planet: Planet.Lost; range: CandidateRangeMetadata }
>;
export type PlacePowerRingCandidate = AtomicCandidateBase<Command.PlacePowerRing, { coordinates: string }>;
export type SpecialCandidate = AtomicCandidateBase<Command.Special, { income: string; eventSpec: string }>;
export type SpendCandidate = AtomicCandidateBase<
Command.Spend,
{
cost: string;
income: string;
multiplier: number;
allowedMultipliers: number[];
hidden: boolean;
}
>;
export type SpaceshipActionCandidate = AtomicCandidateBase<
Command.SpaceshipAction,
{ ship: Spaceship; action: SpaceshipActionType }
>;
export type UpgradeResearchCandidate = AtomicCandidateBase<
Command.UpgradeResearch,
{ field: ResearchField; from: number; to: number }
>;
/** Every executable command family in the standard-flow Lost Fleet Phase 1.2 boundary. */
export type AtomicDecisionCandidate =
| ActionCandidate
| BrainStoneCandidate
| BuildCandidate
| BurnPowerCandidate
| ChargePowerCandidate
| ChooseArtifactTokenCandidate
| ChooseCoverTechTileCandidate
| ChooseFactionCandidate
| ChooseFederationTileCandidate
| ChooseIncomeCandidate
| ChooseRoundBoosterCandidate
| ChooseTechTileCandidate
| ChooseTinkeringTileCandidate
| DeclineCandidate
| EndTurnCandidate
| ExamineArtifactCandidate
| ExploreCandidate
| FormFederationCandidate
| GaiaFormTransdimCandidate
| PassCandidate
| PISwapCandidate
| PlaceLostPlanetCandidate
| PlacePowerRingCandidate
| SpecialCandidate
| SpendCandidate
| SpaceshipActionCandidate
| UpgradeResearchCandidate;
export interface CandidateDeduplication {
key: string;
command: AtomicDecisionCandidate["command"];
occurrences: number;
reason: "identical-semantic-option" | "decline-ignores-offer";
}
export interface AtomicDecisionExpansion {
candidates: AtomicDecisionCandidate[];
deduplications: CandidateDeduplication[];
}

View file

@ -0,0 +1,233 @@
{
"schemaVersion": "gaia-ai-phase0-baseline/v1",
"recordedAt": "2026-07-13T12:57:57.823Z",
"repositoryCommit": "8146e29f41797b630ba5251904657f48b93a27fb",
"verification": {
"fullEngineSuite": {
"command": "npx mocha -r ts-node/register --reporter min 'src/**/*.spec.ts' 'src/*.spec.ts' '*.spec.ts'",
"status": "passed",
"passing": 634,
"pending": 4,
"reportedDurationSeconds": 16
},
"phase0FocusedTests": {
"command": "npx mocha -r ts-node/register --reporter min 'src/ai/challenge-manifest.spec.ts' 'src/ai/benchmark.spec.ts'",
"status": "passed",
"passing": 4,
"manifestTests": 3,
"benchmarkSmokeTests": 1
},
"typeScript": {
"command": "npx tsc --noEmit",
"status": "passed"
}
},
"benchmark": {
"schemaVersion": "gaia-ai-benchmark/v1",
"generatedAt": "2026-07-13T12:57:57.823Z",
"challenge": {
"id": "lost-fleet-xenos-hadsch-hallas-lf-mrj5exuu-c680",
"version": "1.0.0",
"manifestSchemaVersion": "gaia-ai-challenge-manifest/v1",
"manifestSha256": "ce3bdd7322860484dfae771320b9f12967d0677b908f91cdc682d9c4427bf51e"
},
"configuration": {
"warmupIterations": 5,
"iterations": 50,
"randomGameWarmupIterations": 0,
"randomGameIterations": 1,
"memoryCloneCount": 50
},
"environment": {
"node": "v24.16.0",
"v8": "13.6.233.17-node.49",
"enginePackageVersion": "4.8.51",
"os": {
"type": "Windows_NT",
"platform": "win32",
"release": "10.0.26200",
"architecture": "x64"
},
"cpu": {
"model": "AMD Ryzen 5 5600G with Radeon Graphics ",
"logicalCores": 12
},
"memory": {
"totalBytes": 16474476544,
"freeBytesAtStart": 4838019072
},
"process": {
"pid": 5800,
"gcExposed": false
},
"environment": {
"CI": null,
"NODE_ENV": null
},
"repository": {
"commit": "8146e29f41797b630ba5251904657f48b93a27fb"
},
"redactions": {
"hostname": "redacted",
"homeDirectory": "redacted"
}
},
"workloads": {
"serialize": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 0.1044,
"median": 0.1155,
"mean": 0.120436,
"p95": 0.1574,
"max": 0.1764
},
"parse": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 0.1094,
"median": 0.1176,
"mean": 0.122882,
"p95": 0.1704,
"max": 0.2157
},
"hydrate": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 0.4279,
"median": 0.482,
"mean": 0.547568,
"p95": 0.7438,
"max": 2.7423
},
"clone": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 0.4992,
"median": 0.5543,
"mean": 0.560572,
"p95": 0.6916,
"max": 0.8521
},
"commandGeneration": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 0.0086,
"median": 0.0117,
"mean": 0.01516,
"p95": 0.0271,
"max": 0.0866,
"phase": "setupBuilding",
"commandsInChallengePrefixState": 1
},
"candidateExpansion": {
"status": "unavailable",
"reason": "Phase 1 candidate-expansion component does not exist in Phase 0"
},
"actionApplication": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 2.6956,
"median": 3.2845,
"mean": 3.58779,
"p95": 5.5667,
"max": 7.1142,
"description": "Apply the two scripted faction-choice move lines after deterministic initialization"
},
"constructorReplay": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 2.6281,
"median": 2.877,
"mean": 3.215326,
"p95": 4.757,
"max": 5.4989,
"committedMoveLines": 3
},
"hostStyleReplay": {
"status": "measured",
"warmupIterations": 5,
"iterations": 50,
"unit": "milliseconds",
"min": 3.8586,
"median": 4.1026,
"mean": 4.265504,
"p95": 5.2148,
"max": 6.5859,
"committedMoveLines": 3,
"description": "Engine.slowMotion serialize/parse/hydrate between committed lines"
},
"randomGame": {
"status": "measured",
"warmupIterations": 0,
"iterations": 1,
"unit": "milliseconds",
"min": 224.7527,
"median": 224.7527,
"mean": 224.7527,
"p95": 224.7527,
"max": 224.7527,
"generator": "fuzz/random-player deterministic sampler; not a legal-action enumerator",
"gameSeed": "lf-mrj5exuu-c680",
"playSeed": "lost-fleet-xenos-hadsch-hallas-lf-mrj5exuu-c680-benchmark-random-player-v1",
"outcomes": [
{
"finished": true,
"committedLines": 48,
"rounds": 6,
"failureCount": 0,
"finalStateBytes": 27433
}
]
},
"stateSize": {
"status": "measured",
"unit": "UTF-8 JSON bytes",
"challengePrefixState": 19777,
"challengeManifest": 38798,
"randomGameFinalState": 27433
},
"memory": {
"status": "measured",
"method": "retained Engine.fromData(JSON.parse(serializedState)) clones",
"cloneCount": 50,
"gcExposed": false,
"beforeBytes": {
"rss": 282394624,
"heapTotal": 231182336,
"heapUsed": 97513720,
"external": 2953312,
"arrayBuffers": 28969
},
"afterBytes": {
"rss": 282046464,
"heapTotal": 231182336,
"heapUsed": 121978720,
"external": 2953352,
"arrayBuffers": 28969
},
"deltaBytes": {
"rss": -348160,
"heapTotal": 0,
"heapUsed": 24465000,
"external": 40
},
"approximateHeapUsedBytesPerClone": 489300
}
}
}
}

View file

@ -0,0 +1,29 @@
import { expect } from "chai";
import { BENCHMARK_SCHEMA_VERSION, runPhase0Benchmark } from "./benchmark";
describe("Phase 0 AI benchmark", () => {
it("runs a very small smoke configuration and reports every workload", () => {
const result = runPhase0Benchmark({
warmupIterations: 1,
iterations: 1,
randomGameWarmupIterations: 0,
randomGameIterations: 0,
memoryCloneCount: 1,
});
expect(result.schemaVersion).to.equal(BENCHMARK_SCHEMA_VERSION);
expect(result.configuration.warmupIterations).to.equal(1);
expect(result.workloads.serialize.status).to.equal("measured");
expect(result.workloads.parse.status).to.equal("measured");
expect(result.workloads.hydrate.status).to.equal("measured");
expect(result.workloads.clone.status).to.equal("measured");
expect(result.workloads.commandGeneration.status).to.equal("measured");
expect(result.workloads.actionApplication.status).to.equal("measured");
expect(result.workloads.constructorReplay.status).to.equal("measured");
expect(result.workloads.hostStyleReplay.status).to.equal("measured");
expect(result.workloads.randomGame.status).to.equal("skipped");
expect(result.workloads.stateSize.status).to.equal("measured");
expect(result.workloads.memory.status).to.equal("measured");
expect(result.workloads.candidateExpansion.status).to.equal("unavailable");
});
});

350
engine/src/ai/benchmark.ts Normal file
View file

@ -0,0 +1,350 @@
import { execFileSync } from "child_process";
import { cpus, freemem, homedir, hostname, type as osType, platform, release, totalmem } from "os";
import { version as enginePackageVersion } from "../../package.json";
import Engine from "../engine";
import { fuzzGame, FuzzGameResult } from "../fuzz/driver";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "./challenge";
import {
bootChallengeEngine,
challengeManifestSha256,
generateChallengeManifest,
stableManifestJson,
} from "./challenge-manifest";
import { BenchmarkConfig } from "./types";
export const BENCHMARK_SCHEMA_VERSION = "gaia-ai-benchmark/v1" as const;
export const DEFAULT_BENCHMARK_CONFIG: BenchmarkConfig = {
warmupIterations: 5,
iterations: 50,
randomGameWarmupIterations: 0,
randomGameIterations: 1,
memoryCloneCount: 50,
};
interface TimingSummary {
status: "measured";
warmupIterations: number;
iterations: number;
unit: "milliseconds";
min: number;
median: number;
mean: number;
p95: number;
max: number;
}
function durationMilliseconds(start: [number, number]): number {
const elapsed = process.hrtime(start);
return elapsed[0] * 1000 + elapsed[1] / 1e6;
}
function rounded(value: number): number {
return Math.round(value * 1e6) / 1e6;
}
function timing(warmupIterations: number, iterations: number, operation: () => unknown): TimingSummary {
for (let i = 0; i < warmupIterations; i++) {
operation();
}
const samples: number[] = [];
for (let i = 0; i < iterations; i++) {
const start = process.hrtime();
operation();
samples.push(durationMilliseconds(start));
}
const sorted = [...samples].sort((a, b) => a - b);
const percentileIndex = (percentile: number) =>
Math.min(sorted.length - 1, Math.ceil(sorted.length * percentile) - 1);
return {
status: "measured",
warmupIterations,
iterations,
unit: "milliseconds",
min: rounded(sorted[0]),
median: rounded(sorted[Math.floor(sorted.length / 2)]),
mean: rounded(samples.reduce((sum, sample) => sum + sample, 0) / samples.length),
p95: rounded(sorted[percentileIndex(0.95)]),
max: rounded(sorted[sorted.length - 1]),
};
}
function gitCommit(): string | null {
try {
return execFileSync("git", ["rev-parse", "HEAD"], {
cwd: __dirname,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
} catch {
return null;
}
}
function relevantEnvironment() {
const cpuList = cpus();
return {
node: process.version,
v8: process.versions.v8,
enginePackageVersion,
os: {
type: osType(),
platform: platform(),
release: release(),
architecture: process.arch,
},
cpu: {
model: cpuList[0]?.model ?? "unknown",
logicalCores: cpuList.length,
},
memory: {
totalBytes: totalmem(),
freeBytesAtStart: freemem(),
},
process: {
pid: process.pid,
gcExposed: typeof (global as any).gc === "function",
},
environment: {
CI: process.env.CI ?? null,
NODE_ENV: process.env.NODE_ENV ?? null,
},
repository: {
commit: gitCommit(),
},
// Explicitly avoid emitting the actual hostname/home path while recording that they were redacted.
redactions: {
hostname: hostname() ? "redacted" : null,
homeDirectory: homedir() ? "redacted" : null,
},
};
}
function cloneOptions() {
return challengeEngineOptions();
}
function memoryMeasurement(serializedState: string, cloneCount: number) {
const gc = (global as any).gc as (() => void) | undefined;
if (gc) {
gc();
}
const before = process.memoryUsage();
const retainedClones: Engine[] = [];
for (let i = 0; i < cloneCount; i++) {
retainedClones.push(Engine.fromData(JSON.parse(serializedState)));
}
const after = process.memoryUsage();
const result = {
status: "measured" as const,
method: "retained Engine.fromData(JSON.parse(serializedState)) clones",
cloneCount,
gcExposed: !!gc,
beforeBytes: before,
afterBytes: after,
deltaBytes: {
rss: after.rss - before.rss,
heapTotal: after.heapTotal - before.heapTotal,
heapUsed: after.heapUsed - before.heapUsed,
external: after.external - before.external,
},
approximateHeapUsedBytesPerClone: rounded((after.heapUsed - before.heapUsed) / cloneCount),
};
// Keep the array live through the second memoryUsage() call.
if (retainedClones.length !== cloneCount) {
throw new Error("memory clone workload did not retain the requested clone count");
}
return result;
}
function runRandomGame(): FuzzGameResult {
return fuzzGame(
{
gameSeed: LOST_FLEET_CHALLENGE.seed,
playSeed: `${LOST_FLEET_CHALLENGE.id}-benchmark-random-player-v1`,
players: LOST_FLEET_CHALLENGE.playerCount,
lostFleet: true,
},
{ checkpointEvery: 0, maxLines: 1500 }
);
}
function validateConfig(config: BenchmarkConfig): void {
for (const [key, value] of Object.entries(config)) {
if (!Number.isInteger(value) || value < 0) {
throw new Error(`${key} must be a non-negative integer`);
}
}
if (config.iterations < 1) {
throw new Error("iterations must be at least 1");
}
if (config.memoryCloneCount < 1) {
throw new Error("memoryCloneCount must be at least 1");
}
}
export function runPhase0Benchmark(overrides: Partial<BenchmarkConfig> = {}) {
const config = { ...DEFAULT_BENCHMARK_CONFIG, ...overrides };
validateConfig(config);
const engine = bootChallengeEngine();
const serializedState = JSON.stringify(engine);
const manifest = generateChallengeManifest();
const manifestJson = stableManifestJson(manifest, 0);
const prefix = [...LOST_FLEET_CHALLENGE.scriptedPrefix];
let serializedSink = "";
const serialize = timing(config.warmupIterations, config.iterations, () => {
serializedSink = JSON.stringify(engine);
return serializedSink.length;
});
let parsedSink: any;
const parse = timing(config.warmupIterations, config.iterations, () => {
parsedSink = JSON.parse(serializedState);
return parsedSink.phase;
});
const hydrateInputs = Array.from({ length: config.warmupIterations + config.iterations }, () =>
JSON.parse(serializedState)
);
let hydrateIndex = 0;
let engineSink: Engine;
const hydrate = timing(config.warmupIterations, config.iterations, () => {
engineSink = Engine.fromData(hydrateInputs[hydrateIndex++]);
return engineSink.phase;
});
const clone = timing(config.warmupIterations, config.iterations, () => {
engineSink = Engine.fromData(JSON.parse(serializedState));
return engineSink.phase;
});
const commandEngines = Array.from({ length: config.warmupIterations + config.iterations }, () =>
Engine.fromData(JSON.parse(serializedState))
);
let commandIndex = 0;
let commandCountSink = 0;
const commandGeneration = timing(config.warmupIterations, config.iterations, () => {
const commandEngine = commandEngines[commandIndex++];
commandEngine.availableCommands = undefined;
commandCountSink = commandEngine.generateAvailableCommands().length;
return commandCountSink;
});
const actionApplication = timing(config.warmupIterations, config.iterations, () => {
const actionEngine = new Engine([prefix[0]], cloneOptions());
actionEngine.move(prefix[1]);
actionEngine.move(prefix[2]);
return actionEngine.phase;
});
const constructorReplay = timing(config.warmupIterations, config.iterations, () => {
engineSink = new Engine(prefix, cloneOptions());
return engineSink.phase;
});
const hostStyleReplay = timing(config.warmupIterations, config.iterations, () => {
engineSink = Engine.slowMotion(prefix, cloneOptions(), engine.version);
return engineSink.phase;
});
const randomGameOutcomes: Array<{
finished: boolean;
committedLines: number;
rounds: number;
failureCount: number;
finalStateBytes: number;
}> = [];
let randomGameResult: FuzzGameResult | undefined;
let randomGameCall = 0;
const randomGame =
config.randomGameIterations > 0
? timing(config.randomGameWarmupIterations, config.randomGameIterations, () => {
randomGameResult = runRandomGame();
if (randomGameCall++ >= config.randomGameWarmupIterations) {
randomGameOutcomes.push({
finished: randomGameResult.finished,
committedLines: randomGameResult.moves.length,
rounds: randomGameResult.rounds,
failureCount: randomGameResult.failures.length,
finalStateBytes: Buffer.byteLength(JSON.stringify(randomGameResult.engine), "utf8"),
});
}
return randomGameResult.finished;
})
: {
status: "skipped" as const,
reason: "randomGameIterations was configured as 0",
warmupIterations: config.randomGameWarmupIterations,
iterations: 0,
};
const result = {
schemaVersion: BENCHMARK_SCHEMA_VERSION,
generatedAt: new Date().toISOString(),
challenge: {
id: LOST_FLEET_CHALLENGE.id,
version: LOST_FLEET_CHALLENGE.version,
manifestSchemaVersion: LOST_FLEET_CHALLENGE.schemas.manifest,
manifestSha256: challengeManifestSha256(manifest),
},
configuration: config,
environment: relevantEnvironment(),
workloads: {
serialize,
parse,
hydrate,
clone,
commandGeneration: {
...commandGeneration,
phase: engine.phase,
commandsInChallengePrefixState: commandCountSink,
},
candidateExpansion: {
status: "unavailable" as const,
reason: "Phase 1 candidate-expansion component does not exist in Phase 0",
},
actionApplication: {
...actionApplication,
description: "Apply the two scripted faction-choice move lines after deterministic initialization",
},
constructorReplay: {
...constructorReplay,
committedMoveLines: prefix.length,
},
hostStyleReplay: {
...hostStyleReplay,
committedMoveLines: prefix.length,
description: "Engine.slowMotion serialize/parse/hydrate between committed lines",
},
randomGame: {
...randomGame,
generator: "fuzz/random-player deterministic sampler; not a legal-action enumerator",
gameSeed: LOST_FLEET_CHALLENGE.seed,
playSeed: `${LOST_FLEET_CHALLENGE.id}-benchmark-random-player-v1`,
outcomes: randomGameOutcomes,
},
stateSize: {
status: "measured" as const,
unit: "UTF-8 JSON bytes",
challengePrefixState: Buffer.byteLength(serializedState, "utf8"),
challengeManifest: Buffer.byteLength(manifestJson, "utf8"),
randomGameFinalState: randomGameResult
? Buffer.byteLength(JSON.stringify(randomGameResult.engine), "utf8")
: null,
},
memory: memoryMeasurement(serializedState, config.memoryCloneCount),
},
};
// Keep benchmark sinks observably live until all measurements have completed.
if (!serializedSink || !parsedSink || !engineSink) {
throw new Error("benchmark workload sinks were not populated");
}
return result;
}
export type Phase0BenchmarkResult = ReturnType<typeof runPhase0Benchmark>;

View file

@ -0,0 +1,124 @@
import { expect } from "chai";
import "mocha";
import Engine from "../../engine";
import { Phase, Player } from "../../enums";
import { buildCommittedTurnMacros } from "../actions/turn-builder";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "../challenge";
import { playPairedBaselineMatchup } from "../testing/self-play";
import { applyMacroHostStyle, chooseFixedFrame } from "./common";
import { GreedyMacroBot } from "./greedy";
import { HeuristicMacroBot } from "./heuristic";
import { RandomMacroBot } from "./random";
function challengeSetup(): Engine {
return new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
}
describe("Phase 2 committed-macro baseline bots", function () {
this.timeout(30 * 60 * 1000);
it("samples random macros deterministically and applies the choice host-style", () => {
const engine = challengeSetup();
const first = new RandomMacroBot("ai-6-random-lock").select(engine);
const second = new RandomMacroBot("ai-6-random-lock").select(engine);
expect(second.macro.key).to.equal(first.macro.key);
expect(first.macroSet.macros.some((macro) => macro.key === first.macro.key)).to.equal(true);
const committed = applyMacroHostStyle(engine, first.macro);
expect(committed.newTurn).to.equal(true);
});
it("greedy chooses only from the Phase 1.4 committed macro set", () => {
const engine = challengeSetup();
const selection = new GreedyMacroBot().select(engine);
expect(selection.macroSet.macros.some((macro) => macro.key === selection.macro.key)).to.equal(true);
expect(selection.evaluation.value).to.be.a("number");
expect(applyMacroHostStyle(engine, selection.macro).newTurn).to.equal(true);
});
it("keeps the frozen greedy bot default and exposes income normalization as an opt-in policy", () => {
expect(new GreedyMacroBot().name).to.equal("greedy-macro");
expect(new GreedyMacroBot({ valueMode: "income-normalized" }).name).to.equal("income-normalized-greedy-macro");
});
it("heuristic selection is deterministic, inspectable, and committed", () => {
const engine = challengeSetup();
const bot = new HeuristicMacroBot();
const first = bot.select(engine);
const second = bot.select(engine);
expect(second.macro.key).to.equal(first.macro.key);
expect(second.evaluation).to.deep.equal(first.evaluation);
expect(first.evaluation.features).to.not.be.empty;
expect(first.macroSet.macros.some((macro) => macro.key === first.macro.key)).to.equal(true);
expect(applyMacroHostStyle(engine, first.macro).newTurn).to.equal(true);
});
it("maximizes for seat 0 and minimizes the same values for seat 1 without edge negation", () => {
const macros = buildCommittedTurnMacros(challengeSetup(), { conversionIntegration: false }).macros;
const candidates = [
{ macro: macros[0], value: -3 },
{ macro: macros[1], value: 7 },
{ macro: macros[2], value: 2 },
];
expect(chooseFixedFrame(Player.Player1, candidates).value).to.equal(7);
expect(chooseFixedFrame(Player.Player2, candidates).value).to.equal(-3);
expect(candidates.map((candidate) => candidate.value)).to.deep.equal([-3, 7, 2]);
});
it("plays paired greedy-v-random and heuristic-v-greedy games to EndGame with both factions", () => {
const greedyRandom = playPairedBaselineMatchup(
() => new GreedyMacroBot(),
(_seat, label) => new RandomMacroBot(label),
"ai-6-greedy-random"
);
const heuristicGreedy = playPairedBaselineMatchup(
() => new HeuristicMacroBot(),
() => new GreedyMacroBot(),
"ai-6-heuristic-greedy"
);
for (const paired of [greedyRandom, heuristicGreedy]) {
expect(paired.aAsXenos.finalEngine.phase).to.equal(Phase.EndGame);
expect(paired.aAsHadschHallas.finalEngine.phase).to.equal(Phase.EndGame);
expect(paired.aAsXenos.seat0Bot).to.equal(paired.botA);
expect(paired.aAsHadschHallas.seat1Bot).to.equal(paired.botA);
expect(paired.aMargins).to.have.length(2);
expect(paired.pairedMarginMean).to.equal((paired.aMargins[0] + paired.aMargins[1]) / 2);
for (const game of [paired.aAsXenos, paired.aAsHadschHallas]) {
expect(game.fullGameReport.players.map((player) => player.score.finalScore)).to.deep.equal([
game.finalSeat0Score,
game.finalSeat1Score,
]);
for (const player of game.fullGameReport.players) {
expect(player.rounds.map((round) => round.round)).to.deep.equal([1, 2, 3, 4, 5, 6]);
expect(player.rounds.map((round) => round.rawScoreAfterRound)).to.have.length(6);
expect(player.totalPasses).to.equal(6);
expect(player.score.accountedFinalScore).to.equal(player.score.finalScore);
}
}
}
expect({
aAsXenos: [greedyRandom.aAsXenos.finalSeat0Score, greedyRandom.aAsXenos.finalSeat1Score],
aAsHadschHallas: [greedyRandom.aAsHadschHallas.finalSeat0Score, greedyRandom.aAsHadschHallas.finalSeat1Score],
aMargins: greedyRandom.aMargins,
lines: [greedyRandom.aAsXenos.committedLines, greedyRandom.aAsHadschHallas.committedLines],
}).to.deep.equal({
aAsXenos: [68, 51],
aAsHadschHallas: [20, 46],
aMargins: [17, 26],
lines: [45, 37],
});
expect({
aAsXenos: [heuristicGreedy.aAsXenos.finalSeat0Score, heuristicGreedy.aAsXenos.finalSeat1Score],
aAsHadschHallas: [
heuristicGreedy.aAsHadschHallas.finalSeat0Score,
heuristicGreedy.aAsHadschHallas.finalSeat1Score,
],
aMargins: heuristicGreedy.aMargins,
lines: [heuristicGreedy.aAsXenos.committedLines, heuristicGreedy.aAsHadschHallas.committedLines],
}).to.deep.equal({
aAsXenos: [52, 77],
aAsHadschHallas: [72, 38],
aMargins: [-25, -34],
lines: [33, 43],
});
});
});

View file

@ -0,0 +1,72 @@
import Engine from "../../engine";
import { Player } from "../../enums";
import {
buildCommittedTurnMacros,
CommittedTurnMacro,
CommittedTurnMacroBuildOptions,
CommittedTurnMacroSet,
} from "../actions/turn-builder";
import { canonicalStateHash } from "../canonical-state";
export class MacroBotError extends Error {
constructor(message: string) {
super(message);
this.name = "MacroBotError";
}
}
function hydrate(engine: Engine): Engine {
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
}
export function buildBotMacroSet(
engine: Engine,
options: CommittedTurnMacroBuildOptions = {
conversionIntegration: false,
afterConversionIntegration: false,
}
): CommittedTurnMacroSet {
const macroSet = buildCommittedTurnMacros(engine, options);
if (macroSet.macros.length === 0) {
throw new MacroBotError(
`No committed macro for actor ${macroSet.actor} at round ${engine.round}, phase ${engine.phase}`
);
}
return macroSet;
}
/** Fresh-clone, one-move host commit with destination verification. */
export function applyMacroHostStyle(source: Engine, macro: CommittedTurnMacro): Engine {
const committed = hydrate(source);
committed.move(macro.moveLine);
if (!committed.newTurn) {
throw new MacroBotError(`Macro ${macro.key} did not end at a committed turn boundary`);
}
const destinationHash = canonicalStateHash(committed);
if (destinationHash !== macro.destination.stateHash) {
throw new MacroBotError(`Macro ${macro.key} reached ${destinationHash}, expected ${macro.destination.stateHash}`);
}
if ((committed.playerToMove ?? null) !== macro.destination.nextActor) {
throw new MacroBotError(`Macro ${macro.key} recorded the wrong destination actor`);
}
return committed;
}
/** Fixed seat-0 selection. Player 1 maximizes; Player 2 minimizes the same un-negated values. */
export function chooseFixedFrame<T extends { macro: CommittedTurnMacro; value: number }>(
actor: Player,
candidates: T[]
): T {
if (candidates.length === 0) {
throw new MacroBotError("Cannot choose from an empty committed macro set");
}
let best = candidates[0];
for (const candidate of candidates.slice(1)) {
const better = actor === Player.Player1 ? candidate.value > best.value : candidate.value < best.value;
const tiedEarlier = candidate.value === best.value && candidate.macro.key.localeCompare(best.macro.key) < 0;
if (better || tiedEarlier) {
best = candidate;
}
}
return best;
}

View file

@ -0,0 +1,125 @@
import Engine from "../../engine";
import { Phase, Player, PowerArea, Resource } from "../../enums";
import { projectedEndgameResourceVictoryPoints, terminalUtility } from "../evaluation";
import { applyMacroHostStyle, buildBotMacroSet, chooseFixedFrame } from "./common";
import { MacroBot, MacroBotBuildOptions, MacroBotSelection } from "./types";
export type GreedyValueMode = "immediate" | "income-normalized";
export interface GreedyMacroBotOptions extends MacroBotBuildOptions {
/** The default preserves the frozen AI-6 baseline exactly. */
valueMode?: GreedyValueMode;
}
export interface GreedyEvaluation {
terminal: boolean;
value: number;
sourceValue: number;
immediateChange: number;
scoreMargin: number;
resourceMargin: number;
}
function playerResourceValue(engine: Engine, seat: Player): number {
const player = engine.player(seat);
const data = player.data;
const brainstone = data.brainstone === PowerArea.Area3 ? 0.8 : data.brainstone === PowerArea.Area2 ? 0.35 : 0;
return (
data.credits * 0.2 +
data.ores * 0.75 +
data.knowledge * 0.9 +
data.qics * 1.1 +
data.power.area1 * 0.04 +
data.power.area2 * 0.1 +
data.power.area3 * 0.25 +
brainstone +
projectedEndgameResourceVictoryPoints(player) * 0.2
);
}
function remainingIncomePhases(engine: Engine): number {
if (engine.phase === Phase.EndGame) {
return 0;
}
if (engine.round <= 0) {
return 6;
}
if (engine.phase === Phase.RoundStart || engine.phase === Phase.RoundIncome) {
return Math.max(7 - engine.round, 0);
}
return Math.max(6 - engine.round, 0);
}
function playerProjectedIncomeValue(engine: Engine, seat: Player): number {
const player = engine.player(seat);
const phases = remainingIncomePhases(engine);
return (
player.resourceIncome(Resource.Credit) * 0.2 * phases +
player.resourceIncome(Resource.Ore) * 0.75 * phases +
player.resourceIncome(Resource.Knowledge) * 0.9 * phases +
player.resourceIncome(Resource.Qic) * 1.1 * phases +
player.resourceIncome(Resource.ChargePower) * 0.12 * phases +
player.resourceIncome(Resource.GainToken) * 0.1 * phases +
player.resourceIncome(Resource.GainTokenArea3) * 0.25 * phases
);
}
export function greedyStateValue(engine: Engine, mode: GreedyValueMode = "immediate"): number {
if (engine.ended) {
return terminalUtility(engine);
}
const scoreMargin =
engine.player(Player.Player1).data.victoryPoints - engine.player(Player.Player2).data.victoryPoints;
const projectedIncomeMargin =
mode === "income-normalized"
? playerProjectedIncomeValue(engine, Player.Player1) - playerProjectedIncomeValue(engine, Player.Player2)
: 0;
return (
scoreMargin +
playerResourceValue(engine, Player.Player1) -
playerResourceValue(engine, Player.Player2) +
projectedIncomeMargin
);
}
function greedyEvaluation(source: Engine, destination: Engine, mode: GreedyValueMode): GreedyEvaluation {
const sourceValue = greedyStateValue(source, mode);
const value = greedyStateValue(destination, mode);
const scoreMargin =
destination.player(Player.Player1).data.victoryPoints - destination.player(Player.Player2).data.victoryPoints;
const resourceMargin =
playerResourceValue(destination, Player.Player1) - playerResourceValue(destination, Player.Player2);
return {
terminal: destination.ended,
value,
sourceValue,
immediateChange: value - sourceValue,
scoreMargin,
resourceMargin,
};
}
/** One-ply immediate score/resource baseline; it performs no search or opponent modeling. */
export class GreedyMacroBot implements MacroBot<GreedyEvaluation> {
readonly name: string;
constructor(private readonly options: GreedyMacroBotOptions = {}) {
this.name = options.valueMode === "income-normalized" ? "income-normalized-greedy-macro" : "greedy-macro";
}
select(engine: Engine): MacroBotSelection<GreedyEvaluation> {
const macroSet = buildBotMacroSet(engine, this.options.macroBuildOptions);
const candidates = macroSet.macros.map((macro) => {
const destination = applyMacroHostStyle(engine, macro);
const evaluation = greedyEvaluation(engine, destination, this.options.valueMode ?? "immediate");
return { macro, destination, evaluation, value: evaluation.value };
});
const best = chooseFixedFrame(macroSet.actor, candidates);
return {
bot: this.name,
macroSet,
macro: best.macro,
evaluation: best.evaluation,
};
}
}

View file

@ -0,0 +1,34 @@
import Engine from "../../engine";
import { evaluateHeuristic, HeuristicEvaluationOptions, HeuristicEvaluationReport } from "../evaluation";
import { applyMacroHostStyle, buildBotMacroSet, chooseFixedFrame } from "./common";
import { MacroBot, MacroBotBuildOptions, MacroBotSelection } from "./types";
export interface HeuristicMacroBotOptions extends MacroBotBuildOptions {
evaluation?: Omit<HeuristicEvaluationOptions, "transition">;
}
/** Deterministic, inspectable one-ply heuristic baseline. No tree or lookahead is constructed. */
export class HeuristicMacroBot implements MacroBot<HeuristicEvaluationReport> {
readonly name = "heuristic-macro";
constructor(private readonly options: HeuristicMacroBotOptions = {}) {}
select(engine: Engine): MacroBotSelection<HeuristicEvaluationReport> {
const macroSet = buildBotMacroSet(engine, this.options.macroBuildOptions);
const candidates = macroSet.macros.map((macro) => {
const destination = applyMacroHostStyle(engine, macro);
const evaluation = evaluateHeuristic(destination, {
...this.options.evaluation,
transition: { source: engine, macro },
});
return { macro, destination, evaluation, value: evaluation.value };
});
const best = chooseFixedFrame(macroSet.actor, candidates);
return {
bot: this.name,
macroSet,
macro: best.macro,
evaluation: best.evaluation,
};
}
}

View file

@ -0,0 +1,33 @@
import Engine from "../../engine";
import { rngFromString } from "../../fuzz/rng";
import { buildBotMacroSet } from "./common";
import { MacroBot, MacroBotBuildOptions, MacroBotSelection } from "./types";
export interface RandomMacroEvaluation {
randomIndex: number;
macroCount: number;
}
/** Correctness/smoke baseline: uniform sampling over the already-committed Phase 1.4 macros. */
export class RandomMacroBot implements MacroBot<RandomMacroEvaluation> {
readonly name = "random-macro";
private readonly rng: () => number;
constructor(
seed: string,
private readonly options: MacroBotBuildOptions = {}
) {
this.rng = rngFromString(seed);
}
select(engine: Engine): MacroBotSelection<RandomMacroEvaluation> {
const macroSet = buildBotMacroSet(engine, this.options.macroBuildOptions);
const randomIndex = Math.floor(this.rng() * macroSet.macros.length);
return {
bot: this.name,
macroSet,
macro: macroSet.macros[randomIndex],
evaluation: { randomIndex, macroCount: macroSet.macros.length },
};
}
}

View file

@ -0,0 +1,109 @@
import Engine from "../../engine";
import { CommittedTurnMacro, CommittedTurnMacroBuildOptions } from "../actions/turn-builder";
import { HeuristicEvaluationOptions } from "../evaluation";
import { FixedFrameSearch, RootReuseVisitPolicy, SearchDiagnostics, SearchMode } from "../search/core";
import {
EngineSearchDomain,
NonNeuralPriorOptions,
NonNeuralPriorReport,
pinnedSearchMacroBuildOptions,
} from "../search/engine-domain";
import { GreedyValueMode } from "./greedy";
import { MacroBot, MacroBotSelection } from "./types";
export const SEARCH_MACRO_EVALUATION_SCHEMA = "gaia-ai-search-macro-evaluation/v1" as const;
export interface SearchMacroBotOptions {
simulations: number;
mode?: SearchMode;
explorationConstant?: number;
puctValueScale?: number;
rootReuseVisitPolicy?: RootReuseVisitPolicy;
seed?: string;
gumbelMaxActions?: number;
gumbelValueScale?: number;
transpositions?: boolean;
macroBuildOptions?: CommittedTurnMacroBuildOptions;
evaluation?: Omit<HeuristicEvaluationOptions, "transition">;
leafGreedyMix?: number;
greedyValueMode?: GreedyValueMode;
nonTerminalPassValuePenalty?: number;
prior?: NonNeuralPriorOptions;
}
export interface SearchMacroEvaluation {
schemaVersion: typeof SEARCH_MACRO_EVALUATION_SCHEMA;
value: number;
macroBuildOptions: CommittedTurnMacroBuildOptions;
prior: NonNeuralPriorReport;
diagnostics: SearchDiagnostics;
}
export function isSearchMacroEvaluation(value: unknown): value is SearchMacroEvaluation {
if (typeof value !== "object" || value === null) {
return false;
}
return (
Object.prototype.hasOwnProperty.call(value, "schemaVersion") &&
Object.prototype.hasOwnProperty.call(value, "diagnostics")
);
}
/** Stateful offline Phase 2 bot with fixed-budget PUCT or seeded Gumbel root allocation. */
export class SearchMacroBot implements MacroBot<SearchMacroEvaluation> {
readonly name: string;
private readonly domain: EngineSearchDomain;
private readonly searchTree: FixedFrameSearch<Engine, CommittedTurnMacro>;
constructor(private readonly options: SearchMacroBotOptions) {
const mode = options.mode ?? "puct";
this.name = mode === "puct" ? "puct-search" : "gumbel-search";
this.domain = new EngineSearchDomain({
macroBuildOptions: pinnedSearchMacroBuildOptions(options.macroBuildOptions),
evaluation: options.evaluation,
leafGreedyMix: options.leafGreedyMix,
greedyValueMode: options.greedyValueMode,
nonTerminalPassValuePenalty: options.nonTerminalPassValuePenalty,
prior: options.prior,
});
this.searchTree = new FixedFrameSearch(this.domain, {
simulations: options.simulations,
mode,
explorationConstant: options.explorationConstant,
puctValueScale: options.puctValueScale,
rootReuseVisitPolicy: options.rootReuseVisitPolicy,
seed: options.seed,
gumbelMaxActions: options.gumbelMaxActions,
gumbelValueScale: options.gumbelValueScale,
transpositions: options.transpositions,
});
}
select(engine: Engine): MacroBotSelection<SearchMacroEvaluation> {
const result = this.searchTree.search(engine);
const rootKey = result.diagnostics.deterministic.rootStateKey;
const macroSet = this.domain.macroSet(rootKey);
const macro = result.action;
if (!macroSet.macros.some((candidate) => candidate.key === macro.key)) {
throw new Error(`Search selected macro ${macro.key} outside its committed macro set`);
}
const evaluation: SearchMacroEvaluation = {
schemaVersion: SEARCH_MACRO_EVALUATION_SCHEMA,
value: result.diagnostics.deterministic.selectedMeanValue,
macroBuildOptions: this.domain.macroBuildOptions,
prior: this.domain.priorReport(rootKey),
diagnostics: result.diagnostics,
};
this.searchTree.advanceSelectedAction(result.actionKey);
return {
bot: this.name,
macroSet,
macro,
evaluation,
};
}
reset(): void {
this.searchTree.reset();
}
}

View file

@ -0,0 +1,453 @@
import Engine from "../../engine";
import { Building, Command, Player, ResearchField, Resource } from "../../enums";
import PlayerInstance from "../../player";
import { CommittedTurnMacro } from "../actions/turn-builder";
import { evaluateHeuristic, HeuristicEvaluationOptions, HeuristicEvaluationReport } from "../evaluation";
import {
economyPlanApplies,
EconomyPlanTransitionReport,
EconomyReserveBundle,
evaluateEconomyPlanTransition,
} from "../strategy/economy-plan";
import {
assessOpeningPlan,
evaluateOpeningPlanTransition,
openingPlanApplies,
OpeningPlanAssessment,
OpeningPlanId,
OpeningPlanTransitionReport,
rankOpeningPlans,
} from "../strategy/opening-plans";
import {
assessResearchPlan,
evaluateResearchPlanTransition,
rankResearchPlans,
RESEARCH_PLAN_ID,
researchPlanApplies,
ResearchPlanAssessment,
ResearchPlanId,
ResearchPlanTransitionReport,
} from "../strategy/research-plan";
import {
evaluateStrategyTempoTransition,
strategyTempoApplies,
StrategyTempoTransitionReport,
} from "../strategy/tempo";
import { applyMacroHostStyle, buildBotMacroSet, chooseFixedFrame } from "./common";
import { MacroBot, MacroBotBuildOptions, MacroBotSelection } from "./types";
export const STRATEGY_PLAN_BOT_SCHEMA = "gaia-ai-strategy-plan-bot/v4" as const;
export interface StrategyPlanMacroBotOptions extends MacroBotBuildOptions {
evaluation?: Omit<HeuristicEvaluationOptions, "transition">;
/** Plan switching requires a material priority lead; ordinary fluctuations keep the plan stable. */
switchThreshold?: number;
/** Optional diagnostic opportunity cost for Pass; zero preserves the validated plan policy. */
productivePassPenalty?: number;
/** Diagnostic only: gate Advanced Tech goals on a Federation formable this exact turn. */
federationFeasibilityGate?: boolean;
/**
* Opt-in compatible-income / action-budget economic plan. When enabled it scores each macro
* against the active plan's reserved cost bundle (combination coverage, cap waste, stranded
* surplus, wasteful spend, resource-preserving Pass). Default false preserves the frozen policy
* exactly.
*/
economyPlanning?: boolean;
}
export interface StrategyPlanSelectionReport {
schemaVersion: typeof STRATEGY_PLAN_BOT_SCHEMA;
value: number;
heuristic: HeuristicEvaluationReport;
activePlan: OpeningPlanId | ResearchPlanId | null;
researchTarget: ResearchField | null;
planDecision: string;
planCandidates: readonly (OpeningPlanAssessment | ResearchPlanAssessment)[];
transition: OpeningPlanTransitionReport | ResearchPlanTransitionReport | null;
tempo: StrategyTempoTransitionReport | null;
economy: EconomyPlanTransitionReport | null;
}
interface EvaluatedMacro {
macro: CommittedTurnMacro;
destination: Engine;
heuristic: HeuristicEvaluationReport;
transition: OpeningPlanTransitionReport | ResearchPlanTransitionReport | null;
tempo: StrategyTempoTransitionReport | null;
economy: EconomyPlanTransitionReport | null;
value: number;
}
interface PlanDecision {
plan: OpeningPlanId | ResearchPlanId | null;
researchTarget: ResearchField | null;
reason: string;
candidates: readonly (OpeningPlanAssessment | ResearchPlanAssessment)[];
}
function emptyBundle(): EconomyReserveBundle {
return { credits: 0, ores: 0, knowledge: 0, qics: 0 };
}
function addBuildingCost(bundle: EconomyReserveBundle, player: PlayerInstance, building: Building): void {
for (const cost of player.board.cost(building, false)) {
switch (cost.type) {
case Resource.Credit:
bundle.credits += cost.count;
break;
case Resource.Ore:
bundle.ores += cost.count;
break;
case Resource.Knowledge:
bundle.knowledge += cost.count;
break;
case Resource.Qic:
bundle.qics += cost.count;
break;
}
}
}
function availableAcademy(player: PlayerInstance): Building {
return player.data.buildings[Building.Academy1] < player.maxBuildings(Building.Academy1)
? Building.Academy1
: Building.Academy2;
}
/** The plan's remaining building chain from the current stage, in build order. */
function openingChain(player: PlayerInstance, plan: OpeningPlanId): Building[] {
const buildings = player.data.buildings;
if (plan === "academy-engine") {
if (buildings[Building.Academy1] + buildings[Building.Academy2] > 0) {
return [];
}
if (buildings[Building.ResearchLab] > 0) {
return [availableAcademy(player)];
}
if (buildings[Building.TradingStation] > 0) {
return [Building.ResearchLab, availableAcademy(player)];
}
return [Building.TradingStation, Building.ResearchLab, availableAcademy(player)];
}
if (plan === "planetary-institute-engine") {
if (buildings[Building.PlanetaryInstitute] > 0) {
return [];
}
if (buildings[Building.TradingStation] > 0) {
return [Building.PlanetaryInstitute];
}
return [Building.TradingStation, Building.PlanetaryInstitute];
}
const target = Math.min(5, player.maxBuildings(Building.Mine));
const remaining = Math.max(0, Math.min(3, target - buildings[Building.Mine]));
return new Array<Building>(remaining).fill(Building.Mine);
}
/**
* The action budget for the current round: the summed cost bundle of the plan's next few meaningful
* actions, not just the single immediate prerequisite. Coverage and stranded-surplus are measured
* against this so the economy is judged compatible with executing a whole round, which is what the
* diagnosed zero-action middle rounds lacked. An absent plan yields an empty budget.
*/
export function roundActionBudget(
engine: Engine,
actor: Player,
plan: OpeningPlanId | ResearchPlanId | null,
researchTarget: ResearchField | null
): EconomyReserveBundle {
const bundle = emptyBundle();
const player = engine.player(actor);
if (plan && plan !== RESEARCH_PLAN_ID) {
for (const building of openingChain(player, plan as OpeningPlanId)) {
addBuildingCost(bundle, player, building);
}
} else if (plan === RESEARCH_PLAN_ID && researchTarget) {
const level = player.data.research[researchTarget];
const steps = Math.max(1, Math.min(2, 5 - level));
bundle.knowledge = 4 * steps;
}
return bundle;
}
/**
* AI-7 candidate: persistent opening and research plans over the inspectable heuristic baseline.
* It does not script actions. It rewards state progress, protects the next plan cost, penalizes
* passing while a productive plan transition exists, and reports every term.
*/
export class StrategyPlanMacroBot implements MacroBot<StrategyPlanSelectionReport> {
readonly name = "strategy-plan-macro";
private readonly activePlans = new Map<Player, OpeningPlanId>();
private readonly researchTargets = new Map<Player, ResearchField>();
private readonly switchThreshold: number;
constructor(private readonly options: StrategyPlanMacroBotOptions = {}) {
this.switchThreshold = options.switchThreshold ?? 1.25;
}
private decideOpeningPlan(engine: Engine, actor: Player): PlanDecision {
const candidates = rankOpeningPlans(engine, actor);
const best = candidates.find((candidate) => candidate.viable && !candidate.complete) ?? null;
const retainedId = this.activePlans.get(actor);
if (!retainedId) {
if (best) {
this.activePlans.set(actor, best.id);
return { plan: best.id, researchTarget: null, reason: `selected:${best.id}`, candidates };
}
return { plan: null, researchTarget: null, reason: "no-viable-opening-plan", candidates };
}
const retained = assessOpeningPlan(engine, actor, retainedId);
if (retained.complete) {
if (best) {
this.activePlans.set(actor, best.id);
return {
plan: best.id,
researchTarget: null,
reason: `completed:${retainedId}->${best.id}`,
candidates,
};
}
return { plan: null, researchTarget: null, reason: `completed:${retainedId}`, candidates };
}
if (!retained.viable) {
if (best) {
this.activePlans.set(actor, best.id);
return {
plan: best.id,
researchTarget: null,
reason: `aborted:${retainedId}->${best.id}`,
candidates,
};
}
return { plan: null, researchTarget: null, reason: `aborted:${retainedId}`, candidates };
}
if (best && best.id !== retainedId && best.priority >= retained.priority + this.switchThreshold) {
this.activePlans.set(actor, best.id);
return {
plan: best.id,
researchTarget: null,
reason: `material-switch:${retainedId}->${best.id}:${(best.priority - retained.priority).toFixed(3)}`,
candidates,
};
}
return { plan: retainedId, researchTarget: null, reason: `retained:${retainedId}`, candidates };
}
private decideResearchPlan(engine: Engine, actor: Player, federationActionAvailable: boolean): PlanDecision {
const researchContext = { federationActionAvailable };
const candidates = rankResearchPlans(engine, actor, researchContext);
const best = candidates.find((candidate) => candidate.viable && !candidate.complete) ?? null;
const retainedTarget = this.researchTargets.get(actor);
if (!retainedTarget) {
if (best) {
this.researchTargets.set(actor, best.target);
return {
plan: RESEARCH_PLAN_ID,
researchTarget: best.target,
reason: `selected:${RESEARCH_PLAN_ID}:${best.target}`,
candidates,
};
}
return { plan: null, researchTarget: null, reason: "no-viable-research-plan", candidates };
}
const retained = assessResearchPlan(engine, actor, retainedTarget, researchContext);
if (retained.complete || !retained.viable) {
if (best) {
this.researchTargets.set(actor, best.target);
return {
plan: RESEARCH_PLAN_ID,
researchTarget: best.target,
reason: `${retained.complete ? "completed" : "aborted"}:${retainedTarget}->${best.target}`,
candidates,
};
}
return {
plan: null,
researchTarget: null,
reason: `${retained.complete ? "completed" : "aborted"}:${retainedTarget}`,
candidates,
};
}
if (best && best.target !== retainedTarget && best.priority >= retained.priority + this.switchThreshold) {
this.researchTargets.set(actor, best.target);
return {
plan: RESEARCH_PLAN_ID,
researchTarget: best.target,
reason: `material-switch:${retainedTarget}->${best.target}:${(best.priority - retained.priority).toFixed(3)}`,
candidates,
};
}
return {
plan: RESEARCH_PLAN_ID,
researchTarget: retainedTarget,
reason: `retained:${RESEARCH_PLAN_ID}:${retainedTarget}`,
candidates,
};
}
private decidePlan(engine: Engine, actor: Player, federationActionAvailable: boolean): PlanDecision {
if (openingPlanApplies(engine)) {
return this.decideOpeningPlan(engine, actor);
}
if (researchPlanApplies(engine)) {
return this.decideResearchPlan(engine, actor, federationActionAvailable);
}
return { plan: null, researchTarget: null, reason: "outside-plan-horizon", candidates: [] };
}
select(engine: Engine): MacroBotSelection<StrategyPlanSelectionReport> {
const macroSet = buildBotMacroSet(engine, this.options.macroBuildOptions);
const actor = macroSet.actor;
const federationActionAvailable = this.options.federationFeasibilityGate
? macroSet.macros.some((macro) => macro.mainCommand === Command.FormFederation)
: true;
const decision = this.decidePlan(engine, actor, federationActionAvailable);
const evaluated = macroSet.macros.map((macro): EvaluatedMacro => {
const destination = applyMacroHostStyle(engine, macro);
const heuristic = evaluateHeuristic(destination, {
...this.options.evaluation,
transition: { source: engine, macro },
});
return { macro, destination, heuristic, transition: null, tempo: null, economy: null, value: heuristic.value };
});
if (decision.plan && decision.plan !== RESEARCH_PLAN_ID) {
const preliminary = evaluated.map((candidate) =>
evaluateOpeningPlanTransition(
engine,
candidate.destination,
actor,
decision.plan as OpeningPlanId,
candidate.macro.mainCommand,
false
)
);
const productiveAlternative = preliminary.some(
(transition) => transition.progressDelta > 0 || transition.reserveGain > 0
);
const orientation = actor === Player.Player1 ? 1 : -1;
for (let index = 0; index < evaluated.length; index += 1) {
const transition = evaluateOpeningPlanTransition(
engine,
evaluated[index].destination,
actor,
decision.plan as OpeningPlanId,
evaluated[index].macro.mainCommand,
productiveAlternative
);
evaluated[index].transition = transition;
evaluated[index].value = evaluated[index].heuristic.value + orientation * transition.score;
}
} else if (decision.plan === RESEARCH_PLAN_ID && decision.researchTarget) {
const preliminary = evaluated.map((candidate) =>
evaluateResearchPlanTransition(
engine,
candidate.destination,
actor,
decision.researchTarget as ResearchField,
candidate.macro.mainCommand,
false,
{ federationActionAvailable }
)
);
const productiveAlternative = preliminary.some(
(transition) =>
transition.targetProgressDelta > 0 ||
transition.standardTechDelta > 0 ||
transition.advancedTechDelta > 0 ||
transition.federationReadinessDelta > 0 ||
transition.reserveGain > 0
);
const orientation = actor === Player.Player1 ? 1 : -1;
for (let index = 0; index < evaluated.length; index += 1) {
const transition = evaluateResearchPlanTransition(
engine,
evaluated[index].destination,
actor,
decision.researchTarget,
evaluated[index].macro.mainCommand,
productiveAlternative,
{ federationActionAvailable }
);
evaluated[index].transition = transition;
evaluated[index].value = evaluated[index].heuristic.value + orientation * transition.score;
}
}
const productivePassPenalty = this.options.productivePassPenalty ?? 0;
if (strategyTempoApplies(engine) && productivePassPenalty > 0) {
const preliminary = evaluated.map((candidate) =>
evaluateStrategyTempoTransition(
engine,
candidate.destination,
actor,
candidate.macro.mainCommand,
false,
productivePassPenalty
)
);
const productiveAlternative = preliminary.some((transition) => transition.productive);
const orientation = actor === Player.Player1 ? 1 : -1;
for (let index = 0; index < evaluated.length; index += 1) {
const tempo = evaluateStrategyTempoTransition(
engine,
evaluated[index].destination,
actor,
evaluated[index].macro.mainCommand,
productiveAlternative,
productivePassPenalty
);
evaluated[index].tempo = tempo;
evaluated[index].value += orientation * tempo.score;
}
}
if (this.options.economyPlanning && economyPlanApplies(engine)) {
const bundle = roundActionBudget(engine, actor, decision.plan, decision.researchTarget);
const productiveAlternative = evaluated.some(
(candidate) =>
evaluateEconomyPlanTransition(
engine,
candidate.destination,
actor,
candidate.macro.mainCommand,
bundle,
false
).durableProgress
);
const orientation = actor === Player.Player1 ? 1 : -1;
for (let index = 0; index < evaluated.length; index += 1) {
const economy = evaluateEconomyPlanTransition(
engine,
evaluated[index].destination,
actor,
evaluated[index].macro.mainCommand,
bundle,
productiveAlternative
);
evaluated[index].economy = economy;
evaluated[index].value += orientation * economy.score;
}
}
const best = chooseFixedFrame(actor, evaluated);
return {
bot: this.name,
macroSet,
macro: best.macro,
evaluation: {
schemaVersion: STRATEGY_PLAN_BOT_SCHEMA,
value: best.value,
heuristic: best.heuristic,
activePlan: decision.plan,
researchTarget: decision.researchTarget,
planDecision: decision.reason,
planCandidates: decision.candidates,
transition: best.transition,
tempo: best.tempo,
economy: best.economy,
},
};
}
}

View file

@ -0,0 +1,23 @@
import Engine from "../../engine";
import { CommittedTurnMacro, CommittedTurnMacroBuildOptions, CommittedTurnMacroSet } from "../actions/turn-builder";
export interface MacroBotBuildOptions {
/**
* Phase 1.3 conversion integration is exact and uncapped when enabled. Baseline self-play
* defaults it off because the locked rich wallet has a measured 130,532 seed-pair branch set;
* this is a play-policy choice, not a depth, sequence, time, or beam cap in either planner.
*/
macroBuildOptions?: CommittedTurnMacroBuildOptions;
}
export interface MacroBotSelection<T = unknown> {
bot: string;
macroSet: CommittedTurnMacroSet;
macro: CommittedTurnMacro;
evaluation: T;
}
export interface MacroBot<T = unknown> {
readonly name: string;
select(engine: Engine): MacroBotSelection<T>;
}

View file

@ -0,0 +1,346 @@
import { expect } from "chai";
import Engine, { AuctionVariant, EngineOptions } from "../engine";
import { ArtifactToken, BoardAction, Operator, Phase, Player as PlayerEnum, ResearchField, Spaceship } from "../enums";
import {
CANONICAL_STATE_SCHEMA_VERSION,
canonicalJson,
CanonicalStateError,
canonicalStateHash,
canonicalStateJson,
projectCanonicalState,
} from "./canonical-state";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "./challenge";
import { bootChallengeEngine } from "./challenge-manifest";
type CorpusEntry = {
id: string;
moves: string[];
options: EngineOptions;
expectedHash?: string;
};
const BASE_SETUP_FACTION_MOVES = ["init 2 12"];
const BASE_ROUND1_START_MOVES = [
"init 2 12",
"p1 faction terrans",
"p2 faction hadsch-hallas",
"terrans build m 1B1",
"hadsch-hallas build m 5A5",
"hadsch-hallas build m 1A10",
"terrans build m 3A7",
"hadsch-hallas booster booster1",
"terrans booster booster2",
];
const BASE_LEECH_MOVES = [
"init 2 randomSeed",
"p1 faction terrans",
"p2 faction nevlas",
"terrans build m -1x2",
"nevlas build m -1x0",
"nevlas build m 0x-4",
"terrans build m -4x-1",
"nevlas booster booster7",
"terrans booster booster3",
"terrans build ts -1x2. endturn",
];
const CORPUS: CorpusEntry[] = [
{
id: "base-setup-faction",
moves: BASE_SETUP_FACTION_MOVES,
options: {},
},
{
id: "base-round1-start",
moves: BASE_ROUND1_START_MOVES,
options: {},
},
{
id: "base-round1-leech",
moves: BASE_LEECH_MOVES,
options: {},
},
{
id: "phase0-challenge",
moves: [...LOST_FLEET_CHALLENGE.scriptedPrefix],
options: challengeEngineOptions(),
},
];
function cloneOptions<T>(value: T): T {
return JSON.parse(JSON.stringify(value));
}
function buildEngine(entry: CorpusEntry): Engine {
return new Engine([...entry.moves], cloneOptions(entry.options));
}
function reverseObjectKeys<T>(value: T): T {
if (Array.isArray(value)) {
return value.map((entry) => reverseObjectKeys(entry)) as unknown as T;
}
if (value && typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>).reverse();
const result: Record<string, unknown> = {};
for (const [key, entry] of entries) {
result[key] = reverseObjectKeys(entry);
}
return result as T;
}
return value;
}
describe("canonical-state", () => {
it("uses the expected schema version", () => {
expect(CANONICAL_STATE_SCHEMA_VERSION).to.equal("gaia-ai-canonical-state/v1");
});
it("projects the fixed Phase 0 challenge state", () => {
const engine = bootChallengeEngine();
const canonical = projectCanonicalState(engine);
expect(canonical.schemaVersion).to.equal(CANONICAL_STATE_SCHEMA_VERSION);
expect(canonical.phase).to.equal(Phase.SetupBuilding);
expect(canonical.options.lostFleet).to.equal(true);
expect(canonical.players.map((player) => player.faction)).to.deep.equal(["xenos", "hadsch-hallas"]);
});
it("is byte-identical when projecting the same committed state repeatedly", () => {
for (const entry of CORPUS) {
const engine = buildEngine(entry);
expect(canonicalStateJson(engine)).to.equal(canonicalStateJson(engine), entry.id);
expect(canonicalStateHash(engine)).to.equal(canonicalStateHash(engine), entry.id);
}
});
it("matches across constructor replay, slowMotion replay, and serialize/parse hydration", () => {
for (const entry of CORPUS) {
const constructorState = buildEngine(entry);
const slowMotionState = Engine.slowMotion(
[...entry.moves],
cloneOptions(entry.options),
constructorState.version
);
const hydratedState = Engine.fromData(JSON.parse(JSON.stringify(constructorState)));
const constructorJson = canonicalStateJson(constructorState);
const slowMotionJson = canonicalStateJson(slowMotionState);
const hydratedJson = canonicalStateJson(hydratedState);
expect(slowMotionJson).to.equal(constructorJson, `${entry.id} slowMotion parity`);
expect(hydratedJson).to.equal(constructorJson, `${entry.id} hydration parity`);
expect(canonicalStateHash(slowMotionState)).to.equal(
canonicalStateHash(constructorState),
`${entry.id} slowMotion hash`
);
expect(canonicalStateHash(hydratedState)).to.equal(
canonicalStateHash(constructorState),
`${entry.id} hydration hash`
);
}
});
it("does not depend on object identity or object-key insertion order", () => {
const engine = buildEngine(CORPUS[2]);
const equivalentEngine = buildEngine(CORPUS[2]);
const reversedJson = reverseObjectKeys(JSON.parse(JSON.stringify(engine)));
const reversedEngine = Engine.fromData(reversedJson);
const projected = projectCanonicalState(engine);
const reversedProjected = reverseObjectKeys(projected);
expect(canonicalStateHash(equivalentEngine)).to.equal(canonicalStateHash(engine));
expect(canonicalStateHash(reversedEngine)).to.equal(canonicalStateHash(engine));
expect(canonicalJson(reversedProjected)).to.equal(canonicalJson(projected));
});
it("changes the hash when future-relevant base-game fields change", () => {
const mutations = [
{
id: "federation-option",
build: () => buildEngine(CORPUS[2]),
mutate: (engine: Engine) => {
engine.options.noFedCheck = true;
},
},
{
id: "current-player",
build: () => buildEngine(CORPUS[1]),
mutate: (engine: Engine) => {
engine.currentPlayer = PlayerEnum.Player2;
},
},
{
id: "passed-players",
build: () => buildEngine(CORPUS[1]),
mutate: (engine: Engine) => {
engine.passedPlayers = [PlayerEnum.Player1];
},
},
{
id: "board-action-owner",
build: () => buildEngine(CORPUS[2]),
mutate: (engine: Engine) => {
engine.boardActions[BoardAction.Power1] = PlayerEnum.Player1;
},
},
{
id: "player-resource",
build: () => buildEngine(CORPUS[2]),
mutate: (engine: Engine) => {
engine.players[0].data.credits += 1;
},
},
{
id: "player-research",
build: () => buildEngine(CORPUS[2]),
mutate: (engine: Engine) => {
engine.players[0].data.research[ResearchField.Terraforming] += 1;
},
},
{
id: "player-income-event-activation",
build: () => buildEngine(CORPUS[2]),
mutate: (engine: Engine) => {
engine.players[0].events[Operator.Income][0].activated = true;
},
},
{
id: "leech-offer",
build: () => buildEngine(CORPUS[2]),
mutate: (engine: Engine) => {
engine.players[1].data.leechPossible += 1;
},
},
{
id: "federation-cache",
build: () => buildEngine(CORPUS[2]),
mutate: (engine: Engine) => {
engine.players[0].federationCache = {
availableSatellites: 2,
custom: false,
federations: [],
};
},
},
];
for (const testCase of mutations) {
const original = testCase.build();
const changed = Engine.fromData(JSON.parse(JSON.stringify(original)));
testCase.mutate(changed);
expect(canonicalStateHash(changed)).to.not.equal(canonicalStateHash(original), testCase.id);
}
});
it("changes the hash when future-relevant Lost Fleet fields change", () => {
const original = bootChallengeEngine();
const changed = Engine.fromData(JSON.parse(JSON.stringify(original)));
changed.lostFleetTerraformingRow = [...changed.lostFleetTerraformingRow].reverse();
changed.players[0].data.explorationShips[Spaceship.Twilight] = 1;
changed.players[0].data.artifacts = [ArtifactToken.Credit];
expect(canonicalStateHash(changed)).to.not.equal(canonicalStateHash(original));
});
it("ignores excluded cache and log fields", () => {
const original = buildEngine(CORPUS[1]);
const mutations = [
(engine: Engine) => {
engine.availableCommands = [{ name: "pass", player: PlayerEnum.Player1 } as any];
},
(engine: Engine) => {
engine.availableCommand = { name: "pass", player: PlayerEnum.Player1 } as any;
},
(engine: Engine) => {
engine.moveHistory = [...engine.moveHistory, "display-only move"];
},
(engine: Engine) => {
engine.advancedLog = [...engine.advancedLog, { player: PlayerEnum.Player1, move: 999 }];
},
(engine: Engine) => {
engine.players[0].settings.autoIncome = !engine.players[0].settings.autoIncome;
},
(engine: Engine) => {
engine.players[0].name = "display-name";
},
(engine: Engine) => {
engine.map.distanceCache = { "-1x2": { "-1x0": 42 } };
},
(engine: Engine) => {
engine.replayVersion = "display-only";
},
(engine: Engine) => {
engine.oldPhase = Phase.RoundIncome;
},
(engine: Engine) => {
engine.processedPlayer = PlayerEnum.Player2;
},
];
for (const mutate of mutations) {
const changed = Engine.fromData(JSON.parse(JSON.stringify(original)));
mutate(changed);
expect(canonicalStateHash(changed)).to.equal(canonicalStateHash(original));
}
});
it("rejects incomplete transient states", () => {
const engine = buildEngine(CORPUS[1]);
engine.move("terrans build ts 1B1");
expect(engine.newTurn).to.equal(false);
expect(() => canonicalStateJson(engine)).to.throw(CanonicalStateError);
});
it("rejects unsupported faction-picking variants outside the standard flow", () => {
const silentAuction = new Engine(
Engine.parseMoves(`
init 3 djfjjv4k
p1 banFaction terrans
p2 banFaction lantids
p3 banFaction hadsch-hallas
p1 faction itars
p2 faction xenos
p3 faction taklons
p1 silentBid itars 15 xenos 0 taklons 10
p2 silentBid itars 15 xenos 5 taklons 8
p3 silentBid itars 7 xenos 0 taklons 0
`),
{ auction: AuctionVariant.Silent }
);
const randomFactions = new Engine(["init 3 12"], { randomFactions: true });
const banPhase = new Engine(["init 2 12"], { banPhase: true });
expect(() => canonicalStateJson(silentAuction)).to.throw(CanonicalStateError);
expect(() => canonicalStateJson(randomFactions)).to.throw(CanonicalStateError);
expect(() => canonicalStateJson(banPhase)).to.throw(CanonicalStateError);
});
it("rejects Lost Fleet states missing persisted setup randomization", () => {
const engine = bootChallengeEngine();
delete (engine as any).lostFleetTerraformingRow;
expect(() => canonicalStateJson(engine)).to.throw(CanonicalStateError);
});
it("covers a deterministic committed-state corpus", () => {
const hashes = CORPUS.map((entry) => ({
id: entry.id,
hash: canonicalStateHash(buildEngine(entry)),
}));
expect(hashes).to.deep.equal([
{ id: "base-setup-faction", hash: "a9e8e293be80425602a7b744f740274e2af008408fdfe85a4338e9ac7e8dda68" },
{ id: "base-round1-start", hash: "646ab3c7f54fd5726149dcaa14e4b0b266a8472192f1113c07f280228357ba57" },
{ id: "base-round1-leech", hash: "51df79a25990d93a45b5d7e7d15fd953c477f0730a21dee3c92c0ce815595f74" },
{ id: "phase0-challenge", hash: "91842ba26604fd58365bd37f8d2c37ff455b986c4bcf260334aa01a21f242fbe" },
]);
});
});

View file

@ -0,0 +1,570 @@
import { createHash } from "crypto";
import Engine, { EngineOptions } from "../engine";
import {
AdvTechTilePos,
Booster,
Building,
Expansion,
Federation,
Operator,
Phase,
Planet,
Player as PlayerEnum,
ResearchField,
Spaceship,
TechTilePos,
} from "../enums";
import { shipsInPlay, SpaceshipActionType } from "../spaceships";
export const CANONICAL_STATE_SCHEMA_VERSION = "gaia-ai-canonical-state/v1";
const SUPPORTED_SPACESHIP_ACTION_TYPES: readonly SpaceshipActionType[] = ["credit", "knowledge", "power", "qic"];
const EVENT_OPERATORS: readonly Operator[] = [
Operator.Once,
Operator.Income,
Operator.Trigger,
Operator.Activate,
Operator.Pass,
Operator.FourPowerBuildings,
];
const ALL_RESEARCH_FIELDS: readonly ResearchField[] = [
ResearchField.Terraforming,
ResearchField.Navigation,
ResearchField.Intelligence,
ResearchField.GaiaProject,
ResearchField.Economy,
ResearchField.Science,
];
type CanonicalPoint = {
q: number;
r: number;
s: number;
};
type CanonicalOptions = {
concurrentCharges?: true;
advancedRules: boolean;
customBoardSetup: boolean;
noFedCheck: boolean;
flexibleFederations: boolean;
lostFleet: boolean;
factionVariant: string;
factionVariantVersion: number;
};
type CanonicalMapPlacementSector = {
sector: string;
rotation: number;
center: CanonicalPoint | null;
};
type CanonicalMapHex = {
id: string;
q: number;
r: number;
s: number;
planet: Planet;
sector: string;
building: Building | null;
player: PlayerEnum | null;
federations: PlayerEnum[];
additionalMine: PlayerEnum | null;
powerRing: PlayerEnum | null;
spaceship: Spaceship | null;
sectorCenter: CanonicalPoint | null;
};
type CanonicalEvent = {
spec: string;
source: string | null;
};
type CanonicalPlayer = {
player: PlayerEnum;
faction: string | null;
dropped: boolean;
variant: { board: unknown; version: number } | null;
expansions: number;
nbPlayers: number | null;
lostFleetEconomySide: string | null;
data: {
victoryPoints: number;
bid: number;
credits: number;
ores: number;
qics: number;
knowledge: number;
power: {
area1: number;
area2: number;
area3: number;
gaia: number;
};
brainstone: string | null;
buildings: Array<{ building: string; count: number }>;
satellites: number;
research: Array<{ field: string; level: number }>;
range: number;
gaiaformers: number;
gaiaformersInGaia: number;
gaiaformersUsedForAsteroid: number;
gaiaformersUsedForOther: number;
terraformCostDiscount: number;
leechPossible: number;
tokenModifier: number;
lostPlanet: number;
federationCount: number;
powerRingsPlaced: number;
currentTinkeringTile: string | null;
usedTinkeringTiles: string[];
lostFleetCost3Planets: string[];
artifactPlanetTypes: string[];
artifacts: string[];
explorationShips: Array<{ ship: string; slot: number }>;
tiles: {
booster: string | null;
techs: Array<{ tile: string; pos: string; enabled: boolean }>;
federations: Array<{ tile: string; green: boolean }>;
};
spaceshipFederations: Array<{ tile: string; green: boolean }>;
};
events: Array<{ operator: string; events: CanonicalEvent[] }>;
federationCache: {
availableSatellites: number;
custom: boolean;
federations: Array<{
hexes: string[];
satellites: number;
newSatellites: number;
planets: number;
powerValue: number;
}>;
} | null;
};
export type CanonicalState = {
schemaVersion: typeof CANONICAL_STATE_SCHEMA_VERSION;
playerCount: number;
options: CanonicalOptions;
phase: Phase;
round: number;
actors: {
currentPlayer: PlayerEnum | null;
tempCurrentPlayer: PlayerEnum | null;
turnOrder: PlayerEnum[];
passedPlayers: PlayerEnum[];
tempTurnOrder: PlayerEnum[];
leechSources: Array<{ player: PlayerEnum; coordinates: string }>;
lastLeechSource: { player: PlayerEnum; coordinates: string } | null;
pendingCharges?: Engine["pendingCharges"];
chargeWaits?: Engine["chargeWaits"];
nextChargeId?: number;
};
setup: {
factionSelectionOrder: string[];
terraformingFederation: string | null;
scoringExtensionSide: string | null;
lostFleetTerraformingRow: string[];
lostFleetEconomySide: string | null;
boardActions: Array<{ action: string; owner: PlayerEnum | null }>;
spaceshipActions: Array<{
ship: string;
actions: Array<{ type: SpaceshipActionType; owner: PlayerEnum | null }>;
}>;
};
tiles: {
boosters: string[];
techs: Array<{ position: string; tile: string | null; count: number | null }>;
roundScoring: string[];
finalScoring: string[];
federations: Array<{ tile: string; count: number | null }>;
spaceshipTechs: Array<{ ship: string; tile: string | null; count: number | null }>;
spaceshipFederations: Array<{ ship: string; tile: string | null }>;
artifacts: string[];
};
map: {
nbPlayers: number | null;
layout: string | null;
lostFleet: boolean;
placement: {
mirror: boolean;
sectors: CanonicalMapPlacementSector[];
} | null;
hexes: CanonicalMapHex[];
};
players: CanonicalPlayer[];
};
export class CanonicalStateError extends Error {
constructor(message: string) {
super(message);
this.name = "CanonicalStateError";
}
}
export function projectCanonicalState(engine: Engine): CanonicalState {
assertCanonicalStateSupported(engine);
return {
schemaVersion: CANONICAL_STATE_SCHEMA_VERSION,
playerCount: engine.players.length,
options: projectOptions(engine.options),
phase: engine.phase,
round: engine.round,
actors: {
...(engine.options.concurrentCharges
? { pendingCharges: engine.pendingCharges, chargeWaits: engine.chargeWaits, nextChargeId: engine.nextChargeId }
: {}),
currentPlayer: normalizeNullableNumber(engine.currentPlayer),
tempCurrentPlayer: normalizeNullableNumber(engine.tempCurrentPlayer),
turnOrder: [...engine.turnOrder],
passedPlayers: [...(engine.passedPlayers ?? [])],
tempTurnOrder: [...engine.tempTurnOrder],
leechSources: engine.leechSources.map((source) => ({
player: source.player,
coordinates: source.coordinates,
})),
lastLeechSource: engine.lastLeechSource
? {
player: engine.lastLeechSource.player,
coordinates: engine.lastLeechSource.coordinates,
}
: null,
},
setup: {
factionSelectionOrder: [...engine.setup],
terraformingFederation: engine.terraformingFederation ?? null,
scoringExtensionSide: engine.scoringExtensionSide ?? null,
lostFleetTerraformingRow: [...(engine.lostFleetTerraformingRow ?? [])],
lostFleetEconomySide: engine.lostFleetEconomySide ?? null,
boardActions: engine.boardActionTypes.map((action) => ({
action,
owner: normalizeNullableNumber(engine.boardActions[action]),
})),
spaceshipActions: shipsInPlay(engine.expansions, engine.players.length).map((ship) => ({
ship,
actions: SUPPORTED_SPACESHIP_ACTION_TYPES.map((type) => ({
type,
owner: normalizeNullableNumber(engine.spaceshipActions[ship]?.[type]),
})),
})),
},
tiles: {
boosters: Booster.values(engine.expansions).filter((booster) => !!engine.tiles.boosters[booster]),
techs: [...TechTilePos.values(engine.expansions), ...AdvTechTilePos.values(engine.expansions)].map(
(position) => ({
position,
tile: engine.tiles.techs[position]?.tile ?? null,
count: engine.tiles.techs[position]?.count ?? null,
})
),
roundScoring: [...engine.tiles.scorings.round],
finalScoring: [...engine.tiles.scorings.final],
federations: Federation.values(engine.expansions).map((tile) => ({
tile,
count: engine.tiles.federations[tile] ?? null,
})),
spaceshipTechs: shipsInPlay(engine.expansions, engine.players.length).map((ship) => ({
ship,
tile: engine.tiles.spaceshipTechs[ship]?.tile ?? null,
count: engine.tiles.spaceshipTechs[ship]?.count ?? null,
})),
spaceshipFederations: shipsInPlay(engine.expansions, engine.players.length).map((ship) => ({
ship,
tile: engine.tiles.spaceshipFederations[ship] ?? null,
})),
artifacts: [...engine.tiles.artifacts].sort(),
},
map: {
nbPlayers: engine.map.nbPlayers ?? null,
layout: engine.map.layout ?? engine.options.layout ?? "standard",
lostFleet: !!engine.map.lostFleet,
placement: engine.map.placement
? {
mirror: !!engine.map.placement.mirror,
sectors: engine.map.placement.sectors.map((sector) => ({
sector: sector.sector,
rotation: sector.rotation,
center: sector.center ? projectPoint(sector.center) : null,
})),
}
: null,
hexes: Array.from(engine.map.grid.values())
.sort(compareHexes)
.map((hex) => ({
id: hex.toString(),
q: hex.q,
r: hex.r,
s: hex.s,
planet: hex.data.planet,
sector: hex.data.sector,
building: hex.data.building ?? null,
player: normalizeNullableNumber(hex.data.player),
federations: sortNumbers(hex.data.federations ?? []),
additionalMine: normalizeNullableNumber(hex.data.additionalMine),
powerRing: normalizeNullableNumber(hex.data.powerRing),
spaceship: hex.data.spaceship ?? null,
sectorCenter: hex.data.sectorCenter ? projectPoint(hex.data.sectorCenter) : null,
})),
},
players: engine.players.map((player) => ({
player: player.player,
faction: player.faction ?? null,
dropped: !!player.dropped,
variant: player.variant
? {
board: player.variant.board ? JSON.parse(JSON.stringify(player.variant.board)) : null,
version: player.variant.version ?? 0,
}
: null,
expansions: player.expansions,
nbPlayers: player.nbPlayers ?? null,
lostFleetEconomySide: player.lostFleetEconomySide ?? null,
data: {
victoryPoints: player.data.victoryPoints,
bid: player.data.bid,
credits: player.data.credits,
ores: player.data.ores,
qics: player.data.qics,
knowledge: player.data.knowledge,
power: {
area1: player.data.power.area1,
area2: player.data.power.area2,
area3: player.data.power.area3,
gaia: player.data.power.gaia,
},
brainstone: player.data.brainstone ?? null,
buildings: projectBuildingCounts(player.data.buildings),
satellites: player.data.satellites,
research: ALL_RESEARCH_FIELDS.map((field) => ({
field,
level: player.data.research[field] ?? 0,
})),
range: player.data.range,
gaiaformers: player.data.gaiaformers,
gaiaformersInGaia: player.data.gaiaformersInGaia,
gaiaformersUsedForAsteroid: player.data.gaiaformersUsedForAsteroid,
gaiaformersUsedForOther: player.data.gaiaformersUsedForOther,
terraformCostDiscount: player.data.terraformCostDiscount,
leechPossible: player.data.leechPossible ?? 0,
tokenModifier: player.data.tokenModifier,
lostPlanet: player.data.lostPlanet,
federationCount: player.data.federationCount,
powerRingsPlaced: player.data.powerRingsPlaced,
currentTinkeringTile: player.data.currentTinkeringTile ?? null,
usedTinkeringTiles: [...player.data.usedTinkeringTiles].sort(),
lostFleetCost3Planets: [...player.data.lostFleetCost3Planets].sort(),
artifactPlanetTypes: [...player.data.artifactPlanetTypes].sort(),
artifacts: [...player.data.artifacts].sort(),
explorationShips: Object.keys(player.data.explorationShips)
.sort()
.map((ship) => ({
ship,
slot: player.data.explorationShips[ship as Spaceship],
})),
tiles: {
booster: player.data.tiles.booster ?? null,
techs: player.data.tiles.techs.map((tech) => ({
tile: tech.tile,
pos: tech.pos,
enabled: tech.enabled,
})),
federations: player.data.tiles.federations.map((federation) => ({
tile: federation.tile,
green: federation.green,
})),
},
spaceshipFederations: player.data.spaceshipFederations.map((federation) => ({
tile: federation.tile,
green: federation.green,
})),
},
events: EVENT_OPERATORS.map((operator) => ({
operator,
events: player.events[operator].map((event) => ({
spec: event.toString(),
source: event.source ?? null,
})),
})),
federationCache: player.federationCache
? {
availableSatellites: player.federationCache.availableSatellites,
// Player.toJSON() drops the boolean `custom` flag, so a hydrated cache carries
// `undefined` here while the engine consumes it as falsy (available/federations.ts,
// `possibleFeds.length > 0 || p.federationCache.custom`). Projecting the same truthy
// coercion keeps the hash byte-identical for every live boolean value and makes
// hydrated mid-game caches hashable instead of a projection crash. A live `custom:
// true` cache still hashes differently from its hydrated `false` counterpart on
// purpose: that pair genuinely behaves differently in the current engine (the
// base-003 federation-cache staleness class).
custom: !!player.federationCache.custom,
federations: player.federationCache.federations.map((federation) => ({
hexes: federation.hexes.map((hex) => hex.toString()),
satellites: federation.satellites,
newSatellites: federation.newSatellites,
planets: federation.planets,
powerValue: federation.powerValue,
})),
}
: null,
})),
};
}
export function canonicalStateJson(engine: Engine): string {
return canonicalJson(projectCanonicalState(engine));
}
export function canonicalStateBytes(engine: Engine): Buffer {
return Buffer.from(canonicalStateJson(engine), "utf8");
}
export function canonicalStateHash(engine: Engine): string {
const json = canonicalStateJson(engine);
return createHash("sha256")
.update(CANONICAL_STATE_SCHEMA_VERSION, "utf8")
.update("\0", "utf8")
.update(json, "utf8")
.digest("hex");
}
export function canonicalJson(value: CanonicalState): string {
return stableJson(value);
}
function assertCanonicalStateSupported(engine: Engine) {
if (engine.replay) {
throw new CanonicalStateError("canonical state requires a live committed engine, not replay mode");
}
if (engine.phase === Phase.SetupInit || !engine.map || engine.players.length === 0) {
throw new CanonicalStateError("canonical state requires an initialized committed game state");
}
if (!engine.newTurn) {
throw new CanonicalStateError("canonical state requires engine.newTurn === true");
}
if (engine.turnMoves.length > 0 || engine.pendingMove !== "") {
throw new CanonicalStateError("canonical state rejects incomplete turn scaffolding");
}
if (engine.options.auction) {
throw new CanonicalStateError(`unsupported faction-picking option: auction=${engine.options.auction}`);
}
if (engine.options.randomFactions) {
throw new CanonicalStateError("unsupported faction-picking option: randomFactions");
}
if (engine.options.banPhase) {
throw new CanonicalStateError("unsupported faction-picking option: banPhase");
}
if (
[Phase.SetupFactionBan, Phase.SetupAuction, Phase.SetupSilentBid, Phase.SetupPreferenceBid].includes(engine.phase)
) {
throw new CanonicalStateError(`unsupported faction-picking phase: ${engine.phase}`);
}
if ((engine.randomFactions?.length ?? 0) > 0) {
throw new CanonicalStateError("unsupported faction-picking state: engine.randomFactions is populated");
}
if ((engine.bannedFactions?.length ?? 0) > 0) {
throw new CanonicalStateError("unsupported faction-picking state: bannedFactions is populated");
}
if ((engine.silentAuctionBids?.length ?? 0) > 0 || (engine.silentAuctionLog?.length ?? 0) > 0) {
throw new CanonicalStateError("unsupported faction-picking state: silent auction state is populated");
}
if (!engine.map.placement) {
throw new CanonicalStateError("canonical state requires map.placement to be present");
}
if (
engine.options.lostFleet &&
(!engine.lostFleetTerraformingRow || !engine.scoringExtensionSide || !engine.lostFleetEconomySide)
) {
throw new CanonicalStateError("canonical Lost Fleet state requires persisted setup randomization fields");
}
for (const player of engine.players) {
if (player.data.temporaryRange !== 0 || player.data.temporaryStep !== 0) {
throw new CanonicalStateError("canonical state rejects unresolved temporary move modifiers");
}
if ((player.data as any).turns !== 0) {
throw new CanonicalStateError("canonical state rejects unresolved multi-turn move state");
}
if ((player.data as any).brainstoneDest !== undefined) {
throw new CanonicalStateError("canonical state rejects unresolved brainstone choice state");
}
if ((player.data as any).toPick !== undefined) {
throw new CanonicalStateError("canonical state rejects unresolved reward-pick state");
}
}
}
function projectOptions(options: EngineOptions): CanonicalOptions {
return {
...(options.concurrentCharges ? { concurrentCharges: true as const } : {}),
advancedRules: !!options.advancedRules,
customBoardSetup: !!options.customBoardSetup,
noFedCheck: !!options.noFedCheck,
flexibleFederations: !!options.flexibleFederations,
lostFleet: !!options.lostFleet,
factionVariant: options.factionVariant ?? "standard",
factionVariantVersion: options.factionVariantVersion ?? 0,
};
}
function projectBuildingCounts(counts: Record<string, number>): Array<{ building: string; count: number }> {
return Building.values(Expansion.All)
.slice()
.sort()
.map((building) => ({
building,
count: counts?.[building] ?? 0,
}));
}
function projectPoint(point: { q: number; r: number; s: number }): CanonicalPoint {
return { q: point.q, r: point.r, s: point.s };
}
function normalizeNullableNumber(value: number | undefined | null): number | null {
return value === undefined || value === null ? null : value;
}
function sortNumbers(values: number[]): number[] {
return [...values].sort((a, b) => a - b);
}
function compareHexes(left: { q: number; r: number; s: number }, right: { q: number; r: number; s: number }): number {
return left.q - right.q || left.r - right.r || left.s - right.s;
}
function stableJson(value: unknown): string {
if (value === null) {
return "null";
}
if (typeof value === "string") {
return JSON.stringify(value);
}
if (typeof value === "number") {
if (!Number.isFinite(value)) {
throw new CanonicalStateError(`non-finite number in canonical state: ${value}`);
}
return JSON.stringify(value);
}
if (typeof value === "boolean") {
return value ? "true" : "false";
}
if (Array.isArray(value)) {
return `[${value.map((entry) => stableJson(entry)).join(",")}]`;
}
if (typeof value === "object") {
const record = value as Record<string, unknown>;
const keys = Object.keys(record).sort();
for (const key of keys) {
if (record[key] === undefined) {
throw new CanonicalStateError(`undefined canonical field: ${key}`);
}
}
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;
}
throw new CanonicalStateError(`unsupported canonical value type: ${typeof value}`);
}

View file

@ -0,0 +1,42 @@
import { expect } from "chai";
import { Phase } from "../enums";
import { LOST_FLEET_CHALLENGE } from "./challenge";
import {
assertValidChallengeManifest,
bootChallengeEngine,
challengeManifestSha256,
generateChallengeManifest,
} from "./challenge-manifest";
import goldenManifest from "./challenge-manifest.v1.json";
describe("Phase 0 AI challenge manifest", () => {
it("boots only through deterministic faction choice", () => {
const engine = bootChallengeEngine();
expect(engine.phase).to.equal(Phase.SetupBuilding);
expect(engine.newTurn).to.equal(true);
expect(engine.players.map((player) => player.faction)).to.deep.equal(
LOST_FLEET_CHALLENGE.seats.map((seat) => seat.faction)
);
expect(engine.players.every((player) => player.data.occupied.length === 0)).to.equal(true);
expect(engine.players.every((player) => player.data.tiles.booster === null)).to.equal(true);
expect(LOST_FLEET_CHALLENGE.strategicSetupDecisions).to.deep.equal(["starting-buildings", "round-boosters"]);
});
it("matches the checked-in manifest generated from the real engine", () => {
const generated = generateChallengeManifest();
assertValidChallengeManifest(generated);
expect(generated).to.deep.equal(goldenManifest);
});
it("is deterministic and covers separate Space and Deep Space fields", () => {
const first = generateChallengeManifest();
const second = generateChallengeManifest();
expect(challengeManifestSha256(first)).to.equal(challengeManifestSha256(second));
expect(first.map.objectives.space.sectorIds).to.not.be.empty;
expect(first.map.objectives.deepSpace.sectorIds).to.not.be.empty;
expect(first.setup.finalScoring.objectives.space).to.have.property("selected");
expect(first.setup.finalScoring.objectives.deepSpace).to.have.property("selected");
});
});

View file

@ -0,0 +1,355 @@
import { createHash } from "crypto";
import Engine from "../engine";
import { AdvTechTilePos, Booster, Federation, FinalTile, Phase, ResearchField, TechTilePos } from "../enums";
import Event from "../events";
import { classifySectorId, lostFleetSectorKey, LostFleetSectorType } from "../lost-fleet-map";
import { researchEvents } from "../research-tracks";
import Reward from "../reward";
import { EXPLORATION_CHARGE_TRACK, shipsInPlay, spaceshipBoards } from "../spaceships";
import { artifactTokenRewards, artifactTokenSpec } from "../tiles/artifacts";
import { boosterEvents } from "../tiles/boosters";
import { federationRewards } from "../tiles/federations";
import { finalScoringNeutralPlayer, finalScorings, roundScoringEvents } from "../tiles/scoring";
import { spaceshipFederationSpec } from "../tiles/spaceship-federations";
import { spaceshipTechSpec } from "../tiles/spaceship-techs";
import { techTileEvents } from "../tiles/techs";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "./challenge";
interface RewardManifest {
count: number;
type: string;
}
interface EventManifest {
spec: string;
condition: string;
operator: string;
rewards: RewardManifest[];
}
function rewardManifest(reward: Reward): RewardManifest {
return { count: reward.count, type: reward.type };
}
function eventManifest(event: Event): EventManifest {
return {
spec: event.spec,
condition: event.condition,
operator: event.operator,
rewards: event.rewards.map(rewardManifest),
};
}
function finalTileManifest(engine: Engine, tile: FinalTile, selected: boolean) {
const scoring = finalScorings[tile];
return {
id: tile,
selected,
condition: scoring.condition,
neutralPlayer: finalScoringNeutralPlayer(tile, engine.expansions),
};
}
function stableValue(value: any): any {
if (Array.isArray(value)) {
return value.map(stableValue);
}
if (value && typeof value === "object") {
return Object.keys(value)
.sort()
.reduce((result, key) => {
result[key] = stableValue(value[key]);
return result;
}, {});
}
return value;
}
export function stableManifestJson(manifest: any, spacing = 2): string {
return JSON.stringify(stableValue(manifest), null, spacing);
}
export function challengeManifestSha256(manifest: any): string {
return createHash("sha256").update(stableManifestJson(manifest, 0)).digest("hex");
}
export function bootChallengeEngine(): Engine {
return new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
}
function buildChallengeManifest() {
const engine = bootChallengeEngine();
const selectedFinalTiles = engine.tiles.scorings.final;
const standardTechPositions = TechTilePos.values(engine.expansions);
const advancedTechPositions = AdvTechTilePos.values(engine.expansions);
const ships = shipsInPlay(engine.expansions, engine.players.length);
const mapHexes = Array.from(engine.map.grid.values())
.map((hex) => ({
id: hex.toString(),
q: hex.q,
r: hex.r,
s: hex.s,
planet: hex.data.planet,
hasPlanet: hex.hasPlanet(),
sectorId: hex.data.sector,
sectorKey: lostFleetSectorKey(hex) ?? null,
sectorType: classifySectorId(hex.data.sector),
spaceship: hex.data.spaceship ?? null,
adjacent: engine.map.grid
.neighbours(hex)
.map((neighbour) => neighbour.toString())
.sort(),
}))
.sort((a, b) => a.id.localeCompare(b.id));
const spaceSectorIds = [
...new Set(
mapHexes
.filter((hex) => hex.sectorType === LostFleetSectorType.Space)
.map((hex) => hex.sectorKey)
.filter((sector): sector is string => sector !== null)
),
].sort();
const deepSpaceSectorIds = [
...new Set(
mapHexes
.filter((hex) => hex.sectorType === LostFleetSectorType.DeepSpace)
.map((hex) => hex.sectorKey)
.filter((sector): sector is string => sector !== null)
),
].sort();
const manifest = {
schemaVersion: LOST_FLEET_CHALLENGE.schemas.manifest,
challenge: {
id: LOST_FLEET_CHALLENGE.id,
version: LOST_FLEET_CHALLENGE.version,
schemas: LOST_FLEET_CHALLENGE.schemas,
seed: LOST_FLEET_CHALLENGE.seed,
playerCount: LOST_FLEET_CHALLENGE.playerCount,
options: LOST_FLEET_CHALLENGE.options,
seats: LOST_FLEET_CHALLENGE.seats,
fixedTurnOrder: LOST_FLEET_CHALLENGE.fixedTurnOrder,
scriptedPrefix: LOST_FLEET_CHALLENGE.scriptedPrefix,
scriptedPrefixScope: LOST_FLEET_CHALLENGE.scriptedPrefixScope,
strategicSetupDecisions: LOST_FLEET_CHALLENGE.strategicSetupDecisions,
},
engine: {
stateSchemaVersion: LOST_FLEET_CHALLENGE.schemas.engine,
phaseAfterScriptedPrefix: engine.phase,
roundAfterScriptedPrefix: engine.round,
playerToMoveAfterScriptedPrefix: engine.playerToMove,
seatsAfterScriptedPrefix: engine.players.map((player) => ({
player: player.player,
faction: player.faction,
})),
setupBuildingTurnOrder: [...engine.turnOrder],
newTurn: engine.newTurn,
},
setup: {
roundScoring: engine.tiles.scorings.round.map((tile, index) => ({
round: index + 1,
id: tile,
effects: roundScoringEvents(tile, index + 1).map(eventManifest),
})),
finalScoring: {
selected: selectedFinalTiles.map((tile, index) => ({
position: index + 1,
...finalTileManifest(engine, tile, true),
})),
objectives: {
space: finalTileManifest(engine, FinalTile.Sector, selectedFinalTiles.includes(FinalTile.Sector)),
deepSpace: finalTileManifest(
engine,
FinalTile.DeepSpaceSector,
selectedFinalTiles.includes(FinalTile.DeepSpaceSector)
),
},
},
boosters: Booster.values(engine.expansions)
.filter((booster) => engine.tiles.boosters[booster] === true)
.map((booster) => ({
id: booster,
effects: boosterEvents(booster).map(eventManifest),
})),
technology: {
standard: standardTechPositions.map((position) => {
const seeded = engine.tiles.techs[position];
return {
position,
id: seeded.tile,
copies: seeded.count,
effects: techTileEvents({ position, pos: position, tile: seeded.tile } as any).map(eventManifest),
};
}),
advanced: advancedTechPositions.map((position) => {
const seeded = engine.tiles.techs[position];
return {
position,
id: seeded.tile,
copies: seeded.count,
effects: techTileEvents({ position, pos: position, tile: seeded.tile } as any).map(eventManifest),
};
}),
},
federations: {
supply: Federation.values(engine.expansions).map((federation) => ({
id: federation,
count: engine.tiles.federations[federation],
rewards: federationRewards(federation).map(rewardManifest),
})),
terraformingFederation: engine.terraformingFederation,
},
lostFleet: {
economySide: {
id: engine.lostFleetEconomySide,
level3Effects: researchEvents(ResearchField.Economy, 3, engine.expansions, engine.lostFleetEconomySide).map(
eventManifest
),
level4Effects: researchEvents(ResearchField.Economy, 4, engine.expansions, engine.lostFleetEconomySide).map(
eventManifest
),
},
scoringExtensionSide: engine.scoringExtensionSide,
terraformingRow: [...engine.lostFleetTerraformingRow],
},
spaceships: ships.map((ship) => {
const coordinate = mapHexes.find((hex) => hex.spaceship === ship)?.id ?? null;
const tech = engine.tiles.spaceshipTechs[ship];
const federation = engine.tiles.spaceshipFederations[ship];
return {
id: ship,
coordinate,
technology: tech ? { id: tech.tile, copies: tech.count, effect: spaceshipTechSpec[tech.tile] } : null,
federation: federation ? { id: federation, effect: spaceshipFederationSpec[federation] } : null,
actions: spaceshipBoards[ship].actions.map((action) => ({ ...action })),
shuttleSlots: EXPLORATION_CHARGE_TRACK.map((charge, index) => ({ slot: index + 1, charge })),
};
}),
artifacts: engine.tiles.artifacts.map((artifact, index) => ({
slot: index + 1,
id: artifact,
effect: artifactTokenSpec[artifact],
rewardSpec: artifactTokenRewards[artifact] ?? null,
})),
},
map: {
placements: engine.map.placement.sectors.map((sector) => ({
sector: sector.sector,
rotation: sector.rotation,
center: { q: sector.center.q, r: sector.center.r, s: sector.center.s },
})),
mirror: engine.map.placement.mirror ?? false,
hexes: mapHexes,
objectives: {
space: {
sectorType: LostFleetSectorType.Space,
sectorIds: spaceSectorIds,
},
deepSpace: {
sectorType: LostFleetSectorType.DeepSpace,
sectorIds: deepSpaceSectorIds,
},
},
},
};
assertValidChallengeManifest(manifest);
return manifest;
}
export type ChallengeManifest = ReturnType<typeof buildChallengeManifest>;
export function generateChallengeManifest(): ChallengeManifest {
return buildChallengeManifest();
}
export function validateChallengeManifest(manifest: any): string[] {
const errors: string[] = [];
const expectedSeats = LOST_FLEET_CHALLENGE.seats;
if (manifest.schemaVersion !== LOST_FLEET_CHALLENGE.schemas.manifest) {
errors.push(`manifest schema must be ${LOST_FLEET_CHALLENGE.schemas.manifest}`);
}
if (manifest.engine.phaseAfterScriptedPrefix !== Phase.SetupBuilding) {
errors.push(`scripted prefix must stop at ${Phase.SetupBuilding}`);
}
if (manifest.engine.newTurn !== true) {
errors.push("scripted prefix must end at a committed turn boundary");
}
if (
manifest.engine.seatsAfterScriptedPrefix.length !== expectedSeats.length ||
manifest.engine.seatsAfterScriptedPrefix.some(
(seat, index) => seat.player !== expectedSeats[index].player || seat.faction !== expectedSeats[index].faction
)
) {
errors.push("real engine seats after the scripted prefix must match the fixed challenge assignment");
}
if (manifest.challenge.seats.length !== expectedSeats.length) {
errors.push("challenge must contain exactly two seats");
} else {
expectedSeats.forEach((seat, index) => {
if (manifest.challenge.seats[index].faction !== seat.faction) {
errors.push(`seat ${index} must use faction ${seat.faction}`);
}
});
}
if (manifest.challenge.strategicSetupDecisions.join(",") !== "starting-buildings,round-boosters") {
errors.push("starting buildings and round boosters must remain strategic decisions");
}
if (manifest.setup.roundScoring.length !== 6) {
errors.push("manifest must contain six round scoring tiles");
}
if (manifest.setup.finalScoring.selected.length !== 2) {
errors.push("manifest must contain two selected final scoring tiles");
}
if (
manifest.setup.finalScoring.objectives.space === undefined ||
manifest.setup.finalScoring.objectives.deepSpace === undefined
) {
errors.push("Space and Deep Space final objectives must be separate fields");
}
if (manifest.setup.boosters.length !== LOST_FLEET_CHALLENGE.playerCount + 3) {
errors.push("booster pool must contain player count plus three boosters");
}
if (manifest.setup.artifacts.length !== LOST_FLEET_CHALLENGE.playerCount) {
errors.push("Twilight must contain one artifact slot per player");
}
const ids = manifest.map.hexes.map((hex) => hex.id);
if (new Set(ids).size !== ids.length) {
errors.push("canonical map hex IDs must be unique");
}
const byId = new Map<string, any>(manifest.map.hexes.map((hex) => [hex.id, hex]));
for (const hex of manifest.map.hexes) {
for (const adjacent of hex.adjacent) {
const neighbour: any = byId.get(adjacent);
if (!neighbour) {
errors.push(`${hex.id} references missing adjacent hex ${adjacent}`);
} else if (!neighbour.adjacent.includes(hex.id)) {
errors.push(`map adjacency is not symmetric for ${hex.id} and ${adjacent}`);
}
}
}
if (manifest.map.objectives.space === undefined || manifest.map.objectives.deepSpace === undefined) {
errors.push("Space and Deep Space map objectives must be separate fields");
}
for (const ship of manifest.setup.spaceships) {
if (!ship.coordinate || byId.get(ship.coordinate)?.spaceship !== ship.id) {
errors.push(`spaceship ${ship.id} must have its exact map coordinate`);
}
if (ship.actions.length !== 3 || ship.shuttleSlots.length !== 4) {
errors.push(`spaceship ${ship.id} must contain three actions and four shuttle slots`);
}
}
return errors;
}
export function assertValidChallengeManifest(manifest: any): void {
const errors = validateChallengeManifest(manifest);
if (errors.length > 0) {
throw new Error(`Invalid challenge manifest:\n- ${errors.join("\n- ")}`);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,48 @@
import { EngineOptions } from "../engine";
import { Faction, Player } from "../enums";
import { ChallengeDefinition } from "./types";
const CHALLENGE_OPTIONS: EngineOptions = {
lostFleet: true,
officialCenterSectors: false,
advancedRules: false,
customBoardSetup: false,
noFedCheck: false,
flexibleFederations: false,
banPhase: false,
factionVariant: "standard",
factionVariantVersion: 0,
layout: "standard",
randomFactions: false,
};
/**
* Immutable Phase 0 challenge definition. Pass `challengeEngineOptions()` to Engine because Engine
* intentionally mutates the options object it receives while initializing a game.
*/
export const LOST_FLEET_CHALLENGE: ChallengeDefinition = {
id: "lost-fleet-xenos-hadsch-hallas-lf-mrj5exuu-c680",
version: "1.0.0",
schemas: {
challenge: "gaia-ai-challenge/v1",
model: "gaia-ai-model/v1",
engine: "gaia-engine-state/v1",
feature: "gaia-ai-features/v1",
manifest: "gaia-ai-challenge-manifest/v1",
},
seed: "lf-mrj5exuu-c680",
playerCount: 2,
options: CHALLENGE_OPTIONS,
seats: [
{ seat: 0, player: Player.Player1, playerId: "p1", faction: Faction.Xenos },
{ seat: 1, player: Player.Player2, playerId: "p2", faction: Faction.HadschHallas },
],
fixedTurnOrder: [Player.Player1, Player.Player2],
scriptedPrefix: ["init 2 lf-mrj5exuu-c680", "p1 faction xenos", "p2 faction hadsch-hallas"],
scriptedPrefixScope: "initialization-and-faction-choice-only",
strategicSetupDecisions: ["starting-buildings", "round-boosters"],
};
export function challengeEngineOptions(): EngineOptions {
return JSON.parse(JSON.stringify(LOST_FLEET_CHALLENGE.options));
}

View file

@ -0,0 +1,189 @@
import { expect } from "chai";
import "mocha";
import Engine from "../engine";
import { Building, Command, Phase, Player, PowerArea } from "../enums";
import { expandAtomicDecisions } from "./actions/expand";
import { buildCommittedTurnMacros } from "./actions/turn-builder";
import { applyMacroHostStyle } from "./bots/common";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "./challenge";
import {
DEFAULT_HEURISTIC_WEIGHTS,
evaluateHeuristic,
HEURISTIC_FEATURES,
orientSeatValues,
projectedEndgameResourceVictoryPoints,
terminalUtility,
} from "./evaluation";
function actorPrefix(engine: Engine): string {
return engine.player(engine.playerToMove).faction;
}
function lockedRoundOneEngine(): Engine {
const engine = new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
let guard = 20;
while (engine.phase === Phase.SetupBuilding || engine.phase === Phase.SetupBooster) {
const candidate = expandAtomicDecisions(engine).candidates[0];
engine.move(`${actorPrefix(engine)} ${candidate.moveFragment}`);
expect(--guard).to.be.greaterThan(0);
}
return engine;
}
function adjacentTradingStationSource(): Engine {
return new Engine(
[
"init 2 randomSeed",
"p1 faction terrans",
"p2 faction nevlas",
"terrans build m -1x2",
"nevlas build m -1x0",
"nevlas build m 0x-4",
"terrans build m -4x-1",
"nevlas booster booster7",
"terrans booster booster3",
],
{}
);
}
describe("Phase 2 inspectable heuristic evaluation", () => {
it("reports every stable feature exactly once with a public default weight", () => {
const report = evaluateHeuristic(lockedRoundOneEngine());
expect(report.features.map((feature) => feature.feature)).to.deep.equal([...HEURISTIC_FEATURES]);
expect(new Set(report.features.map((feature) => feature.feature)).size).to.equal(HEURISTIC_FEATURES.length);
for (const feature of HEURISTIC_FEATURES) {
expect(DEFAULT_HEURISTIC_WEIGHTS).to.have.property(feature);
}
expect(report.value).to.equal(report.features.reduce((sum, feature) => sum + feature.contribution, 0));
});
it("is deterministic and does not mutate the committed source", () => {
const engine = lockedRoundOneEngine();
const before = JSON.stringify(engine);
const first = evaluateHeuristic(engine);
const second = evaluateHeuristic(engine);
expect(second).to.deep.equal(first);
expect(JSON.stringify(engine)).to.equal(before);
});
it("applies the owner-labelled Xenos starting-Mine ranking and reports its components", () => {
const source = new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
const ranked = buildCommittedTurnMacros(source, { conversionIntegration: false })
.macros.map((macro) => {
const destination = applyMacroHostStyle(source, macro);
const report = evaluateHeuristic(destination, { transition: { source, macro } });
const placement = report.features.find((feature) => feature.feature === "setup-placement-opportunity");
return {
coordinates: macro.moveFragments[0].split(" ").pop(),
value: report.value,
placement,
};
})
.sort((left, right) => right.value - left.value);
expect(ranked.map((entry) => entry.coordinates)).to.deep.equal(["3A0", "6A4", "1A3", "2A11"]);
expect(ranked[0].placement.details.coordinates).to.equal("3A0");
expect(ranked[0].placement.details.shipAccess).to.be.greaterThan(0);
expect(ranked[0].placement.details.gaiaAccess).to.be.greaterThan(0);
expect(ranked[0].placement.details.asteroidAccess).to.be.greaterThan(0);
expect(ranked[0].placement.details.nearbyPlanetDensity).to.be.greaterThan(0);
});
it("limits the setup-placement prior to setup rather than leaking it into ordinary turns", () => {
const report = evaluateHeuristic(lockedRoundOneEngine());
const placement = report.features.find((feature) => feature.feature === "setup-placement-opportunity");
expect(placement.seat0).to.equal(0);
expect(placement.seat1).to.equal(0);
expect(placement.contribution).to.equal(0);
});
it("ablates every feature independently without changing any other term", () => {
const engine = lockedRoundOneEngine();
const baseline = evaluateHeuristic(engine);
for (const disabled of HEURISTIC_FEATURES) {
const ablated = evaluateHeuristic(engine, { disabledFeatures: [disabled] });
const baselineTerm = baseline.features.find((feature) => feature.feature === disabled);
const ablatedTerm = ablated.features.find((feature) => feature.feature === disabled);
expect(ablatedTerm.enabled, disabled).to.equal(false);
expect(ablatedTerm.contribution, disabled).to.equal(0);
expect(ablated.value, disabled).to.be.closeTo(baseline.value - baselineTerm.contribution, 1e-9);
for (const term of ablated.features.filter((feature) => feature.feature !== disabled)) {
expect(term, `${disabled} changed ${term.feature}`).to.deep.equal(
baseline.features.find((feature) => feature.feature === term.feature)
);
}
}
});
it("uses an exact terminal seat-0 margin and locks seat-swap signs", () => {
const engine = lockedRoundOneEngine();
engine.player(Player.Player1).data.victoryPoints = 137;
engine.player(Player.Player2).data.victoryPoints = 121;
engine.ended = true;
const report = evaluateHeuristic(engine);
expect(terminalUtility(engine)).to.equal(16);
expect(report.terminal).to.equal(true);
expect(report.terminalScoreMargin).to.equal(16);
expect(report.value).to.equal(16);
expect(orientSeatValues(137, 121)).to.equal(16);
expect(orientSeatValues(121, 137)).to.equal(-16);
for (const feature of report.features) {
expect(orientSeatValues(feature.seat1, feature.seat0), feature.feature).to.equal(-feature.rawMargin);
}
});
it("projects final leftover-resource conversion exactly", () => {
const engine = lockedRoundOneEngine();
const data = engine.player(Player.Player1).data;
data.credits = 7;
data.ores = 4;
data.knowledge = 5;
data.qics = 3;
data.power.area1 = 1;
data.power.area2 = 5;
data.power.area3 = 2;
data.brainstone = PowerArea.Area2;
const projected = projectedEndgameResourceVictoryPoints(engine.player(Player.Player1));
const clone = Engine.fromData(JSON.parse(JSON.stringify(engine)));
const before = clone.player(Player.Player1).data.victoryPoints;
clone.player(Player.Player1).data.finalResourceHandling();
expect(clone.player(Player.Player1).data.victoryPoints - before).to.equal(projected);
});
it("reports exact marginal leech charge and VP cost from a committed macro edge", () => {
const source = adjacentTradingStationSource();
const build = buildCommittedTurnMacros(source, { conversionIntegration: false }).macros.find(
(macro) => macro.mainCommand === Command.Build && macro.destination.leechPending
);
const leech = applyMacroHostStyle(source, build);
const macros = buildCommittedTurnMacros(leech, { conversionIntegration: false }).macros;
const charge = macros.find((macro) => macro.mainCommand === Command.ChargePower);
const destination = applyMacroHostStyle(leech, charge);
const report = evaluateHeuristic(destination, { transition: { source: leech, macro: charge } });
const term = report.features.find((feature) => feature.feature === "leech-marginal");
const actor = charge.actor;
const exactCost = leech.player(actor).data.victoryPoints - destination.player(actor).data.victoryPoints;
expect(term.details.command).to.equal(Command.ChargePower);
expect(term.details.victoryPointCost).to.equal(exactCost);
expect(term.details.charged).to.be.greaterThan(0);
expect(term.details.offered).to.equal(leech.player(actor).data.leechPossible);
});
it("reports the Trading Station discount against the exact opponent charge offer", () => {
const source = adjacentTradingStationSource();
const macro = buildCommittedTurnMacros(source, { conversionIntegration: false }).macros.find(
(candidate) =>
candidate.mainCommand === Command.Build &&
candidate.moveFragments[0].startsWith(`${Command.Build} ${Building.TradingStation} `) &&
candidate.destination.leechPending
);
const destination = applyMacroHostStyle(source, macro);
const report = evaluateHeuristic(destination, { transition: { source, macro } });
const term = report.features.find((feature) => feature.feature === "trading-station-adjacency-charge");
const opponent = macro.actor === Player.Player1 ? Player.Player2 : Player.Player1;
expect(term.details.adjacentOpponent).to.equal(true);
expect(term.details.discountCredits).to.equal(3);
expect(term.details.opponentChargeOffer).to.equal(destination.player(opponent).data.leechPossible);
});
});

691
engine/src/ai/evaluation.ts Normal file
View file

@ -0,0 +1,691 @@
import { boardActions } from "../actions";
import { ISOLATED_DISTANCE } from "../available/types";
import Engine from "../engine";
import {
ArtifactToken,
Building,
Command,
Condition,
Operator,
Phase,
Player as PlayerEnum,
PowerArea,
ResearchField,
Resource,
} from "../enums";
import Player from "../player";
import Reward from "../reward";
import { EXPLORATION_CHARGE_TRACK, shipsInPlay, spaceshipBoards } from "../spaceships";
import { boosterEvents } from "../tiles/boosters";
import { finalScoringNeutralPlayer, roundScoringEvents } from "../tiles/scoring";
import { isAdvanced, isSpaceshipTechTile } from "../tiles/techs";
import { CommittedTurnMacro } from "./actions/turn-builder";
import { scoreSetupMinePlacement, scoreSetupPlacements } from "./setup-placement";
export const HEURISTIC_EVALUATION_SCHEMA = "gaia-ai-heuristic-evaluation/v1" as const;
/**
* Public, stable feature names are the ablation surface. A feature is disabled by name, with no
* hidden coupling to the other terms. Values are always oriented once at the report boundary as
* seat 0 minus seat 1; callers never negate a value merely because the actor changed.
*/
export const HEURISTIC_FEATURES = [
"current-score",
"resource-stock",
"projected-income-credit",
"projected-income-ore",
"projected-income-knowledge",
"projected-income-qic",
"projected-income-power",
"building-supply-uncovered-income",
"setup-placement-opportunity",
"round-tile-timing",
"space-sector-progress",
"deep-space-sector-progress",
"gaia-pipeline",
"research-level-3-5-races",
"advanced-tech-prerequisites",
"standard-tech-cover-opportunity-cost",
"shared-power-ship-action-availability",
"booster-value-pass-order",
"power-bowl-capacity",
"leech-marginal",
"trading-station-adjacency-charge",
"federation-current-option-value",
"lost-planet-value",
"ship-exploration-value",
"artifact-value",
"ship-tech-value",
"ship-federation-value",
"final-scoring-projection",
"endgame-leftover-conversion",
] as const;
export type HeuristicFeature = (typeof HEURISTIC_FEATURES)[number];
export interface HeuristicEvaluationOptions {
disabledFeatures?: readonly HeuristicFeature[];
weights?: Partial<Record<HeuristicFeature, number>>;
/** Optional committed edge context for exact leech and Trading Station marginal terms. */
transition?: {
source: Engine;
macro: CommittedTurnMacro;
};
}
export interface HeuristicFeatureContribution {
feature: HeuristicFeature;
enabled: boolean;
weight: number;
seat0: number;
seat1: number;
rawMargin: number;
contribution: number;
details?: Record<string, number | string | boolean | null>;
}
export interface HeuristicEvaluationReport {
schemaVersion: typeof HEURISTIC_EVALUATION_SCHEMA;
terminal: boolean;
terminalScoreMargin: number | null;
heuristicValue: number;
/** Exact final margin at EndGame; otherwise the sum of enabled feature contributions. */
value: number;
features: HeuristicFeatureContribution[];
}
interface FeatureMeasurement {
seats: [number, number];
details?: Record<string, number | string | boolean | null>;
}
export const DEFAULT_HEURISTIC_WEIGHTS: Readonly<Record<HeuristicFeature, number>> = {
"current-score": 1,
"resource-stock": 1,
"projected-income-credit": 0.22,
"projected-income-ore": 0.8,
"projected-income-knowledge": 1,
"projected-income-qic": 1.2,
"projected-income-power": 0.13,
"building-supply-uncovered-income": 0.55,
"setup-placement-opportunity": 1,
"round-tile-timing": 0.7,
"space-sector-progress": 1.25,
"deep-space-sector-progress": 1.5,
"gaia-pipeline": 0.75,
"research-level-3-5-races": 0.65,
"advanced-tech-prerequisites": 0.8,
"standard-tech-cover-opportunity-cost": 0.7,
"shared-power-ship-action-availability": 0.45,
"booster-value-pass-order": 0.65,
"power-bowl-capacity": 0.18,
"leech-marginal": 1,
"trading-station-adjacency-charge": 1,
"federation-current-option-value": 0.7,
"lost-planet-value": 2.5,
"ship-exploration-value": 0.9,
"artifact-value": 1,
"ship-tech-value": 1.2,
"ship-federation-value": 1.4,
"final-scoring-projection": 0.45,
"endgame-leftover-conversion": 0.85,
};
const RESOURCE_STOCK_VALUES: Record<string, number> = {
[Resource.Credit]: 0.22,
[Resource.Ore]: 0.8,
[Resource.Knowledge]: 1,
[Resource.Qic]: 1.2,
};
function players(engine: Engine): [Player, Player] {
return [engine.player(PlayerEnum.Player1), engine.player(PlayerEnum.Player2)];
}
function paired(engine: Engine, measure: (player: Player) => number): [number, number] {
const pair = players(engine);
return [measure(pair[0]), measure(pair[1])];
}
/** Fixed-frame orientation helper, exported so sign behavior can be locked independently. */
export function orientSeatValues(seat0: number, seat1: number): number {
return seat0 - seat1;
}
/** Exact utility contract for a finished two-player challenge game. */
export function terminalUtility(engine: Engine): number {
return orientSeatValues(
engine.player(PlayerEnum.Player1).data.victoryPoints,
engine.player(PlayerEnum.Player2).data.victoryPoints
);
}
function remainingIncomePhases(engine: Engine): number {
if (engine.phase === Phase.EndGame) {
return 0;
}
if (engine.round <= 0) {
return 6;
}
if (engine.phase === Phase.RoundStart || engine.phase === Phase.RoundIncome) {
return Math.max(7 - engine.round, 0);
}
return Math.max(6 - engine.round, 0);
}
function projectedIncome(player: Player, engine: Engine, resource: Resource): number {
return player.resourceIncome(resource) * remainingIncomePhases(engine);
}
function resourceStock(player: Player): number {
const data = player.data;
return (
data.credits * RESOURCE_STOCK_VALUES[Resource.Credit] +
data.ores * RESOURCE_STOCK_VALUES[Resource.Ore] +
data.knowledge * RESOURCE_STOCK_VALUES[Resource.Knowledge] +
data.qics * RESOURCE_STOCK_VALUES[Resource.Qic] +
data.power.area1 * 0.05 +
data.power.area2 * 0.12 +
data.power.area3 * 0.3 +
data.power.gaia * 0.08
);
}
function buildingSupplyAndIncome(player: Player): number {
const data = player.data;
const placed =
data.buildings[Building.Mine] * 0.8 +
data.buildings[Building.TradingStation] * 1.3 +
data.buildings[Building.ResearchLab] * 1.6 +
data.buildings[Building.PlanetaryInstitute] * 2.4 +
(data.buildings[Building.Academy1] + data.buildings[Building.Academy2]) * 2.2;
const minesLeft = player.maxBuildings(Building.Mine) - data.buildings[Building.Mine];
const tradingStationsLeft = player.maxBuildings(Building.TradingStation) - data.buildings[Building.TradingStation];
const labsLeft = player.maxBuildings(Building.ResearchLab) - data.buildings[Building.ResearchLab];
const supplyFlexibility =
(minesLeft > 0 ? Math.min(minesLeft, 2) * 0.35 : -2) +
(tradingStationsLeft > 0 ? 0.4 : -0.8) +
(labsLeft > 0 ? 0.3 : -0.6);
return placed + supplyFlexibility;
}
function setupPlacementOpportunity(
engine: Engine,
transition?: HeuristicEvaluationOptions["transition"]
): FeatureMeasurement {
if (engine.round > 0) {
return { seats: [0, 0] };
}
const placementScores = players(engine).map((player) => scoreSetupPlacements(engine, player));
const seats: [number, number] = [placementScores[0].total, placementScores[1].total];
if (
!transition ||
transition.source.phase !== Phase.SetupBuilding ||
transition.macro.mainCommand !== Command.Build
) {
return { seats };
}
const actor = transition.macro.actor;
const priorCoordinates = new Set(transition.source.player(actor).data.occupied.map((hex) => hex.toString()));
const placed = engine.player(actor).data.occupied.find((hex) => !priorCoordinates.has(hex.toString()));
if (!placed) {
return { seats };
}
const score = scoreSetupMinePlacement(engine, engine.player(actor), placed.toString());
return {
seats,
details: {
actor,
coordinates: placed.toString(),
shipAccess: score.shipAccess,
opponentColorAccess: score.opponentColorAccess,
gaiaAccess: score.gaiaAccess,
asteroidAccess: score.asteroidAccess,
oneStepColorAccess: score.oneStepColorAccess,
nearbyPlanetDensity: score.nearbyPlanetDensity,
placementTotal: score.total,
},
};
}
function conditionPotential(player: Player, condition: Condition): number {
const data = player.data;
switch (condition) {
case Condition.Mine:
case Condition.NewSector:
case Condition.NewPlanetType:
return Math.min(Math.max(player.maxBuildings(Building.Mine) - data.buildings[Building.Mine], 0), 2);
case Condition.MineOnGaia:
return Math.min(data.buildings[Building.GaiaFormer] + data.gaiaformersInGaia + 1, 2);
case Condition.TradingStation:
return Math.min(data.buildings[Building.Mine], 2);
case Condition.ResearchLab:
return Math.min(data.buildings[Building.TradingStation], 2);
case Condition.BigBuilding:
return Math.min(data.buildings[Building.TradingStation] + data.buildings[Building.ResearchLab], 1);
case Condition.AdvanceResearch:
return Math.min(Math.floor(data.knowledge / 4) + 1, 2);
case Condition.TerraformStep:
return Math.min(Math.floor(data.ores / 2) + data.temporaryStep, 3);
default:
return player.eventConditionCount(condition);
}
}
function scoringTilePotential(player: Player, engine: Engine): number {
if (engine.round <= 0 || engine.round > engine.tiles.scorings.round.length) {
return 0;
}
let value = 0;
for (let round = engine.round; round <= engine.tiles.scorings.round.length; round += 1) {
const tile = engine.tiles.scorings.round[round - 1];
const distance = round - engine.round;
const timing = distance === 0 ? 1 : 0.18 / distance;
for (const event of roundScoringEvents(tile, round)) {
const victoryPoints = event.rewards
.filter((reward) => reward.type === Resource.VictoryPoint)
.reduce((sum, reward) => sum + reward.count, 0);
value += victoryPoints * conditionPotential(player, event.condition) * timing;
}
}
return value;
}
function gaiaPipeline(player: Player): number {
const data = player.data;
const available = Math.max(
data.gaiaformers - data.gaiaformersInGaia - data.buildings[Building.GaiaFormer] - data.gaiaformersUsedForAsteroid,
0
);
return (
player.eventConditionCount(Condition.Gaia) * 2 +
data.buildings[Building.GaiaFormer] * 1.7 +
data.gaiaformersInGaia * 1.1 +
available * 0.6 +
data.research[ResearchField.GaiaProject] * 0.45
);
}
function researchRace(player: Player, engine: Engine): number {
let value = 0;
for (const field of ResearchField.values(engine.expansions)) {
const level = player.data.research[field] ?? 0;
value += level * 0.5;
value += Math.max(level - 2, 0) * 4;
if (level === 2) {
value += 0.8;
}
if (level === 4 && player.data.hasGreenFederation()) {
value += 2.5;
} else if (level === 5) {
value += 5;
}
}
return value;
}
function advancedTechPrerequisites(player: Player, engine: Engine): number {
const green = player.data.hasGreenFederation() ? 1 : 0;
const enabledStandard = player.data.tiles.techs.filter(
(tile) => tile.enabled && !isAdvanced(tile.pos) && !isSpaceshipTechTile(tile.tile)
).length;
const eligibleTracks = ResearchField.values(engine.expansions).filter(
(field) => player.data.research[field] >= 4 && (engine.tiles.techs[`adv-${field}`] as any)?.count !== 0
).length;
return green * (eligibleTracks * 2 + Math.min(enabledStandard, 2) * 0.75) + eligibleTracks * 0.35;
}
function standardTechOpportunity(player: Player): number {
const penaltyByTile: Record<string, number> = {
tech1: 1.4,
tech2: 1.8,
tech3: 1.2,
tech4: 0.3,
tech5: 2.4,
tech6: 2.6,
tech7: 1.8,
tech8: 1.9,
tech9: 1.1,
"ship-tech-range": 2.4,
"ship-tech-terraform": 1.3,
"ship-tech-resource": 0.3,
};
let value = 0;
for (const tile of player.data.tiles.techs) {
if (isAdvanced(tile.pos)) {
continue;
}
const tileValue = penaltyByTile[String(tile.tile)] ?? 1;
value += tile.enabled ? Math.min(tileValue, 1) * 0.15 : -tileValue;
}
return value;
}
function sharedActionAvailability(player: Player, engine: Engine): number {
const boardAccess = engine.boardActionTypes.reduce((value, action) => {
if (engine.boardActions[action] !== null && engine.boardActions[action] !== undefined) {
return value;
}
return value + (player.data.canPay(Reward.parse(boardActions[action].cost)) ? 1 : 0);
}, 0);
let shipAccess = 0;
for (const ship of shipsInPlay(engine.expansions, engine.players.length)) {
if (!player.data.hasExplored(ship)) {
continue;
}
for (const action of spaceshipBoards[ship].actions) {
const unclaimed =
engine.spaceshipActions[ship]?.[action.type] === null ||
engine.spaceshipActions[ship]?.[action.type] === undefined;
if (unclaimed && player.data.canPay(Reward.parse(action.cost))) {
shipAccess += 0.6;
}
}
}
return boardAccess + shipAccess;
}
function boosterAndPassValue(player: Player, engine: Engine): number {
let value = 0;
const booster = player.data.tiles.booster;
if (booster) {
for (const event of boosterEvents(booster)) {
if (event.operator === Operator.Pass) {
const points = event.rewards
.filter((reward) => reward.type === Resource.VictoryPoint)
.reduce((sum, reward) => sum + reward.count, 0);
value += points * player.eventConditionCount(event.condition);
} else if (event.operator === Operator.Activate) {
value += 1.2;
}
}
}
const passIndex = (engine.passedPlayers ?? []).indexOf(player.player);
if (passIndex >= 0) {
value += (engine.players.length - passIndex) * 0.7;
}
return value;
}
function bowlCapacity(player: Player): number {
const brainstone = player.data.brainstone;
const brainstoneCapacity = brainstone === PowerArea.Area1 ? 2 : brainstone === PowerArea.Area2 ? 1 : 0;
return player.data.power.area1 * 2 + player.data.power.area2 + brainstoneCapacity;
}
function powerChargeProgress(player: Player): number {
const brainstone = player.data.brainstone;
const brainstoneProgress = brainstone === PowerArea.Area2 ? 1 : brainstone === PowerArea.Area3 ? 2 : 0;
return player.data.power.area2 + player.data.power.area3 * 2 + brainstoneProgress;
}
function challengeSeat(player: PlayerEnum): 0 | 1 {
if (player !== PlayerEnum.Player1 && player !== PlayerEnum.Player2) {
throw new Error(`AI-6 evaluator supports only the fixed two-player challenge, got player ${player}`);
}
return player as 0 | 1;
}
function leechMarginal(engine: Engine, transition?: HeuristicEvaluationOptions["transition"]): FeatureMeasurement {
const seats: [number, number] = [0, 0];
if (!transition || transition.source.phase !== Phase.RoundLeech) {
return { seats };
}
const actor = transition.macro.actor;
const sourcePlayer = transition.source.player(actor);
const destinationPlayer = engine.player(actor);
const charged = Math.max(powerChargeProgress(destinationPlayer) - powerChargeProgress(sourcePlayer), 0);
const victoryPointCost = Math.max(sourcePlayer.data.victoryPoints - destinationPlayer.data.victoryPoints, 0);
// The exact VP cost is already present in current-score. This term adds only the measured bowl
// benefit, while reporting both sides of the marginal explicitly for audit.
seats[challengeSeat(actor)] = charged * 0.45;
return {
seats,
details: {
actor,
command: transition.macro.mainCommand,
offered: sourcePlayer.data.leechPossible ?? 0,
charged,
victoryPointCost,
netPointEquivalentIncludingScore: charged * 0.45 - victoryPointCost,
},
};
}
function tradingStationMarginal(
engine: Engine,
transition?: HeuristicEvaluationOptions["transition"]
): FeatureMeasurement {
const seats: [number, number] = [0, 0];
if (!transition || transition.macro.mainCommand !== Command.Build) {
return { seats };
}
const actor = transition.macro.actor;
const sourcePlayer = transition.source.player(actor);
const destinationPlayer = engine.player(actor);
const upgraded = sourcePlayer.data.occupied.find((hex) => {
const destination = engine.map.getS(hex.toString());
return hex.buildingOf(actor) === Building.Mine && destination.buildingOf(actor) === Building.TradingStation;
});
if (!upgraded) {
return { seats };
}
const opponent = actor === PlayerEnum.Player1 ? PlayerEnum.Player2 : PlayerEnum.Player1;
const adjacentOpponent = transition.source
.player(opponent)
.data.occupied.some(
(hex) => hex.hasStructure() && transition.source.map.distance(hex, upgraded) < ISOLATED_DISTANCE
);
const discountCredits = adjacentOpponent ? 3 : 0;
const opponentChargeOffer = engine.player(opponent).data.leechPossible ?? 0;
seats[challengeSeat(actor)] = discountCredits * RESOURCE_STOCK_VALUES[Resource.Credit] - opponentChargeOffer * 0.18;
return {
seats,
details: {
actor,
coordinates: upgraded.toString(),
adjacentOpponent,
discountCredits,
opponentChargeOffer,
destinationCredits: destinationPlayer.data.credits,
},
};
}
function federationValue(player: Player): number {
const data = player.data;
const current = (data.tiles.federations.length + data.spaceshipFederations.length) * 3;
const green =
data.tiles.federations.filter((tile) => tile.green).length +
data.spaceshipFederations.filter((tile) => tile.green).length;
const target = player.federationCost;
const progress = target > 0 ? Math.min(player.fedValue / target, 1) : 0;
const unfederatedStructureValue = Math.max(player.structureValue - player.fedValue, 0);
return current + green * 1.5 + progress * 3 + Math.min(unfederatedStructureValue / Math.max(target, 1), 1.5);
}
function shipExplorationValue(player: Player, engine: Engine): number {
let value = 0;
for (const ship of shipsInPlay(engine.expansions, engine.players.length)) {
const slot = player.data.explorationShips[ship];
if (slot !== undefined) {
value += 3 + (EXPLORATION_CHARGE_TRACK[slot - 1] ?? 0) * 0.45;
}
}
return value;
}
function artifactValue(player: Player): number {
const dynamic: Record<string, number> = {
[ArtifactToken.Power]: 2.5,
[ArtifactToken.Asteroid]: 2,
[ArtifactToken.Protoplanet]: 2,
[ArtifactToken.ResearchLevel]: 2.5,
[ArtifactToken.ResearchTracks]: 2.5,
[ArtifactToken.Federation]: 2.5,
[ArtifactToken.GaiaProject]: 2.2,
[ArtifactToken.PlanetTypes]: 2.2,
[ArtifactToken.DeepSpace]: 2.2,
};
return (
player.data.artifacts.reduce((sum, artifact) => sum + (dynamic[artifact] ?? 0.7), 0) +
player.data.artifactPlanetTypes.length
);
}
function projectedFinalScoring(engine: Engine): [number, number] {
const pair = players(engine);
const scores: [number, number] = [0, 0];
const victoryPoints = [18, 12, 6, 0, 0, 0];
for (const tile of engine.tiles.scorings.final) {
const counts = pair.map((player) => player.finalCount(tile));
const ranking = counts.map((count, index) => ({ index, count }));
if (engine.players.length === 2) {
ranking.push({ index: -1, count: finalScoringNeutralPlayer(tile, engine.expansions) });
}
ranking.sort((left, right) => right.count - left.count || left.index - right.index);
for (let seat = 0; seat < pair.length; seat += 1) {
const count = counts[seat];
if (count <= 0) {
continue;
}
const first = ranking.findIndex((entry) => entry.count === count);
const ties = ranking.filter((entry) => entry.count === count).length;
const points = victoryPoints.slice(first, first + ties).reduce((sum, value) => sum + value, 0);
scores[seat] += Math.floor(points / ties);
}
}
return scores;
}
/** Exact projection of PlayerData.finalResourceHandling() without mutating the evaluated state. */
export function projectedEndgameResourceVictoryPoints(player: Player): number {
const data = player.data;
const burnable = data.burnablePower();
let area3 = data.power.area3;
let brainstone = data.brainstone;
if (burnable > 0) {
if (brainstone === PowerArea.Area2) {
brainstone = PowerArea.Area3;
area3 += burnable - 1;
} else {
area3 += burnable;
}
}
const spendable = Math.floor(area3 * data.tokenModifier) + (brainstone === PowerArea.Area3 ? 3 : 0);
const credits = Math.min(30, data.credits + spendable);
const ores = Math.min(15, data.ores + data.qics);
return Math.floor((credits + ores + data.knowledge) / 3);
}
function featureMeasurement(
feature: HeuristicFeature,
engine: Engine,
transition?: HeuristicEvaluationOptions["transition"]
): FeatureMeasurement {
switch (feature) {
case "current-score":
return { seats: paired(engine, (player) => player.data.victoryPoints) };
case "resource-stock":
return { seats: paired(engine, resourceStock) };
case "projected-income-credit":
return { seats: paired(engine, (player) => projectedIncome(player, engine, Resource.Credit)) };
case "projected-income-ore":
return { seats: paired(engine, (player) => projectedIncome(player, engine, Resource.Ore)) };
case "projected-income-knowledge":
return { seats: paired(engine, (player) => projectedIncome(player, engine, Resource.Knowledge)) };
case "projected-income-qic":
return { seats: paired(engine, (player) => projectedIncome(player, engine, Resource.Qic)) };
case "projected-income-power":
return {
seats: paired(
engine,
(player) =>
(player.resourceIncome(Resource.ChargePower) +
player.resourceIncome(Resource.GainToken) +
player.resourceIncome(Resource.GainTokenArea3)) *
remainingIncomePhases(engine)
),
};
case "building-supply-uncovered-income":
return { seats: paired(engine, buildingSupplyAndIncome) };
case "setup-placement-opportunity":
return setupPlacementOpportunity(engine, transition);
case "round-tile-timing":
return { seats: paired(engine, (player) => scoringTilePotential(player, engine)) };
case "space-sector-progress":
return { seats: paired(engine, (player) => player.eventConditionCount(Condition.Sector)) };
case "deep-space-sector-progress":
return { seats: paired(engine, (player) => player.eventConditionCount(Condition.DeepSpaceSector)) };
case "gaia-pipeline":
return { seats: paired(engine, gaiaPipeline) };
case "research-level-3-5-races":
return { seats: paired(engine, (player) => researchRace(player, engine)) };
case "advanced-tech-prerequisites":
return { seats: paired(engine, (player) => advancedTechPrerequisites(player, engine)) };
case "standard-tech-cover-opportunity-cost":
return { seats: paired(engine, standardTechOpportunity) };
case "shared-power-ship-action-availability":
return { seats: paired(engine, (player) => sharedActionAvailability(player, engine)) };
case "booster-value-pass-order":
return { seats: paired(engine, (player) => boosterAndPassValue(player, engine)) };
case "power-bowl-capacity":
return { seats: paired(engine, bowlCapacity) };
case "leech-marginal":
return leechMarginal(engine, transition);
case "trading-station-adjacency-charge":
return tradingStationMarginal(engine, transition);
case "federation-current-option-value":
return { seats: paired(engine, federationValue) };
case "lost-planet-value":
return { seats: paired(engine, (player) => player.data.lostPlanet) };
case "ship-exploration-value":
return { seats: paired(engine, (player) => shipExplorationValue(player, engine)) };
case "artifact-value":
return { seats: paired(engine, artifactValue) };
case "ship-tech-value":
return {
seats: paired(
engine,
(player) => player.data.tiles.techs.filter((tile) => isSpaceshipTechTile(tile.tile)).length
),
};
case "ship-federation-value":
return { seats: paired(engine, (player) => player.data.spaceshipFederations.length) };
case "final-scoring-projection":
return { seats: projectedFinalScoring(engine) };
case "endgame-leftover-conversion":
return { seats: paired(engine, projectedEndgameResourceVictoryPoints) };
}
}
export function evaluateHeuristic(engine: Engine, options: HeuristicEvaluationOptions = {}): HeuristicEvaluationReport {
const disabled = new Set(options.disabledFeatures ?? []);
const features = HEURISTIC_FEATURES.map((feature): HeuristicFeatureContribution => {
const measurement = featureMeasurement(feature, engine, options.transition);
const weight = options.weights?.[feature] ?? DEFAULT_HEURISTIC_WEIGHTS[feature];
const rawMargin = orientSeatValues(measurement.seats[0], measurement.seats[1]);
const enabled = !disabled.has(feature);
return {
feature,
enabled,
weight,
seat0: measurement.seats[0],
seat1: measurement.seats[1],
rawMargin,
contribution: enabled ? rawMargin * weight : 0,
details: measurement.details,
};
});
const heuristicValue = features.reduce((sum, feature) => sum + feature.contribution, 0);
const terminalScoreMargin = engine.ended ? terminalUtility(engine) : null;
return {
schemaVersion: HEURISTIC_EVALUATION_SCHEMA,
terminal: engine.ended,
terminalScoreMargin,
heuristicValue,
value: terminalScoreMargin === null ? heuristicValue : terminalScoreMargin,
features,
};
}

View file

@ -0,0 +1,35 @@
import { createHash } from "crypto";
import { stableCandidateJson } from "../actions/canonical-key";
import {
CONVERSION_PLAN_SCHEMA,
CONVERSION_STATE_SCHEMA,
CanonicalConversionPlanKey,
CanonicalConversionStateKey,
ConversionTimingContext,
ProjectedConversionState,
} from "./types";
function digest(value: unknown): string {
return createHash("sha256").update(stableCandidateJson(value)).digest("hex");
}
/** Object identity and property insertion order are deliberately absent from state keys. */
export function canonicalConversionStateKey(state: ProjectedConversionState): CanonicalConversionStateKey {
return `conversion-state-v1:${digest({
schemaVersion: CONVERSION_STATE_SCHEMA,
...state,
conversionRights: [...state.conversionRights].sort(),
})}`;
}
/**
* A plan key names the semantic transition, not a particular commutative ordering. The ordered
* executable fragments remain on OrderedConversionPlan for replay.
*/
export function canonicalConversionPlanKey(material: {
sourceStateKey: CanonicalConversionStateKey;
destinationStateKey: CanonicalConversionStateKey;
timing: ConversionTimingContext;
}): CanonicalConversionPlanKey {
return `conversion-plan-v1:${digest({ schemaVersion: CONVERSION_PLAN_SCHEMA, ...material })}`;
}

View file

@ -0,0 +1,499 @@
import { expect } from "chai";
import { createHash } from "crypto";
import "mocha";
import Engine, { AuctionVariant } from "../../engine";
import { Building, Command, Phase, Player, PowerArea, Resource, Round, SubPhase } from "../../enums";
import { expandAtomicDecisions } from "../actions/expand";
import { AtomicDecisionCandidate } from "../actions/types";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "../challenge";
import { canonicalConversionPlanKey, canonicalConversionStateKey } from "./canonical-key";
import { planAfterActionConversions, planResourceConversions, ResourceConversionPlannerError } from "./planner";
function hydrate(engine: Engine): Engine {
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
}
function actorPrefix(engine: Engine): string {
return engine.player(engine.playerToMove).faction;
}
function lockedRoundOneEngine(): Engine {
const engine = new Engine(LOST_FLEET_CHALLENGE.scriptedPrefix, challengeEngineOptions());
let guard = 20;
while (engine.phase === Phase.SetupBuilding || engine.phase === Phase.SetupBooster) {
const candidate = expandAtomicDecisions(engine).candidates[0];
engine.move(`${actorPrefix(engine)} ${candidate.moveFragment}`);
expect(--guard, "locked setup must terminate").to.be.greaterThan(0);
}
expect(engine.phase).to.equal(Phase.RoundMove);
return engine;
}
function hadschHallasTurn(): Engine {
const engine = lockedRoundOneEngine();
const pass = expandAtomicDecisions(engine).candidates.find((candidate) => candidate.command === Command.Pass);
expect(pass).not.to.equal(undefined);
engine.move(`${actorPrefix(engine)} ${pass.moveFragment}`);
expect(engine.player(engine.playerToMove).faction).to.equal("hadsch-hallas");
return engine;
}
function smallWallet(
engine: Engine,
wallet: Partial<{
credits: number;
ores: number;
knowledge: number;
qics: number;
area1: number;
area2: number;
area3: number;
gaia: number;
}>
): Engine {
const player = engine.player(engine.playerToMove);
player.data.credits = wallet.credits ?? 0;
player.data.ores = wallet.ores ?? 0;
player.data.knowledge = wallet.knowledge ?? 0;
player.data.qics = wallet.qics ?? 0;
player.data.power.area1 = wallet.area1 ?? 0;
player.data.power.area2 = wallet.area2 ?? 0;
player.data.power.area3 = wallet.area3 ?? 0;
player.data.power.gaia = wallet.gaia ?? 0;
player.data.brainstone = null;
player.data.temporaryRange = 0;
player.data.temporaryStep = 0;
player.data.turns = 0;
engine.subPhase = SubPhase.BeforeMove;
engine.newTurn = true;
engine.pendingMove = "";
engine.turnMoves = [];
engine.clearAvailableCommands();
player.federationCache = null;
return engine;
}
function walletKey(state: {
credits: number;
ores: number;
knowledge: number;
qics: number;
power: { area1: number; area2: number; area3: number };
}): string {
return [
state.credits,
state.ores,
state.knowledge,
state.qics,
state.power.area1,
state.power.area2,
state.power.area3,
].join("/");
}
function planningResultKeyDigest(result: ReturnType<typeof planResourceConversions>): string {
const keyMaterial = {
sourceStateKey: result.sourceStateKey,
states: result.reachableStates.map(canonicalConversionStateKey).sort(),
plans: result.reachablePlans.map((plan) => plan.key).sort(),
frontier: result.stateFrontier.frontier.map(canonicalConversionStateKey).sort(),
candidates: result.candidates.map((entry) => ({
candidateKey: entry.candidate.key,
plans: entry.plans.map((plan) => plan.key).sort(),
paymentFrontier: entry.payments.frontier
.map((payment) => [payment.postPaymentStateKey, payment.conversionPlanKey])
.sort(),
paymentDominated: entry.payments.dominated.map((payment) => [payment.dominatedKey, payment.dominatingKey]).sort(),
})),
};
return createHash("sha256").update(JSON.stringify(keyMaterial)).digest("hex");
}
function bruteForceBaseConversions(initial: {
credits: number;
ores: number;
knowledge: number;
qics: number;
area1: number;
}): string[] {
type Wallet = typeof initial;
const key = (state: Wallet) => [state.credits, state.ores, state.knowledge, state.qics, state.area1, 0, 0].join("/");
const seen = new Map<string, Wallet>([[key(initial), initial]]);
const queue: Wallet[] = [initial];
while (queue.length > 0) {
const state = queue.shift() as Wallet;
const next: Wallet[] = [];
if (state.qics >= 1) {
next.push({ ...state, qics: state.qics - 1, ores: state.ores + 1 });
}
if (state.knowledge >= 1) {
next.push({ ...state, knowledge: state.knowledge - 1, credits: state.credits + 1 });
}
if (state.ores >= 1) {
next.push({ ...state, ores: state.ores - 1, credits: state.credits + 1 });
next.push({ ...state, ores: state.ores - 1, area1: state.area1 + 1 });
}
for (const candidate of next) {
const candidateKey = key(candidate);
if (!seen.has(candidateKey)) {
seen.set(candidateKey, candidate);
queue.push(candidate);
}
}
}
return Array.from(seen.keys()).sort();
}
function candidateByCommand(engine: Engine, command: Command): AtomicDecisionCandidate {
const candidate = expandAtomicDecisions(engine).candidates.find((entry) => entry.command === command);
expect(candidate, `candidate ${command}`).not.to.equal(undefined);
return candidate;
}
describe("Phase 1.3 offline resource-conversion planner", () => {
it("matches an independent tiny bounded brute-force conversion oracle", () => {
const source = smallWallet(hadschHallasTurn(), { ores: 2, knowledge: 1, qics: 1 });
const result = planResourceConversions(source);
const actual = result.reachableStates.map(walletKey).sort();
const expected = bruteForceBaseConversions({ credits: 0, ores: 2, knowledge: 1, qics: 1, area1: 0 });
expect(actual).to.deep.equal(expected);
expect(result.diagnostics.lossyCycles).to.have.length(0);
});
it("models Xenos ore-to-Area-III and replays its executable fragment", () => {
const source = smallWallet(lockedRoundOneEngine(), { ores: 1 });
const result = planResourceConversions(source);
const plan = result.reachablePlans.find(
(entry) => entry.moveFragments.length === 1 && entry.moveFragments[0] === "spend 1o for 1ta3"
);
expect(plan).not.to.equal(undefined);
const destination = result.reachableStates.find(
(state) => canonicalConversionStateKey(state) === plan.destinationStateKey
);
expect(destination.ores).to.equal(0);
expect(destination.power.area3).to.equal(1);
const replay = hydrate(source);
replay.move(`${actorPrefix(replay)} ${plan.moveFragments.join(". ")}`);
expect(replay.player(replay.playerToMove).data.ores).to.equal(destination.ores);
expect(replay.player(replay.playerToMove).data.power.area3).to.equal(destination.power.area3);
});
it("keeps Hadsch Halla credit conversions gated by its Planetary Institute", () => {
const before = smallWallet(hadschHallasTurn(), { credits: 4 });
const beforeResult = planResourceConversions(before);
expect(beforeResult.reachablePlans.some((plan) => plan.moveFragments.includes("spend 4c for 1q"))).to.equal(false);
const after = hydrate(before);
after.player(after.playerToMove).data.buildings[Building.PlanetaryInstitute] = 1;
after.players.forEach((player) => {
player.federationCache = null;
});
after.clearAvailableCommands();
const afterResult = planResourceConversions(after);
expect(afterResult.reachablePlans.some((plan) => plan.moveFragments.includes("spend 4c for 1q"))).to.equal(true);
expect(afterResult.reachableStates.some((state) => state.credits === 0 && state.qics === 1)).to.equal(true);
});
it("keeps burn and wait nondominated and uses burn to expose a typed main action", () => {
const source = smallWallet(lockedRoundOneEngine(), { area2: 8 });
const affordable = smallWallet(hydrate(source), { area3: 4 });
const target = candidateByCommand(affordable, Command.Action);
expect(expandAtomicDecisions(source).candidates.some((entry) => entry.key === target.key)).to.equal(false);
const result = planResourceConversions(source, { mainCandidates: [target] });
expect(result.largestConversionDepth).to.equal(8);
expect(result.stateFrontier.frontier.some((state) => state.power.area2 === 8 && state.power.area3 === 0)).to.equal(
true
);
expect(result.stateFrontier.frontier.some((state) => state.power.area2 === 0 && state.power.area3 === 4)).to.equal(
true
);
const candidate = result.candidates.find((entry) => entry.candidate.key === target.key);
expect(candidate).not.to.equal(undefined);
expect(candidate.plans.some((plan) => plan.steps.filter((step) => step.kind === "burn").length === 4)).to.equal(
true
);
expect(
candidate.payments.frontier.some(
(payment) => payment.postPaymentState.power.area1 === 4 && payment.postPaymentState.power.area3 === 0
)
).to.equal(true);
});
it("reaches depths above two without a depth cap and canonicalizes ranged aliases", () => {
const source = smallWallet(lockedRoundOneEngine(), { ores: 3 });
const result = planResourceConversions(source);
expect(result.largestConversionDepth).to.be.at.least(3);
expect(
result.reachablePlans.some(
(plan) => plan.steps.filter((step) => step.moveFragments[0] === "spend 1o for 1ta3").length === 3
)
).to.equal(true);
expect(
result.diagnostics.aliases.some(
(entry) => entry.moveFragment === "spend 2o for 2ta3" && entry.canonicalUnitFragment === "spend 1o for 1ta3"
)
).to.equal(true);
});
it("keeps brainstone payment branches distinct and replays brainstone burn exactly", () => {
const spendSource = smallWallet(lockedRoundOneEngine(), { area3: 4 });
spendSource.player(spendSource.playerToMove).data.brainstone = PowerArea.Area3;
const spend = planResourceConversions(spendSource);
const qicStates = spend.reachablePlans
.filter((plan) => plan.moveFragments[0] === "spend 4pw for 1q")
.map((plan) =>
spend.reachableStates.find((state) => canonicalConversionStateKey(state) === plan.destinationStateKey)
);
expect(qicStates.some((state) => state.power.brainstone === PowerArea.Area1)).to.equal(true);
expect(qicStates.some((state) => state.power.brainstone === PowerArea.Area3)).to.equal(true);
expect(spend.reachablePlans.some((plan) => plan.moveFragments.includes("brainstone area1"))).to.equal(true);
expect(spend.reachablePlans.some((plan) => plan.moveFragments.includes("brainstone area3"))).to.equal(true);
const burnSource = smallWallet(lockedRoundOneEngine(), { area2: 1 });
burnSource.player(burnSource.playerToMove).data.brainstone = PowerArea.Area2;
const burn = planResourceConversions(burnSource);
const burnPlan = burn.reachablePlans.find(
(plan) => plan.moveFragments.length === 1 && plan.moveFragments[0] === "burn 1"
);
const destination = burn.reachableStates.find(
(state) => canonicalConversionStateKey(state) === burnPlan.destinationStateKey
);
expect(destination.power.brainstone).to.equal(PowerArea.Area3);
expect(destination.power.area2).to.equal(0);
const replay = hydrate(burnSource);
replay.move(`${actorPrefix(replay)} burn 1`);
expect(replay.player(replay.playerToMove).data.brainstone).to.equal(PowerArea.Area3);
expect(replay.player(replay.playerToMove).data.power.area2).to.equal(0);
});
it("merges commutative orders into one semantic state and plan key", () => {
const source = smallWallet(hadschHallasTurn(), { knowledge: 1, qics: 1 });
const result = planResourceConversions(source);
const merge = result.diagnostics.merges.find(
(entry) =>
entry.reason === "commutative-order" &&
entry.keptMoveFragments.includes("spend 1k for 1c") &&
entry.mergedMoveFragments.includes("spend 1q for 1o")
);
expect(merge).not.to.equal(undefined);
const plan = result.reachablePlans.find((entry) => entry.key === merge.keptPlanKey);
expect(plan.destinationStateKey).to.equal(merge.destinationStateKey);
expect(
canonicalConversionPlanKey({
sourceStateKey: plan.sourceStateKey,
destinationStateKey: plan.destinationStateKey,
timing: plan.timing,
})
).to.equal(plan.key);
});
it("detects Hadsch Halla lossy cycles and preserves every nondominated outcome", () => {
const source = smallWallet(hadschHallasTurn(), { credits: 4 });
source.player(source.playerToMove).data.buildings[Building.PlanetaryInstitute] = 1;
source.clearAvailableCommands();
const result = planResourceConversions(source);
expect(result.diagnostics.lossyCycles.length).to.be.greaterThan(0);
expect(
result.diagnostics.lossyCycles.some(
(cycle) => cycle.resourceCycle.includes(Resource.Credit) && cycle.resourceCycle.includes(Resource.Ore)
)
).to.equal(true);
expect(result.stateFrontier.frontier.some((state) => state.credits === 4)).to.equal(true);
expect(
result.reachableStates.some(
(state) =>
state.credits === 1 &&
state.qics === 0 &&
state.ores === 0 &&
state.knowledge === 0 &&
state.power.area1 === 0 &&
state.power.area2 === 0 &&
state.power.area3 === 0
)
).to.equal(false);
});
it("models final-round conversions without assigning resource values", () => {
const source = smallWallet(hadschHallasTurn(), { qics: 1 });
source.round = Round.LastRound;
const result = planResourceConversions(source);
expect(result.reachableStates.every((state) => state.finalRound)).to.equal(true);
expect(
result.reachableStates.some((state) => state.qics === 0 && state.ores === 0 && state.credits === 1)
).to.equal(true);
});
it("retains post-action bowl opening before leech and defers ordinary conversions", () => {
const source = smallWallet(lockedRoundOneEngine(), { ores: 1, knowledge: 4 });
const main = candidateByCommand(source, Command.UpgradeResearch);
const result = planAfterActionConversions(source, main);
expect(result.status).to.equal("planned");
expect(
result.retained.some(
(entry) =>
entry.reason === "opens-power-bowl-capacity-before-leech" &&
entry.leechCapacityAfter > entry.leechCapacityBefore &&
entry.plan.moveFragments.includes("spend 1o for 1ta3") &&
entry.plan.moveFragments.includes("spend 1pw for 1c")
)
).to.equal(true);
expect(
result.deferred.some((entry) => entry.reason === "ordinary-resources-unobservable-before-next-before-move")
).to.equal(true);
});
it("keeps state and plan keys stable across replay, slow motion, hydration, and object ordering", () => {
const base = lockedRoundOneEngine();
const constructorReplay = new Engine(base.moveHistory, challengeEngineOptions(), base.version);
const slowMotion = Engine.slowMotion(base.moveHistory, challengeEngineOptions(), base.version);
const hydration = hydrate(base);
const sources = [base, constructorReplay, slowMotion, hydration].map((engine) => smallWallet(engine, { ores: 1 }));
const results = sources.map((engine) => planResourceConversions(engine));
const stateKeys = results.map((result) => result.reachableStates.map(canonicalConversionStateKey).sort());
const planKeys = results.map((result) => result.reachablePlans.map((plan) => plan.key).sort());
expect(stateKeys.slice(1).every((keys) => JSON.stringify(keys) === JSON.stringify(stateKeys[0]))).to.equal(true);
expect(planKeys.slice(1).every((keys) => JSON.stringify(keys) === JSON.stringify(planKeys[0]))).to.equal(true);
const reordered = JSON.parse(JSON.stringify(results[0].reachableStates[0]));
reordered.conversionRights.reverse();
expect(canonicalConversionStateKey(reordered)).to.equal(canonicalConversionStateKey(results[0].reachableStates[0]));
});
it("completes the untouched locked state with stable exhaustive keys and executable unit fragments", function () {
this.timeout(10 * 60 * 1000);
const base = lockedRoundOneEngine();
const sources = [
base,
new Engine(base.moveHistory, challengeEngineOptions(), base.version),
Engine.slowMotion(base.moveHistory, challengeEngineOptions(), base.version),
hydrate(base),
];
const expectedDigest = "b4e266ef95ca8cc34cfd1cde4380a782ff01f4802a077d49ac9686924e222850";
for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex += 1) {
const result = planResourceConversions(sources[sourceIndex]);
expect(result.reachableStates).to.have.length(36_159);
expect(result.reachablePlans).to.have.length(36_159);
expect(result.stateFrontier.frontier).to.have.length(9_985);
expect(result.candidates).to.have.length(45);
expect(result.largestConversionDepth).to.equal(30);
expect(result.diagnostics.merges).to.have.length(85_126);
expect(result.diagnostics.lossyCycles).to.have.length(0);
expect(result.diagnostics.paretoPruned).to.have.length(56_139);
expect(result.diagnostics.aliases).to.have.length(111);
expect(result.profile.counters.statesGenerated).to.equal(151_249);
expect(result.profile.counters.statesAccepted).to.equal(36_159);
expect(result.profile.counters.transitionsConsidered).to.equal(254_360);
expect(result.profile.counters.activeFrontierSize).to.equal(9_985);
expect(result.profile.counters.candidateStatesExpanded).to.equal(9_985);
expect(result.profile.counters.paymentResultsGenerated).to.equal(130_532);
expect(planningResultKeyDigest(result)).to.equal(expectedDigest);
if (sourceIndex === 0) {
const states = new Map(result.reachableStates.map((state) => [canonicalConversionStateKey(state), state]));
const representatives = new Map<string, (typeof result.reachablePlans)[number]>();
for (const plan of result.reachablePlans) {
const step = plan.steps[plan.steps.length - 1];
if (step) {
const signature = `${step.familyKey}\0${step.moveFragments.join(". ")}`;
representatives.set(signature, plan);
}
}
const representativeFragments = new Set(
Array.from(representatives.values()).map((plan) => plan.steps[plan.steps.length - 1].moveFragments[0])
);
for (const alias of result.diagnostics.aliases) {
expect(representativeFragments.has(alias.canonicalUnitFragment), alias.canonicalUnitFragment).to.equal(true);
}
for (const plan of representatives.values()) {
const replay = hydrate(base);
replay.move(`${actorPrefix(replay)} ${plan.moveFragments.join(". ")}`);
const destination = states.get(plan.destinationStateKey);
const data = replay.player(replay.playerToMove).data;
expect({
credits: data.credits,
ores: data.ores,
knowledge: data.knowledge,
qics: data.qics,
victoryPoints: data.victoryPoints,
area1: data.power.area1,
area2: data.power.area2,
area3: data.power.area3,
gaia: data.power.gaia,
brainstone: data.brainstone,
}).to.deep.equal({
credits: destination.credits,
ores: destination.ores,
knowledge: destination.knowledge,
qics: destination.qics,
victoryPoints: destination.victoryPoints,
area1: destination.power.area1,
area2: destination.power.area2,
area3: destination.power.area3,
gaia: destination.power.gaia,
brainstone: destination.power.brainstone,
});
}
}
}
});
it("rejects unsupported faction-picking variants and incomplete external states", () => {
const variants = [
(engine: Engine) => {
engine.options.randomFactions = true;
},
(engine: Engine) => {
engine.options.banPhase = true;
},
(engine: Engine) => {
engine.options.auction = AuctionVariant.ChooseBid;
},
(engine: Engine) => {
engine.silentAuctionBids = [{ player: Player.Player1, bids: [0, 0] }] as any;
},
];
for (const mutate of variants) {
const source = smallWallet(lockedRoundOneEngine(), {});
mutate(source);
expect(() => planResourceConversions(source)).to.throw();
}
const incomplete = smallWallet(lockedRoundOneEngine(), {});
incomplete.newTurn = false;
expect(() => planResourceConversions(incomplete)).to.throw();
});
it("rejects the committed Phase 0 setup state outside the RoundMove boundary", () => {
const challenge = new Engine(LOST_FLEET_CHALLENGE.scriptedPrefix, challengeEngineOptions());
expect(challenge.phase).to.equal(Phase.SetupBuilding);
expect(() => planResourceConversions(challenge)).to.throw(ResourceConversionPlannerError);
});
it("leaves the locked Phase 1.2 candidate count, keys, digest, and fragments unchanged", () => {
const source = lockedRoundOneEngine();
const before = expandAtomicDecisions(source).candidates;
expect(before).to.have.length(62);
const digest = createHash("sha256")
.update(
before
.map((candidate) => candidate.key)
.sort()
.join("\n")
)
.digest("hex");
expect(digest).to.equal("a28eb3d03e2b51e1bea28170b92f5e99991f41c76b1b1c8a2193a97a0ee704d9");
for (const candidate of before) {
expect(candidate.moveFragment).to.be.a("string").and.not.equal("");
}
expect(expandAtomicDecisions(source).candidates.map((candidate) => candidate.key)).to.deep.equal(
before.map((candidate) => candidate.key)
);
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,240 @@
import { Faction, Phase, Player, PowerArea, Resource, SubPhase } from "../../enums";
import { AtomicDecisionCandidate, ResourceAmount } from "../actions/types";
export const CONVERSION_STATE_SCHEMA = "gaia-ai-conversion-state/v1" as const;
export const CONVERSION_PLAN_SCHEMA = "gaia-ai-conversion-plan/v1" as const;
export type CanonicalConversionStateKey = string;
export type CanonicalConversionPlanKey = string;
export type ConversionTimingContext =
| {
kind: "pre-action";
phase: Phase.RoundMove;
subphase: SubPhase.BeforeMove;
}
| {
kind: "post-action-before-leech";
phase: Phase.RoundMove;
subphase: SubPhase.AfterMove;
mainCandidateKey: string;
/** True only for an internally replayed, ordinary non-pass main action. */
nextTurnDeferralProven: boolean;
};
export interface ProjectedPowerState {
area1: number;
area2: number;
area3: number;
gaia: number;
brainstone: PowerArea | null;
}
export interface ProjectedGaiaformerState {
total: number;
inGaia: number;
onBoard: number;
usedForAsteroid: number;
usedForOther: number;
available: number;
}
/**
* Resource-only projection used by the conversion graph. `contextKey` binds a projection to the
* unchanged board/action context, so equal-looking wallets from different positions never merge.
*/
export interface ProjectedConversionState {
schemaVersion: typeof CONVERSION_STATE_SCHEMA;
contextKey: string;
actor: Player;
faction: Faction;
phase: Phase.RoundMove;
round: number;
finalRound: boolean;
timing: ConversionTimingContext;
credits: number;
ores: number;
knowledge: number;
qics: number;
victoryPoints: number;
power: ProjectedPowerState;
gaiaformers: ProjectedGaiaformerState;
tokenModifier: number;
terraformCostDiscount: number;
temporaryRange: number;
temporaryStep: number;
satellites: number;
hasPlanetaryInstitute: boolean;
conversionRights: string[];
}
export interface ExecutableConversionStep {
kind: "spend" | "burn";
familyKey: string;
cost: ResourceAmount[];
reward: ResourceAmount[];
effects: string[];
/** One Spend/Burn fragment followed by a BrainStone choice fragment when production requires it. */
moveFragments: string[];
beforeStateKey: CanonicalConversionStateKey;
afterStateKey: CanonicalConversionStateKey;
changesPowerBowls: boolean;
}
export interface OrderedConversionPlan {
schemaVersion: typeof CONVERSION_PLAN_SCHEMA;
key: CanonicalConversionPlanKey;
timing: ConversionTimingContext;
sourceStateKey: CanonicalConversionStateKey;
destinationStateKey: CanonicalConversionStateKey;
steps: ExecutableConversionStep[];
moveFragments: string[];
}
export interface PaymentResult {
candidateKey: string;
conversionPlanKey: CanonicalConversionPlanKey;
affordable: boolean;
cost: ResourceAmount[];
postPaymentState: ProjectedConversionState;
postPaymentStateKey: CanonicalConversionStateKey;
brainstoneChoice: PowerArea | "discard" | null;
moveFragments: string[];
}
export interface ParetoFrontierResult<T> {
frontier: T[];
dominated: Array<{
dominatedKey: string;
dominatingKey: string;
}>;
}
export interface CandidateConversionPlans {
candidate: AtomicDecisionCandidate;
plans: OrderedConversionPlan[];
payments: ParetoFrontierResult<PaymentResult>;
}
export interface ConversionMergeDiagnostic {
destinationStateKey: CanonicalConversionStateKey;
keptPlanKey: CanonicalConversionPlanKey;
keptMoveFragments: string[];
mergedMoveFragments: string[];
reason: "commutative-order" | "equivalent-executable-sequence";
}
export interface LossyCycleDiagnostic {
ancestorStateKey: CanonicalConversionStateKey;
discardedStateKey: CanonicalConversionStateKey;
moveFragments: string[];
resourceCycle: Resource[];
reason: "componentwise-dominated-cycle";
}
export interface ConversionAliasDiagnostic {
moveFragment: string;
canonicalUnitFragment: string;
reason: "ranged-repeat-canonicalized";
}
export interface ParetoPruneDiagnostic {
discardedStateKey: CanonicalConversionStateKey;
dominatingStateKey: CanonicalConversionStateKey;
moveFragments: string[];
reason: "componentwise-dominated-transition";
}
export interface ConversionPlannerDiagnostics {
merges: ConversionMergeDiagnostic[];
lossyCycles: LossyCycleDiagnostic[];
aliases: ConversionAliasDiagnostic[];
paretoPruned: ParetoPruneDiagnostic[];
unavailableEffects: string[];
}
/** Deterministic work counters for profiling the exhaustive offline planner. */
export interface ResourceConversionPlannerCounters {
statesGenerated: number;
statesAccepted: number;
activeFrontierSize: number;
maximumActiveFrontierSize: number;
transitionsConsidered: number;
exactStateMerges: number;
paretoPrunes: number;
lossyCyclePrunes: number;
dominanceComparisons: number;
exactContextComputations: number;
stateKeyComputations: number;
planKeyComputations: number;
resourceCycleGraphReconstructions: number;
candidateStatesExpanded: number;
paymentResultsGenerated: number;
}
/** Descriptive timings only. They are never consulted to terminate or prune planning. */
export interface ResourceConversionPlannerTimings {
setupMs: number;
reachabilityMs: number;
resultAssemblyMs: number;
candidateConstructionMs: number;
paymentFrontiersMs: number;
totalMs: number;
}
export interface ResourceConversionPlannerProfile {
counters: ResourceConversionPlannerCounters;
timings: ResourceConversionPlannerTimings;
}
export interface ResourceConversionPlannerProgress {
counters: ResourceConversionPlannerCounters;
largestConversionDepth: number;
elapsedMs: number;
}
export interface ResourceConversionPlanningResult {
sourceStateKey: CanonicalConversionStateKey;
timing: ConversionTimingContext;
reachableStates: ProjectedConversionState[];
reachablePlans: OrderedConversionPlan[];
stateFrontier: ParetoFrontierResult<ProjectedConversionState>;
candidates: CandidateConversionPlans[];
diagnostics: ConversionPlannerDiagnostics;
largestConversionDepth: number;
profile: ResourceConversionPlannerProfile;
}
export interface DeferredAfterActionPlan {
planKey: CanonicalConversionPlanKey;
moveFragments: string[];
reason:
| "ordinary-resources-unobservable-before-next-before-move"
| "trailing-non-bowl-conversions-deferred-after-capacity-opening"
| "power-bowl-change-does-not-increase-leech-capacity";
}
export interface RetainedAfterActionPlan {
plan: OrderedConversionPlan;
leechCapacityBefore: number;
leechCapacityAfter: number;
reason: "opens-power-bowl-capacity-before-leech" | "deferral-proof-unavailable" | "wait";
}
export interface AfterActionConversionResult {
status: "planned" | "not-applicable";
reason: string | null;
mainCandidate: AtomicDecisionCandidate;
retained: RetainedAfterActionPlan[];
deferred: DeferredAfterActionPlan[];
planning: ResourceConversionPlanningResult | null;
}
export interface ResourceConversionPlannerOptions {
/** Optional Phase 1.2 candidate filter. Keys not legal in a reached state simply have no result. */
mainCandidates?: readonly AtomicDecisionCandidate[];
/** Optional offline profiler callback. It observes work and never changes planner semantics. */
onProgress?: (progress: ResourceConversionPlannerProgress) => void;
/** Deterministic transition interval for `onProgress`; defaults to 100,000. */
progressEveryTransitions?: number;
}

View file

@ -0,0 +1,268 @@
import { expect } from "chai";
import "mocha";
import { FixedFrameActor, FixedFrameSearch, SearchCandidate, SearchDomain, SearchRootActionDiagnostics } from "./core";
interface ReferenceAction {
key: string;
next: string;
prior: number;
}
interface ReferenceState {
key: string;
actor: FixedFrameActor | null;
value: number;
terminal: number | null;
actions: ReferenceAction[];
}
class ReferenceDomain implements SearchDomain<ReferenceState, ReferenceAction> {
parityCalls = 0;
constructor(private readonly states: Map<string, ReferenceState>) {}
stateKey(state: ReferenceState): string {
return state.key;
}
actor(state: ReferenceState): FixedFrameActor | null {
return state.actor;
}
terminalValue(state: ReferenceState): number | null {
return state.terminal;
}
evaluate(state: ReferenceState): number {
return state.value;
}
expand(state: ReferenceState): Array<SearchCandidate<ReferenceState, ReferenceAction>> {
return state.actions.map((action) => {
const destination = this.states.get(action.next);
if (!destination) {
throw new Error(`Missing reference state ${action.next}`);
}
return {
key: action.key,
action,
state: destination,
value: destination.terminal ?? destination.value,
prior: action.prior,
};
});
}
assertTranspositionParity(retained: ReferenceState, candidate: ReferenceState): void {
this.parityCalls += 1;
expect(candidate.key).to.equal(retained.key);
expect(candidate.actor).to.equal(retained.actor);
expect(candidate.terminal).to.equal(retained.terminal);
expect(candidate.value).to.equal(retained.value);
expect(candidate.actions.map((action) => action.key).sort()).to.deep.equal(
retained.actions.map((action) => action.key).sort()
);
}
}
function state(
key: string,
actor: FixedFrameActor | null,
value: number,
terminal: number | null,
actions: ReferenceAction[] = []
): ReferenceState {
return { key, actor, value, terminal, actions };
}
function action(key: string, next: string, prior: number): ReferenceAction {
return { key, next, prior };
}
function map(states: ReferenceState[]): Map<string, ReferenceState> {
return new Map(states.map((entry): [string, ReferenceState] => [entry.key, entry]));
}
function actionDiagnostics(actions: SearchRootActionDiagnostics[], key: string): SearchRootActionDiagnostics {
const diagnostics = actions.find((entry) => entry.key === key);
if (!diagnostics) {
throw new Error(`Missing diagnostics for ${key}`);
}
return diagnostics;
}
describe("Phase 2 fixed-frame reference search", () => {
it("maximizes and minimizes by the actual actor, including a repeated actor", () => {
const states = map([
state("root", 0, 0, null, [action("repeat", "seat0-again", 0.5), action("switch", "seat1", 0.5)]),
state("seat0-again", 0, 0, null, [action("good", "plus-nine", 0.5), action("bad", "minus-two", 0.5)]),
state("seat1", 1, 0, null, [action("allow-eight", "plus-eight", 0.5), action("force-one", "plus-one", 0.5)]),
state("plus-nine", null, 9, 9),
state("minus-two", null, -2, -2),
state("plus-eight", null, 8, 8),
state("plus-one", null, 1, 1),
]);
const search = new FixedFrameSearch(new ReferenceDomain(states), {
simulations: 256,
explorationConstant: 1,
});
const result = search.search(states.get("root"));
expect(result.actionKey).to.equal("repeat");
expect(result.diagnostics.deterministic.principalVariation.slice(0, 2)).to.deep.equal(["repeat", "good"]);
expect(actionDiagnostics(result.diagnostics.deterministic.rootActions, "repeat").meanValue).to.be.greaterThan(
actionDiagnostics(result.diagnostics.deterministic.rootActions, "switch").meanValue
);
});
it("uses exact terminal margins and never negates the fixed seat-0 value", () => {
const states = map([
state("leech-switch", 1, 100, null, [
action("seat0-plus-five", "plus-five", 0.5),
action("seat0-minus-four", "minus-four", 0.5),
]),
state("plus-five", null, 5, 5),
state("minus-four", null, -4, -4),
]);
const result = new FixedFrameSearch(new ReferenceDomain(states), { simulations: 32 }).search(
states.get("leech-switch")
);
expect(result.actionKey).to.equal("seat0-minus-four");
expect(result.diagnostics.deterministic.selectedMeanValue).to.equal(-4);
});
it("breaks exact ties by canonical action key and conserves every simulation", () => {
const states = map([
state("root", 0, 0, null, [action("z-key", "same-z", 0.5), action("a-key", "same-a", 0.5)]),
state("same-z", null, 3, 3),
state("same-a", null, 3, 3),
]);
const result = new FixedFrameSearch(new ReferenceDomain(states), { simulations: 20 }).search(states.get("root"));
expect(result.actionKey).to.equal("a-key");
expect(result.diagnostics.deterministic.completedSimulations).to.equal(20);
expect(result.diagnostics.deterministic.rootActions.reduce((sum, edge) => sum + edge.visitDelta, 0)).to.equal(20);
});
it("scales fixed-frame Q into PUCT exploration units without changing raw diagnostics", () => {
const states = map([
state("root", 0, 0, null, [action("high-value", "high", 0.01), action("high-prior", "prior", 0.99)]),
state("high", null, 10, 10),
state("prior", null, 8, 8),
]);
const raw = new FixedFrameSearch(new ReferenceDomain(states), { simulations: 1 }).search(states.get("root"));
const scaled = new FixedFrameSearch(new ReferenceDomain(states), {
simulations: 1,
puctValueScale: 10,
}).search(states.get("root"));
expect(raw.actionKey).to.equal("high-value");
expect(scaled.actionKey).to.equal("high-prior");
expect(scaled.diagnostics.deterministic.puctValueScale).to.equal(10);
expect(scaled.diagnostics.deterministic.selectedMeanValue).to.equal(8);
expect(() => new FixedFrameSearch(new ReferenceDomain(states), { simulations: 1, puctValueScale: 0 })).to.throw(
"puctValueScale must be positive"
);
});
it("allocates seeded Gumbel sequential halving deterministically at a fixed budget", () => {
const states = map([
state("root", 0, 0, null, [
action("a", "a-terminal", 0.4),
action("b", "b-terminal", 0.3),
action("c", "c-terminal", 0.2),
action("d", "d-terminal", 0.1),
]),
state("a-terminal", null, 2, 2),
state("b-terminal", null, 1, 1),
state("c-terminal", null, 0, 0),
state("d-terminal", null, -1, -1),
]);
const options = {
simulations: 17,
mode: "gumbel-sequential-halving" as const,
seed: "ai-7-gumbel-reference",
gumbelMaxActions: 4,
};
const first = new FixedFrameSearch(new ReferenceDomain(states), options).search(states.get("root"));
const second = new FixedFrameSearch(new ReferenceDomain(states), options).search(states.get("root"));
expect(second.diagnostics.deterministic).to.deep.equal(first.diagnostics.deterministic);
expect(first.diagnostics.deterministic.completedSimulations).to.equal(17);
expect(
first.diagnostics.deterministic.rootActions.reduce((sum, edge) => sum + edge.sequentialHalvingVisits, 0)
).to.equal(17);
expect(first.diagnostics.deterministic.rootActions.filter((edge) => edge.gumbel !== undefined)).to.have.length(4);
});
it("retains a selected subtree and agrees with a fresh tree on the next decision", () => {
const states = map([
state("root", 0, 0, null, [action("advance", "next", 1)]),
state("next", 1, 0, null, [action("low", "low-terminal", 0.5), action("high", "high-terminal", 0.5)]),
state("low-terminal", null, -3, -3),
state("high-terminal", null, 7, 7),
]);
const reused = new FixedFrameSearch(new ReferenceDomain(states), { simulations: 8 });
const first = reused.search(states.get("root"));
reused.advanceSelectedAction(first.actionKey);
const reusedResult = reused.search(states.get("next"));
const freshResult = new FixedFrameSearch(new ReferenceDomain(states), { simulations: 8 }).search(
states.get("next")
);
expect(reusedResult.diagnostics.deterministic.reuse.kind).to.equal("same-root");
expect(reusedResult.diagnostics.deterministic.reuse.availableVisits).to.be.greaterThan(0);
expect(reusedResult.diagnostics.deterministic.reuse.reusedVisits).to.be.greaterThan(0);
expect(reusedResult.actionKey).to.equal(freshResult.actionKey);
expect(reusedResult.actionKey).to.equal("low");
expect(reusedResult.diagnostics.deterministic.rootActions.map((edge) => edge.key)).to.deep.equal(
freshResult.diagnostics.deterministic.rootActions.map((edge) => edge.key)
);
});
it("can preserve an expanded subtree while resetting its retained search moments", () => {
const states = map([
state("root", 0, 0, null, [action("advance", "next", 1)]),
state("next", 1, 0, null, [action("low", "low-terminal", 0.5), action("high", "high-terminal", 0.5)]),
state("low-terminal", null, -3, -3),
state("high-terminal", null, 7, 7),
]);
const search = new FixedFrameSearch(new ReferenceDomain(states), {
simulations: 8,
rootReuseVisitPolicy: "reset-subtree",
});
const first = search.search(states.get("root"));
search.advanceSelectedAction(first.actionKey);
const result = search.search(states.get("next"));
expect(result.actionKey).to.equal("low");
expect(result.diagnostics.deterministic.rootReuseVisitPolicy).to.equal("reset-subtree");
expect(result.diagnostics.deterministic.reuse.kind).to.equal("same-root");
expect(result.diagnostics.deterministic.reuse.availableVisits).to.be.greaterThan(0);
expect(result.diagnostics.deterministic.reuse.reusedVisits).to.equal(0);
expect(result.diagnostics.deterministic.reuse.reusedNodes).to.be.greaterThan(1);
expect(result.diagnostics.deterministic.rootVisits).to.equal(8);
});
it("guards transpositions and preserves legal/value decisions when the DAG is ablated", () => {
const states = map([
state("root", 0, 0, null, [action("left", "shared", 0.5), action("right", "shared", 0.5)]),
state("shared", 1, 0, null, [
action("minimum", "minimum-terminal", 0.5),
action("maximum", "maximum-terminal", 0.5),
]),
state("minimum-terminal", null, -6, -6),
state("maximum-terminal", null, 4, 4),
]);
const guardedDomain = new ReferenceDomain(states);
const dag = new FixedFrameSearch(guardedDomain, { simulations: 64, transpositions: true }).search(
states.get("root")
);
const tree = new FixedFrameSearch(new ReferenceDomain(states), { simulations: 64, transpositions: false }).search(
states.get("root")
);
expect(dag.diagnostics.deterministic.transpositions.hits).to.be.greaterThan(0);
expect(dag.diagnostics.deterministic.transpositions.parityChecks).to.equal(guardedDomain.parityCalls);
expect(guardedDomain.parityCalls).to.be.greaterThan(0);
expect(dag.actionKey).to.equal(tree.actionKey);
expect(dag.diagnostics.deterministic.rootActions.map((edge) => edge.key)).to.deep.equal(
tree.diagnostics.deterministic.rootActions.map((edge) => edge.key)
);
expect(dag.diagnostics.deterministic.selectedMeanValue).to.be.lessThan(0);
expect(tree.diagnostics.deterministic.selectedMeanValue).to.be.lessThan(0);
});
});

View file

@ -0,0 +1,804 @@
export type FixedFrameActor = 0 | 1;
export type SearchMode = "puct" | "gumbel-sequential-halving";
export type RootReuseVisitPolicy = "retain" | "reset-subtree";
export interface SearchPriorDetails {
policy: string;
rawValue: number;
orientedValue: number;
centeredValue: number;
temperature: number;
}
export interface SearchCandidate<State, Action> {
key: string;
action: Action;
state: State;
/** Exact terminal value or the fixed-frame heuristic value of the child. */
value: number;
prior: number;
priorDetails?: SearchPriorDetails;
}
export interface SearchDomain<State, Action> {
stateKey(state: State): string;
actor(state: State): FixedFrameActor | null;
terminalValue(state: State): number | null;
evaluate(state: State): number;
expand(state: State): SearchCandidate<State, Action>[];
/** Required guard when transpositions are enabled. It must throw on any semantic mismatch. */
assertTranspositionParity?(retained: State, candidate: State): void;
}
export interface SearchOptions {
simulations: number;
mode?: SearchMode;
explorationConstant?: number;
/** Divide fixed-frame Q values by this scale before adding dimensionless PUCT exploration. */
puctValueScale?: number;
/** Whether a promoted child keeps old search moments or only its expanded structure. */
rootReuseVisitPolicy?: RootReuseVisitPolicy;
seed?: string;
gumbelMaxActions?: number;
gumbelValueScale?: number;
transpositions?: boolean;
}
export interface SearchRootActionDiagnostics {
key: string;
prior: number;
visits: number;
visitDelta: number;
meanValue: number;
standardDeviation: number;
minimumValue: number;
maximumValue: number;
priorDetails?: SearchPriorDetails;
gumbel?: number;
sequentialHalvingVisits: number;
}
export interface SearchDeterministicDiagnostics {
rootStateKey: string;
rootActor: FixedFrameActor;
mode: SearchMode;
simulationBudget: number;
completedSimulations: number;
explorationConstant: number;
puctValueScale: number;
rootReuseVisitPolicy: RootReuseVisitPolicy;
seed: string;
selectedActionKey: string;
selectedMeanValue: number;
rootValue: number;
rootVisits: number;
expansions: number;
expandedEdges: number;
terminalLeaves: number;
cycleStops: number;
principalVariation: string[];
rootActions: SearchRootActionDiagnostics[];
reuse: {
kind: "fresh" | "same-root" | "descendant" | "transposition-table";
availableVisits: number;
reusedVisits: number;
reusedNodes: number;
};
transpositions: {
enabled: boolean;
hits: number;
parityChecks: number;
};
}
export interface SearchPerformanceDiagnostics {
elapsedMs: number;
expansionsPerSecond: number;
}
export interface SearchDiagnostics {
deterministic: SearchDeterministicDiagnostics;
performance: SearchPerformanceDiagnostics;
}
export interface SearchResult<Action> {
action: Action;
actionKey: string;
diagnostics: SearchDiagnostics;
}
interface SearchNode<State, Action> {
key: string;
state: State;
actor: FixedFrameActor | null;
terminalValue: number | null;
leafValue: number;
visits: number;
valueSum: number;
valueSquareSum: number;
minimumValue: number;
maximumValue: number;
edges: Array<SearchEdge<State, Action>> | null;
}
interface SearchEdge<State, Action> {
key: string;
action: Action;
prior: number;
priorDetails?: SearchPriorDetails;
child: SearchNode<State, Action>;
visits: number;
valueSum: number;
valueSquareSum: number;
minimumValue: number;
maximumValue: number;
}
interface SearchCallCounters {
expansions: number;
expandedEdges: number;
terminalLeaves: number;
cycleStops: number;
transpositionHits: number;
parityChecks: number;
}
interface RootPreparation {
kind: SearchDeterministicDiagnostics["reuse"]["kind"];
availableVisits: number;
reusedVisits: number;
reusedNodes: number;
}
interface PendingAdvance {
key: string;
availableVisits: number;
reusedNodes: number;
}
interface GumbelAllocation<State, Action> {
selected: SearchEdge<State, Action>;
samples: Map<string, number>;
allocatedVisits: Map<string, number>;
}
const DEFAULT_EXPLORATION_CONSTANT = 1.25;
const DEFAULT_PUCT_VALUE_SCALE = 1;
const DEFAULT_GUMBEL_VALUE_SCALE = 0.12;
const MIN_RANDOM = 1e-12;
const VALUE_EPSILON = 1e-9;
function assertPositiveInteger(value: number, label: string): void {
if (!Number.isInteger(value) || value <= 0) {
throw new Error(`${label} must be a positive integer`);
}
}
function mean(visits: number, sum: number, fallback: number): number {
return visits === 0 ? fallback : sum / visits;
}
function standardDeviation(visits: number, sum: number, squareSum: number): number {
if (visits <= 1) {
return 0;
}
const average = sum / visits;
return Math.sqrt(Math.max(0, squareSum / visits - average * average));
}
function updateMoments(
target: {
visits: number;
valueSum: number;
valueSquareSum: number;
minimumValue: number;
maximumValue: number;
},
value: number
): void {
target.visits += 1;
target.valueSum += value;
target.valueSquareSum += value * value;
target.minimumValue = Math.min(target.minimumValue, value);
target.maximumValue = Math.max(target.maximumValue, value);
}
function hashSeed(seed: string): number {
let hash = 2166136261;
for (let index = 0; index < seed.length; index += 1) {
hash ^= seed.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
/** Small evaluation-only PRNG. Search never consumes the engine RNG. */
function deterministicRandom(seed: string): () => number {
let state = hashSeed(seed) || 0x9e3779b9;
return () => {
state += 0x6d2b79f5;
let value = state;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
function sampleGumbel(random: () => number): number {
const uniform = Math.min(1 - MIN_RANDOM, Math.max(MIN_RANDOM, random()));
return -Math.log(-Math.log(uniform));
}
function oriented(actor: FixedFrameActor, value: number): number {
return actor === 0 ? value : -value;
}
export class FixedFrameSearch<State, Action> {
private root: SearchNode<State, Action> | null = null;
private readonly transpositionTable = new Map<string, SearchNode<State, Action>>();
private readonly parityValidatedKeys = new Set<string>();
private searchCount = 0;
private pendingAdvance: PendingAdvance | null = null;
constructor(
private readonly domain: SearchDomain<State, Action>,
private readonly options: SearchOptions
) {
assertPositiveInteger(options.simulations, "simulations");
if ((options.explorationConstant ?? DEFAULT_EXPLORATION_CONSTANT) < 0) {
throw new Error("explorationConstant must be non-negative");
}
if (
!Number.isFinite(options.puctValueScale ?? DEFAULT_PUCT_VALUE_SCALE) ||
(options.puctValueScale ?? DEFAULT_PUCT_VALUE_SCALE) <= 0
) {
throw new Error("puctValueScale must be positive");
}
if (options.transpositions && !domain.assertTranspositionParity) {
throw new Error("Transpositions require an assertTranspositionParity guard");
}
}
search(state: State): SearchResult<Action> {
const started = Date.now();
const counters: SearchCallCounters = {
expansions: 0,
expandedEdges: 0,
terminalLeaves: 0,
cycleStops: 0,
transpositionHits: 0,
parityChecks: 0,
};
const preparation = this.prepareRoot(state);
const root = this.root;
if (!root || root.terminalValue !== null || root.actor === null) {
throw new Error("Cannot search a terminal state or a state without an actor");
}
this.expandNode(root, counters);
const rootEdges = root.edges;
if (!rootEdges || rootEdges.length === 0) {
throw new Error(`Search root ${root.key} has no legal actions`);
}
const beforeVisits = new Map<string, number>();
for (const edge of rootEdges) {
beforeVisits.set(edge.key, edge.visits);
}
const mode = this.options.mode ?? "puct";
const seed = `${this.options.seed ?? "gaia-ai-7"}:${root.key}:${this.searchCount}`;
let selected: SearchEdge<State, Action>;
let gumbelSamples = new Map<string, number>();
let sequentialHalvingVisits = new Map<string, number>();
if (mode === "gumbel-sequential-halving") {
const allocation = this.runSequentialHalving(root, seed, counters);
selected = allocation.selected;
gumbelSamples = allocation.samples;
sequentialHalvingVisits = allocation.allocatedVisits;
} else {
for (let simulation = 0; simulation < this.options.simulations; simulation += 1) {
this.simulate(root, null, counters);
}
selected = this.finalEdge(root);
}
this.searchCount += 1;
const rootActions = rootEdges.map((edge): SearchRootActionDiagnostics => {
const priorVisits = beforeVisits.get(edge.key) ?? 0;
const details: SearchRootActionDiagnostics = {
key: edge.key,
prior: edge.prior,
visits: edge.visits,
visitDelta: edge.visits - priorVisits,
meanValue: mean(edge.visits, edge.valueSum, edge.child.leafValue),
standardDeviation: standardDeviation(edge.visits, edge.valueSum, edge.valueSquareSum),
minimumValue: edge.visits === 0 ? edge.child.leafValue : edge.minimumValue,
maximumValue: edge.visits === 0 ? edge.child.leafValue : edge.maximumValue,
priorDetails: edge.priorDetails,
sequentialHalvingVisits: sequentialHalvingVisits.get(edge.key) ?? 0,
};
const gumbel = gumbelSamples.get(edge.key);
if (gumbel !== undefined) {
details.gumbel = gumbel;
}
return details;
});
const completedSimulations = rootActions.reduce((sum, edge) => sum + edge.visitDelta, 0);
if (completedSimulations !== this.options.simulations) {
throw new Error(
`Search budget accounting mismatch: completed ${completedSimulations}, expected ${this.options.simulations}`
);
}
const elapsedMs = Math.max(0, Date.now() - started);
return {
action: selected.action,
actionKey: selected.key,
diagnostics: {
deterministic: {
rootStateKey: root.key,
rootActor: root.actor,
mode,
simulationBudget: this.options.simulations,
completedSimulations,
explorationConstant: this.options.explorationConstant ?? DEFAULT_EXPLORATION_CONSTANT,
puctValueScale: this.options.puctValueScale ?? DEFAULT_PUCT_VALUE_SCALE,
rootReuseVisitPolicy: this.options.rootReuseVisitPolicy ?? "retain",
seed,
selectedActionKey: selected.key,
selectedMeanValue: mean(selected.visits, selected.valueSum, selected.child.leafValue),
rootValue: mean(root.visits, root.valueSum, root.leafValue),
rootVisits: root.visits,
expansions: counters.expansions,
expandedEdges: counters.expandedEdges,
terminalLeaves: counters.terminalLeaves,
cycleStops: counters.cycleStops,
principalVariation: this.principalVariation(root),
rootActions,
reuse: {
kind: preparation.kind,
availableVisits: preparation.availableVisits,
reusedVisits: preparation.reusedVisits,
reusedNodes: preparation.reusedNodes,
},
transpositions: {
enabled: this.options.transpositions ?? false,
hits: counters.transpositionHits,
parityChecks: counters.parityChecks,
},
},
performance: {
elapsedMs,
expansionsPerSecond: elapsedMs === 0 ? counters.expansions * 1000 : (counters.expansions * 1000) / elapsedMs,
},
},
};
}
/** Retain the chosen child as the next expected committed root. */
advanceSelectedAction(actionKey: string): void {
if (!this.root || !this.root.edges) {
throw new Error("Cannot advance an unexpanded search tree");
}
const selected = this.root.edges.find((edge) => edge.key === actionKey);
if (!selected) {
throw new Error(`Cannot advance unknown root action ${actionKey}`);
}
this.root = selected.child;
this.pendingAdvance = {
key: this.root.key,
availableVisits: this.root.visits,
reusedNodes: this.countReachable(this.root),
};
if (this.options.rootReuseVisitPolicy === "reset-subtree") {
this.resetReachableMoments(this.root);
}
if (this.options.transpositions) {
this.rebuildTranspositionTable();
}
}
reset(): void {
this.root = null;
this.transpositionTable.clear();
this.parityValidatedKeys.clear();
this.searchCount = 0;
this.pendingAdvance = null;
}
private prepareRoot(state: State): RootPreparation {
const key = this.domain.stateKey(state);
if (this.root && this.root.key === key) {
if (this.pendingAdvance?.key === key) {
const preparation = {
kind: "same-root" as const,
availableVisits: this.pendingAdvance.availableVisits,
reusedVisits: this.root.visits,
reusedNodes: this.pendingAdvance.reusedNodes,
};
this.pendingAdvance = null;
return preparation;
}
return {
kind: "same-root",
availableVisits: this.root.visits,
reusedVisits: this.root.visits,
reusedNodes: this.countReachable(this.root),
};
}
this.pendingAdvance = null;
if (this.root) {
const descendant = this.findReachable(this.root, key);
if (descendant) {
this.root = descendant;
if (this.options.transpositions) {
this.rebuildTranspositionTable();
}
return {
kind: "descendant",
availableVisits: descendant.visits,
reusedVisits: descendant.visits,
reusedNodes: this.countReachable(descendant),
};
}
}
if (this.options.transpositions) {
const retained = this.transpositionTable.get(key);
if (retained) {
this.root = retained;
this.rebuildTranspositionTable();
return {
kind: "transposition-table",
availableVisits: retained.visits,
reusedVisits: retained.visits,
reusedNodes: this.countReachable(retained),
};
}
}
this.root = this.createNode(state);
this.transpositionTable.clear();
this.parityValidatedKeys.clear();
if (this.options.transpositions) {
this.transpositionTable.set(key, this.root);
}
return { kind: "fresh", availableVisits: 0, reusedVisits: 0, reusedNodes: 0 };
}
private createNode(state: State, suppliedValue?: number): SearchNode<State, Action> {
const terminalValue = this.domain.terminalValue(state);
const leafValue = terminalValue === null ? (suppliedValue ?? this.domain.evaluate(state)) : terminalValue;
return {
key: this.domain.stateKey(state),
state,
actor: terminalValue === null ? this.domain.actor(state) : null,
terminalValue,
leafValue,
visits: 0,
valueSum: 0,
valueSquareSum: 0,
minimumValue: Number.POSITIVE_INFINITY,
maximumValue: Number.NEGATIVE_INFINITY,
edges: null,
};
}
private expandNode(node: SearchNode<State, Action>, counters: SearchCallCounters): void {
if (node.edges !== null || node.terminalValue !== null) {
return;
}
if (node.actor === null) {
throw new Error(`Non-terminal search node ${node.key} has no actor`);
}
const candidates = [...this.domain.expand(node.state)].sort((left, right) => left.key.localeCompare(right.key));
if (candidates.length === 0) {
throw new Error(`Non-terminal search node ${node.key} has no legal actions`);
}
const keySet = new Set(candidates.map((candidate) => candidate.key));
if (keySet.size !== candidates.length) {
throw new Error(`Search node ${node.key} has duplicate action keys`);
}
const priorSum = candidates.reduce((sum, candidate) => sum + candidate.prior, 0);
if (!Number.isFinite(priorSum) || Math.abs(priorSum - 1) > VALUE_EPSILON) {
throw new Error(`Search priors at ${node.key} sum to ${priorSum}, expected 1`);
}
for (const candidate of candidates) {
if (!Number.isFinite(candidate.value) || !Number.isFinite(candidate.prior) || candidate.prior < 0) {
throw new Error(`Search candidate ${candidate.key} has a non-finite value or invalid prior`);
}
}
node.edges = candidates.map((candidate): SearchEdge<State, Action> => ({
key: candidate.key,
action: candidate.action,
prior: candidate.prior,
priorDetails: candidate.priorDetails,
child: this.transposedChild(candidate, counters),
visits: 0,
valueSum: 0,
valueSquareSum: 0,
minimumValue: Number.POSITIVE_INFINITY,
maximumValue: Number.NEGATIVE_INFINITY,
}));
counters.expansions += 1;
counters.expandedEdges += node.edges.length;
}
private transposedChild(
candidate: SearchCandidate<State, Action>,
counters: SearchCallCounters
): SearchNode<State, Action> {
const key = this.domain.stateKey(candidate.state);
if (!this.options.transpositions) {
return this.createNode(candidate.state, candidate.value);
}
const retained = this.transpositionTable.get(key);
if (!retained) {
const child = this.createNode(candidate.state, candidate.value);
this.transpositionTable.set(key, child);
return child;
}
if (
retained.actor !== (retained.terminalValue === null ? this.domain.actor(candidate.state) : null) ||
retained.terminalValue !== this.domain.terminalValue(candidate.state) ||
Math.abs(retained.leafValue - candidate.value) > VALUE_EPSILON
) {
throw new Error(`Transposition value/actor parity failed for ${key}`);
}
if (!this.parityValidatedKeys.has(key)) {
if (!this.domain.assertTranspositionParity) {
throw new Error("Missing transposition parity guard");
}
this.domain.assertTranspositionParity(retained.state, candidate.state);
this.parityValidatedKeys.add(key);
counters.parityChecks += 1;
}
counters.transpositionHits += 1;
return retained;
}
private selectPuctEdge(node: SearchNode<State, Action>): SearchEdge<State, Action> {
const edges = node.edges;
if (!edges || node.actor === null) {
throw new Error(`Cannot select from unexpanded node ${node.key}`);
}
const explorationConstant = this.options.explorationConstant ?? DEFAULT_EXPLORATION_CONSTANT;
const puctValueScale = this.options.puctValueScale ?? DEFAULT_PUCT_VALUE_SCALE;
let best = edges[0];
let bestScore = Number.NEGATIVE_INFINITY;
for (const edge of edges) {
const value = mean(edge.visits, edge.valueSum, edge.child.leafValue);
const exploration = (explorationConstant * edge.prior * Math.sqrt(Math.max(1, node.visits))) / (1 + edge.visits);
const score = oriented(node.actor, value) / puctValueScale + exploration;
if (score > bestScore || (score === bestScore && edge.key.localeCompare(best.key) < 0)) {
best = edge;
bestScore = score;
}
}
return best;
}
private simulate(
root: SearchNode<State, Action>,
forcedRootEdge: SearchEdge<State, Action> | null,
counters: SearchCallCounters
): number {
const nodes: Array<SearchNode<State, Action>> = [root];
const edges: Array<SearchEdge<State, Action>> = [];
const pathKeys = new Set<string>([root.key]);
let node = root;
let first = true;
while (node.terminalValue === null) {
this.expandNode(node, counters);
const edge = first && forcedRootEdge ? forcedRootEdge : this.selectPuctEdge(node);
first = false;
edges.push(edge);
node = edge.child;
if (pathKeys.has(node.key)) {
counters.cycleStops += 1;
break;
}
nodes.push(node);
pathKeys.add(node.key);
if (node.terminalValue !== null) {
counters.terminalLeaves += 1;
break;
}
if (node.edges === null) {
this.expandNode(node, counters);
break;
}
}
const value = node.terminalValue ?? node.leafValue;
for (const visited of nodes) {
updateMoments(visited, value);
}
for (const edge of edges) {
updateMoments(edge, value);
}
return value;
}
private runSequentialHalving(
root: SearchNode<State, Action>,
seed: string,
counters: SearchCallCounters
): GumbelAllocation<State, Action> {
const edges = root.edges;
if (!edges || root.actor === null) {
throw new Error("Cannot run root allocation on an unexpanded root");
}
const random = deterministicRandom(seed);
const samples = new Map<string, number>();
for (const edge of edges) {
samples.set(edge.key, sampleGumbel(random));
}
const maxActions = Math.min(edges.length, this.options.simulations, this.options.gumbelMaxActions ?? edges.length);
let feasibleActions = maxActions;
while (
feasibleActions > 1 &&
feasibleActions * Math.max(1, Math.ceil(Math.log2(feasibleActions))) > this.options.simulations
) {
feasibleActions -= 1;
}
assertPositiveInteger(feasibleActions, "gumbelMaxActions after budget restriction");
let active = [...edges]
.sort((left, right) => {
const leftScore = Math.log(Math.max(MIN_RANDOM, left.prior)) + (samples.get(left.key) ?? 0);
const rightScore = Math.log(Math.max(MIN_RANDOM, right.prior)) + (samples.get(right.key) ?? 0);
return rightScore - leftScore || left.key.localeCompare(right.key);
})
.slice(0, feasibleActions);
const allocatedVisits = new Map<string, number>();
let remaining = this.options.simulations;
while (active.length > 1 && remaining > 0) {
const remainingRounds = Math.max(1, Math.ceil(Math.log2(active.length)));
const roundBudget = Math.min(remaining, Math.max(active.length, Math.floor(remaining / remainingRounds)));
const base = Math.floor(roundBudget / active.length);
let extra = roundBudget % active.length;
for (const edge of active) {
const allocation = base + (extra > 0 ? 1 : 0);
extra = Math.max(0, extra - 1);
for (let simulation = 0; simulation < allocation; simulation += 1) {
this.simulate(root, edge, counters);
}
allocatedVisits.set(edge.key, (allocatedVisits.get(edge.key) ?? 0) + allocation);
}
remaining -= roundBudget;
const valueScale = this.options.gumbelValueScale ?? DEFAULT_GUMBEL_VALUE_SCALE;
active.sort((left, right) => {
const leftValue = mean(left.visits, left.valueSum, left.child.leafValue);
const rightValue = mean(right.visits, right.valueSum, right.child.leafValue);
const leftScore = (samples.get(left.key) ?? 0) + valueScale * oriented(root.actor, leftValue);
const rightScore = (samples.get(right.key) ?? 0) + valueScale * oriented(root.actor, rightValue);
return rightScore - leftScore || left.key.localeCompare(right.key);
});
active = active.slice(0, Math.ceil(active.length / 2));
}
const selected = active[0];
while (remaining > 0) {
this.simulate(root, selected, counters);
allocatedVisits.set(selected.key, (allocatedVisits.get(selected.key) ?? 0) + 1);
remaining -= 1;
}
return { selected, samples, allocatedVisits };
}
private finalEdge(node: SearchNode<State, Action>): SearchEdge<State, Action> {
const edges = node.edges;
if (!edges || node.actor === null) {
throw new Error(`Cannot choose a final edge from ${node.key}`);
}
let best = edges[0];
for (const edge of edges.slice(1)) {
const edgeMean = mean(edge.visits, edge.valueSum, edge.child.leafValue);
const bestMean = mean(best.visits, best.valueSum, best.child.leafValue);
if (
edge.visits > best.visits ||
(edge.visits === best.visits && oriented(node.actor, edgeMean) > oriented(node.actor, bestMean)) ||
(edge.visits === best.visits && edgeMean === bestMean && edge.key.localeCompare(best.key) < 0)
) {
best = edge;
}
}
return best;
}
private principalVariation(root: SearchNode<State, Action>): string[] {
const variation: string[] = [];
const seen = new Set<string>();
let node: SearchNode<State, Action> | null = root;
while (node && node.edges && node.edges.length > 0 && node.actor !== null && !seen.has(node.key)) {
seen.add(node.key);
const edge = this.finalEdge(node);
if (edge.visits === 0) {
break;
}
variation.push(edge.key);
node = edge.child;
}
return variation;
}
private findReachable(root: SearchNode<State, Action>, key: string): SearchNode<State, Action> | null {
const queue: Array<SearchNode<State, Action>> = [root];
const visited = new Set<SearchNode<State, Action>>();
while (queue.length > 0) {
const node = queue.shift();
if (!node || visited.has(node)) {
continue;
}
if (node.key === key) {
return node;
}
visited.add(node);
if (node.edges) {
queue.push(...node.edges.map((edge) => edge.child));
}
}
return null;
}
private countReachable(root: SearchNode<State, Action>): number {
const queue: Array<SearchNode<State, Action>> = [root];
const visited = new Set<SearchNode<State, Action>>();
while (queue.length > 0) {
const node = queue.shift();
if (!node || visited.has(node)) {
continue;
}
visited.add(node);
if (node.edges) {
queue.push(...node.edges.map((edge) => edge.child));
}
}
return visited.size;
}
private resetReachableMoments(root: SearchNode<State, Action>): void {
const queue: Array<SearchNode<State, Action>> = [root];
const visited = new Set<SearchNode<State, Action>>();
while (queue.length > 0) {
const node = queue.shift();
if (!node || visited.has(node)) {
continue;
}
visited.add(node);
node.visits = 0;
node.valueSum = 0;
node.valueSquareSum = 0;
node.minimumValue = Number.POSITIVE_INFINITY;
node.maximumValue = Number.NEGATIVE_INFINITY;
if (node.edges) {
for (const edge of node.edges) {
edge.visits = 0;
edge.valueSum = 0;
edge.valueSquareSum = 0;
edge.minimumValue = Number.POSITIVE_INFINITY;
edge.maximumValue = Number.NEGATIVE_INFINITY;
queue.push(edge.child);
}
}
}
}
private rebuildTranspositionTable(): void {
this.transpositionTable.clear();
if (!this.root) {
return;
}
const queue: Array<SearchNode<State, Action>> = [this.root];
const visited = new Set<SearchNode<State, Action>>();
while (queue.length > 0) {
const node = queue.shift();
if (!node || visited.has(node)) {
continue;
}
visited.add(node);
this.transpositionTable.set(node.key, node);
if (node.edges) {
queue.push(...node.edges.map((edge) => edge.child));
}
}
}
}

View file

@ -0,0 +1,292 @@
import Engine from "../../engine";
import { Command, Player } from "../../enums";
import { CommittedTurnMacro, CommittedTurnMacroBuildOptions, CommittedTurnMacroSet } from "../actions/turn-builder";
import { applyMacroHostStyle, buildBotMacroSet } from "../bots/common";
import { greedyStateValue, GreedyValueMode } from "../bots/greedy";
import { canonicalStateHash } from "../canonical-state";
import { evaluateHeuristic, HeuristicEvaluationOptions, terminalUtility } from "../evaluation";
import { FixedFrameActor, SearchCandidate, SearchDomain } from "./core";
export const NON_NEURAL_PRIOR_SCHEMA = "gaia-ai-non-neural-prior/v1" as const;
export interface NonNeuralPriorOptions {
/** Shared softmax temperature in fixed-frame heuristic/greedy value units. */
temperature?: number;
/** Probability blended uniformly across legal macros so every edge remains explorable. */
uniformMix?: number;
/** Probability-level mixture of the immediate greedy softmax into the heuristic softmax. */
greedyMix?: number;
}
export interface NonNeuralPriorEntry {
macroKey: string;
/** Search leaf value after the optional value-level greedy blend. */
fixedFrameValue: number;
orientedValue: number;
centeredValue: number;
heuristicFixedFrameValue: number;
heuristicOrientedValue: number;
greedyFixedFrameValue: number;
greedyOrientedValue: number;
greedyCenteredValue: number;
heuristicProbability: number;
greedyProbability: number;
prior: number;
}
export interface NonNeuralPriorReport {
schemaVersion: typeof NON_NEURAL_PRIOR_SCHEMA;
policy: "heuristic-softmax-uniform-mix" | "heuristic-greedy-softmax-uniform-mix";
actor: Player;
temperature: number;
uniformMix: number;
greedyMix: number;
leafGreedyMix: number;
nonTerminalPassValuePenalty: number;
entries: NonNeuralPriorEntry[];
}
export interface EngineSearchDomainOptions {
macroBuildOptions?: CommittedTurnMacroBuildOptions;
/** State-only leaf evaluation keeps canonical transposition values path-independent. */
evaluation?: Omit<HeuristicEvaluationOptions, "transition">;
/** Value-level blend of immediate greedy into the state-only heuristic leaf evaluation. */
leafGreedyMix?: number;
/** The default preserves every frozen search arm's immediate-greedy semantics. */
greedyValueMode?: GreedyValueMode;
/** Actor-relative opportunity cost applied only to non-terminal Pass leaf/prior values. */
nonTerminalPassValuePenalty?: number;
prior?: NonNeuralPriorOptions;
}
const VALUE_EPSILON = 1e-9;
const DEFAULT_PRIOR_TEMPERATURE = 8;
const DEFAULT_PRIOR_UNIFORM_MIX = 0.05;
const DEFAULT_PRIOR_GREEDY_MIX = 0;
export function pinnedSearchMacroBuildOptions(
options: CommittedTurnMacroBuildOptions = {}
): CommittedTurnMacroBuildOptions {
const conversionIntegration = options.conversionIntegration ?? false;
return {
conversionIntegration,
afterConversionIntegration: options.afterConversionIntegration ?? conversionIntegration,
mainCandidateKeys: options.mainCandidateKeys ? [...options.mainCandidateKeys] : undefined,
};
}
function fixedFrameActor(player: Player): FixedFrameActor {
return player === Player.Player1 ? 0 : 1;
}
function stableMacroParity(left: CommittedTurnMacro, right: CommittedTurnMacro): boolean {
return (
left.key === right.key &&
left.sourceStateHash === right.sourceStateHash &&
left.destination.stateHash === right.destination.stateHash &&
left.destination.nextActor === right.destination.nextActor &&
left.destination.gameEnded === right.destination.gameEnded
);
}
/** Engine-only adapter. Every child is one verified Phase 1.4 host-style committed macro. */
export class EngineSearchDomain implements SearchDomain<Engine, CommittedTurnMacro> {
readonly macroBuildOptions: CommittedTurnMacroBuildOptions;
readonly priorOptions: Required<NonNeuralPriorOptions>;
readonly leafGreedyMix: number;
readonly greedyValueMode: GreedyValueMode;
readonly nonTerminalPassValuePenalty: number;
private readonly macroSets = new Map<string, CommittedTurnMacroSet>();
private readonly priorReports = new Map<string, NonNeuralPriorReport>();
constructor(private readonly options: EngineSearchDomainOptions = {}) {
this.macroBuildOptions = pinnedSearchMacroBuildOptions(options.macroBuildOptions);
this.priorOptions = {
temperature: options.prior?.temperature ?? DEFAULT_PRIOR_TEMPERATURE,
uniformMix: options.prior?.uniformMix ?? DEFAULT_PRIOR_UNIFORM_MIX,
greedyMix: options.prior?.greedyMix ?? DEFAULT_PRIOR_GREEDY_MIX,
};
this.leafGreedyMix = options.leafGreedyMix ?? 0;
this.greedyValueMode = options.greedyValueMode ?? "immediate";
this.nonTerminalPassValuePenalty = options.nonTerminalPassValuePenalty ?? 0;
if (!Number.isFinite(this.priorOptions.temperature) || this.priorOptions.temperature <= 0) {
throw new Error("Non-neural prior temperature must be positive");
}
if (
!Number.isFinite(this.priorOptions.uniformMix) ||
this.priorOptions.uniformMix < 0 ||
this.priorOptions.uniformMix > 1
) {
throw new Error("Non-neural prior uniformMix must be between 0 and 1");
}
if (
!Number.isFinite(this.priorOptions.greedyMix) ||
this.priorOptions.greedyMix < 0 ||
this.priorOptions.greedyMix > 1
) {
throw new Error("Non-neural prior greedyMix must be between 0 and 1");
}
if (!Number.isFinite(this.leafGreedyMix) || this.leafGreedyMix < 0 || this.leafGreedyMix > 1) {
throw new Error("Search leafGreedyMix must be between 0 and 1");
}
if (!Number.isFinite(this.nonTerminalPassValuePenalty) || this.nonTerminalPassValuePenalty < 0) {
throw new Error("Search nonTerminalPassValuePenalty must be finite and non-negative");
}
}
stateKey(state: Engine): string {
return canonicalStateHash(state);
}
actor(state: Engine): FixedFrameActor | null {
if (state.ended || state.playerToMove === undefined || state.playerToMove === null) {
return null;
}
return fixedFrameActor(state.playerToMove);
}
terminalValue(state: Engine): number | null {
return state.ended ? terminalUtility(state) : null;
}
evaluate(state: Engine): number {
const heuristicValue = evaluateHeuristic(state, this.options.evaluation).value;
return (
(1 - this.leafGreedyMix) * heuristicValue + this.leafGreedyMix * greedyStateValue(state, this.greedyValueMode)
);
}
expand(state: Engine): Array<SearchCandidate<Engine, CommittedTurnMacro>> {
const stateKey = this.stateKey(state);
const macroSet = buildBotMacroSet(state, this.macroBuildOptions);
if (macroSet.sourceStateHash !== stateKey) {
throw new Error(`Macro set source ${macroSet.sourceStateHash} does not match search state ${stateKey}`);
}
this.macroSets.set(stateKey, macroSet);
const children = macroSet.macros.map((macro) => {
const destination = applyMacroHostStyle(state, macro);
const passAdjustment =
macro.mainCommand === Command.Pass && !destination.ended
? (macroSet.actor === Player.Player1 ? -1 : 1) * this.nonTerminalPassValuePenalty
: 0;
const heuristicValue = evaluateHeuristic(destination, this.options.evaluation).value + passAdjustment;
const greedyValue = greedyStateValue(destination, this.greedyValueMode) + passAdjustment;
return {
macro,
destination,
heuristicValue,
greedyValue,
value: destination.ended
? terminalUtility(destination)
: (1 - this.leafGreedyMix) * heuristicValue + this.leafGreedyMix * greedyValue,
};
});
const orientation = macroSet.actor === Player.Player1 ? 1 : -1;
const orientedValues = children.map((child) => orientation * child.value);
const average = orientedValues.reduce((sum, value) => sum + value, 0) / orientedValues.length;
const heuristicOrientedValues = children.map((child) => orientation * child.heuristicValue);
const heuristicAverage =
heuristicOrientedValues.reduce((sum, value) => sum + value, 0) / heuristicOrientedValues.length;
const heuristicExponentials = heuristicOrientedValues.map((value) =>
Math.exp(Math.max(-40, Math.min(40, (value - heuristicAverage) / this.priorOptions.temperature)))
);
const heuristicExponentialSum = heuristicExponentials.reduce((sum, value) => sum + value, 0);
const greedyOrientedValues = children.map((child) => orientation * child.greedyValue);
const greedyAverage = greedyOrientedValues.reduce((sum, value) => sum + value, 0) / greedyOrientedValues.length;
const greedyExponentials = greedyOrientedValues.map((value) =>
Math.exp(Math.max(-40, Math.min(40, (value - greedyAverage) / this.priorOptions.temperature)))
);
const greedyExponentialSum = greedyExponentials.reduce((sum, value) => sum + value, 0);
const entries = children.map((child, index): NonNeuralPriorEntry => {
const heuristicProbability = heuristicExponentials[index] / heuristicExponentialSum;
const greedyProbability = greedyExponentials[index] / greedyExponentialSum;
const blendedProbability =
(1 - this.priorOptions.greedyMix) * heuristicProbability + this.priorOptions.greedyMix * greedyProbability;
return {
macroKey: child.macro.key,
fixedFrameValue: child.value,
orientedValue: orientedValues[index],
centeredValue: orientedValues[index] - average,
heuristicFixedFrameValue: child.heuristicValue,
heuristicOrientedValue: heuristicOrientedValues[index],
greedyFixedFrameValue: child.greedyValue,
greedyOrientedValue: greedyOrientedValues[index],
greedyCenteredValue: greedyOrientedValues[index] - greedyAverage,
heuristicProbability,
greedyProbability,
prior: (1 - this.priorOptions.uniformMix) * blendedProbability + this.priorOptions.uniformMix / children.length,
};
});
const report: NonNeuralPriorReport = {
schemaVersion: NON_NEURAL_PRIOR_SCHEMA,
policy:
this.priorOptions.greedyMix === 0 ? "heuristic-softmax-uniform-mix" : "heuristic-greedy-softmax-uniform-mix",
actor: macroSet.actor,
temperature: this.priorOptions.temperature,
uniformMix: this.priorOptions.uniformMix,
greedyMix: this.priorOptions.greedyMix,
leafGreedyMix: this.leafGreedyMix,
nonTerminalPassValuePenalty: this.nonTerminalPassValuePenalty,
entries,
};
this.priorReports.set(stateKey, report);
return children.map((child, index): SearchCandidate<Engine, CommittedTurnMacro> => ({
key: child.macro.key,
action: child.macro,
state: child.destination,
value: child.value,
prior: entries[index].prior,
priorDetails: {
policy: report.policy,
rawValue: child.value,
orientedValue: entries[index].orientedValue,
centeredValue: entries[index].centeredValue,
temperature: report.temperature,
},
}));
}
macroSet(stateKey: string): CommittedTurnMacroSet {
const macroSet = this.macroSets.get(stateKey);
if (!macroSet) {
throw new Error(`No expanded macro set recorded for search state ${stateKey}`);
}
return macroSet;
}
priorReport(stateKey: string): NonNeuralPriorReport {
const report = this.priorReports.get(stateKey);
if (!report) {
throw new Error(`No prior report recorded for search state ${stateKey}`);
}
return report;
}
assertTranspositionParity(retained: Engine, candidate: Engine): void {
const retainedKey = this.stateKey(retained);
const candidateKey = this.stateKey(candidate);
if (retainedKey !== candidateKey) {
throw new Error(`Transposition canonical key mismatch: ${retainedKey} versus ${candidateKey}`);
}
const retainedValue = retained.ended ? terminalUtility(retained) : this.evaluate(retained);
const candidateValue = candidate.ended ? terminalUtility(candidate) : this.evaluate(candidate);
if (Math.abs(retainedValue - candidateValue) > VALUE_EPSILON) {
throw new Error(`Transposition heuristic value mismatch at ${retainedKey}`);
}
if (retained.ended || candidate.ended) {
if (retained.ended !== candidate.ended) {
throw new Error(`Transposition terminal parity mismatch at ${retainedKey}`);
}
return;
}
const retainedSet = buildBotMacroSet(retained, this.macroBuildOptions);
const candidateSet = buildBotMacroSet(candidate, this.macroBuildOptions);
if (
retainedSet.actor !== candidateSet.actor ||
retainedSet.macros.length !== candidateSet.macros.length ||
retainedSet.macros.some((macro, index) => !stableMacroParity(macro, candidateSet.macros[index]))
) {
throw new Error(`Transposition legal macro parity mismatch at ${retainedKey}`);
}
}
}

View file

@ -0,0 +1,251 @@
import { expect } from "chai";
import "mocha";
import Engine from "../../engine";
import { Phase } from "../../enums";
import { applyMacroHostStyle } from "../bots/common";
import { GreedyMacroBot, greedyStateValue } from "../bots/greedy";
import { SearchMacroBot } from "../bots/search";
import { canonicalStateHash } from "../canonical-state";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "../challenge";
import { buildCuratedSearchPositions, playPairedSearchStrengthMatchup, StrengthOpponent } from "../testing/strength";
import { EngineSearchDomain } from "./engine-domain";
function challengeSetup(): Engine {
return new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
}
const greedyOpponent: StrengthOpponent = {
name: "greedy-macro",
factory: () => new GreedyMacroBot(),
};
describe("Phase 2 committed-macro search integration", function () {
this.timeout(30 * 60 * 1000);
it("runs deterministic fixed-budget PUCT over host-style committed macros", () => {
const engine = challengeSetup();
const options = {
simulations: 3,
mode: "puct" as const,
seed: "ai-7-puct-integration",
macroBuildOptions: { conversionIntegration: false, afterConversionIntegration: false },
};
const first = new SearchMacroBot(options).select(engine);
const second = new SearchMacroBot(options).select(engine);
expect(second.macro.key).to.equal(first.macro.key);
expect(second.evaluation.diagnostics.deterministic).to.deep.equal(first.evaluation.diagnostics.deterministic);
expect(first.evaluation.macroBuildOptions).to.deep.equal({
conversionIntegration: false,
afterConversionIntegration: false,
mainCandidateKeys: undefined,
});
const diagnostics = first.evaluation.diagnostics.deterministic;
expect(diagnostics.rootActions.map((edge) => edge.key)).to.deep.equal(
first.macroSet.macros.map((macro) => macro.key)
);
expect(diagnostics.rootActions.reduce((sum, edge) => sum + edge.prior, 0)).to.be.closeTo(1, 1e-9);
expect(diagnostics.rootActions.reduce((sum, edge) => sum + edge.visitDelta, 0)).to.equal(3);
expect(first.macroSet.macros.some((macro) => macro.key === first.macro.key)).to.equal(true);
expect(applyMacroHostStyle(engine, first.macro).newTurn).to.equal(true);
});
it("keeps the frozen heuristic prior at greedyMix zero and exposes an inspectable blended prior", () => {
const engine = challengeSetup();
const baselineDomain = new EngineSearchDomain();
const explicitBaselineDomain = new EngineSearchDomain({ prior: { greedyMix: 0 } });
const blendedDomain = new EngineSearchDomain({ prior: { greedyMix: 0.5 } });
const leafBlendedDomain = new EngineSearchDomain({ leafGreedyMix: 0.5 });
const stateKey = canonicalStateHash(engine);
const baseline = baselineDomain.expand(engine);
const explicitBaseline = explicitBaselineDomain.expand(engine);
const blended = blendedDomain.expand(engine);
const leafBlended = leafBlendedDomain.expand(engine);
const report = blendedDomain.priorReport(stateKey);
expect(explicitBaseline.map((candidate) => candidate.prior)).to.deep.equal(
baseline.map((candidate) => candidate.prior)
);
expect(baselineDomain.priorReport(stateKey).policy).to.equal("heuristic-softmax-uniform-mix");
expect(baselineDomain.priorReport(stateKey).greedyMix).to.equal(0);
expect(report.policy).to.equal("heuristic-greedy-softmax-uniform-mix");
expect(report.greedyMix).to.equal(0.5);
expect(leafBlendedDomain.priorReport(stateKey).leafGreedyMix).to.equal(0.5);
expect(leafBlended.map((candidate) => candidate.prior)).to.deep.equal(baseline.map((candidate) => candidate.prior));
for (const [index, entry] of leafBlendedDomain.priorReport(stateKey).entries.entries()) {
expect(entry.fixedFrameValue).to.be.closeTo(
(entry.heuristicFixedFrameValue + entry.greedyFixedFrameValue) / 2,
1e-12
);
expect(leafBlended[index].value).to.equal(entry.fixedFrameValue);
}
expect(report.entries.reduce((sum, entry) => sum + entry.heuristicProbability, 0)).to.be.closeTo(1, 1e-9);
expect(report.entries.reduce((sum, entry) => sum + entry.greedyProbability, 0)).to.be.closeTo(1, 1e-9);
expect(blended.reduce((sum, candidate) => sum + candidate.prior, 0)).to.be.closeTo(1, 1e-9);
for (const entry of report.entries) {
const expected =
(1 - report.uniformMix) *
((1 - report.greedyMix) * entry.heuristicProbability + report.greedyMix * entry.greedyProbability) +
report.uniformMix / report.entries.length;
expect(entry.prior).to.be.closeTo(expected, 1e-12);
}
expect(() => new EngineSearchDomain({ prior: { greedyMix: -0.01 } })).to.throw(
"Non-neural prior greedyMix must be between 0 and 1"
);
expect(() => new EngineSearchDomain({ leafGreedyMix: 1.01 })).to.throw(
"Search leafGreedyMix must be between 0 and 1"
);
});
it("keeps immediate greedy frozen and exposes income-normalized search values independently", () => {
const position = buildCuratedSearchPositions().find((entry) => entry.label === "round-1");
const immediate = new EngineSearchDomain({ leafGreedyMix: 1, prior: { greedyMix: 1 } });
const normalized = new EngineSearchDomain({
leafGreedyMix: 1,
greedyValueMode: "income-normalized",
prior: { greedyMix: 1 },
});
const immediateCandidates = immediate.expand(position.engine);
const normalizedCandidates = normalized.expand(position.engine);
expect(immediate.greedyValueMode).to.equal("immediate");
expect(normalized.greedyValueMode).to.equal("income-normalized");
expect(immediateCandidates.map((candidate) => candidate.value)).to.not.deep.equal(
normalizedCandidates.map((candidate) => candidate.value)
);
expect(greedyStateValue(position.engine)).to.not.equal(greedyStateValue(position.engine, "income-normalized"));
});
it("applies an actor-relative opportunity cost only to non-terminal Pass values", () => {
const position = buildCuratedSearchPositions().find((entry) => entry.label === "round-1");
const baseline = new EngineSearchDomain({ leafGreedyMix: 1, prior: { greedyMix: 1 } });
const productive = new EngineSearchDomain({
leafGreedyMix: 1,
prior: { greedyMix: 1 },
nonTerminalPassValuePenalty: 4,
});
baseline.expand(position.engine);
productive.expand(position.engine);
const baselineReport = baseline.priorReport(position.stateHash);
const productiveReport = productive.priorReport(position.stateHash);
const macros = baseline.macroSet(position.stateHash);
const passKey = macros.macros.find((macro) => macro.mainCommand === "pass").key;
const ordinaryKey = macros.macros.find((macro) => macro.mainCommand !== "pass").key;
const baselinePass = baselineReport.entries.find((entry) => entry.macroKey === passKey);
const productivePass = productiveReport.entries.find((entry) => entry.macroKey === passKey);
const baselineOrdinary = baselineReport.entries.find((entry) => entry.macroKey === ordinaryKey);
const productiveOrdinary = productiveReport.entries.find((entry) => entry.macroKey === ordinaryKey);
expect(baselineReport.nonTerminalPassValuePenalty).to.equal(0);
expect(productiveReport.nonTerminalPassValuePenalty).to.equal(4);
expect(productivePass.greedyFixedFrameValue).to.equal(baselinePass.greedyFixedFrameValue - 4);
expect(productiveOrdinary.greedyFixedFrameValue).to.equal(baselineOrdinary.greedyFixedFrameValue);
expect(() => new EngineSearchDomain({ nonTerminalPassValuePenalty: -1 })).to.throw(
"Search nonTerminalPassValuePenalty must be finite and non-negative"
);
});
it("keeps the seeded Gumbel root variant reproducible and independently reported", () => {
const engine = challengeSetup();
const options = {
simulations: 5,
mode: "gumbel-sequential-halving" as const,
seed: "ai-7-gumbel-integration",
gumbelMaxActions: 5,
};
const first = new SearchMacroBot(options).select(engine);
const second = new SearchMacroBot(options).select(engine);
expect(second.macro.key).to.equal(first.macro.key);
expect(second.evaluation.diagnostics.deterministic).to.deep.equal(first.evaluation.diagnostics.deterministic);
const diagnostics = first.evaluation.diagnostics.deterministic;
expect(diagnostics.mode).to.equal("gumbel-sequential-halving");
expect(diagnostics.completedSimulations).to.equal(5);
expect(diagnostics.rootActions.reduce((sum, edge) => sum + edge.sequentialHalvingVisits, 0)).to.equal(5);
});
it("reuses the actual selected subtree and matches a fresh next-state decision", () => {
const source = challengeSetup();
const retained = new SearchMacroBot({ simulations: 1, seed: "ai-7-reuse" });
const first = retained.select(source);
const destination = applyMacroHostStyle(source, first.macro);
const reused = retained.select(destination);
const fresh = new SearchMacroBot({ simulations: 1, seed: "ai-7-reuse" }).select(destination);
expect(reused.evaluation.diagnostics.deterministic.reuse.kind).to.equal("same-root");
expect(reused.evaluation.diagnostics.deterministic.reuse.reusedVisits).to.be.greaterThan(0);
expect(reused.macro.key).to.equal(fresh.macro.key);
expect(reused.macroSet.macros.map((macro) => macro.key)).to.deep.equal(
fresh.macroSet.macros.map((macro) => macro.key)
);
});
it("reports scale-aware PUCT and clears promoted-root moments when configured", () => {
const source = challengeSetup();
const retained = new SearchMacroBot({
simulations: 1,
seed: "ai-7-scaled-reset-reuse",
puctValueScale: 32,
rootReuseVisitPolicy: "reset-subtree",
});
const first = retained.select(source);
const destination = applyMacroHostStyle(source, first.macro);
const reused = retained.select(destination);
const diagnostics = reused.evaluation.diagnostics.deterministic;
expect(diagnostics.puctValueScale).to.equal(32);
expect(diagnostics.rootReuseVisitPolicy).to.equal("reset-subtree");
expect(diagnostics.reuse.kind).to.equal("same-root");
expect(diagnostics.reuse.availableVisits).to.be.greaterThan(0);
expect(diagnostics.reuse.reusedVisits).to.equal(0);
expect(diagnostics.completedSimulations).to.equal(1);
});
it("guards canonical state, legal macro, and heuristic value parity before DAG reuse", () => {
const engine = challengeSetup();
const clone = Engine.fromData(JSON.parse(JSON.stringify(engine)));
const domain = new EngineSearchDomain();
expect(canonicalStateHash(clone)).to.equal(canonicalStateHash(engine));
expect(() => domain.assertTranspositionParity(engine, clone)).not.to.throw();
});
it("curates committed setup and round 1-6 positions without command gaps", () => {
const positions = buildCuratedSearchPositions();
expect(positions.map((position) => position.label)).to.deep.equal([
"setup",
"round-1",
"round-2",
"round-3",
"round-4",
"round-5",
"round-6",
]);
expect(new Set(positions.map((position) => position.stateHash)).size).to.equal(7);
for (const position of positions) {
expect(position.engine.newTurn).to.equal(true);
expect(position.actor).to.equal(position.engine.playerToMove);
}
});
it("takes both factions to EndGame at a tiny paired smoke budget", () => {
const paired = playPairedSearchStrengthMatchup(
(_seat, seed) => new SearchMacroBot({ simulations: 1, seed }),
greedyOpponent,
"ai-7-smoke"
);
expect(paired.candidateAsXenos.finalEngine.phase).to.equal(Phase.EndGame);
expect(paired.candidateAsHadschHallas.finalEngine.phase).to.equal(Phase.EndGame);
expect(paired.candidateAsXenos.telemetry.selections).to.be.greaterThan(0);
expect(paired.candidateAsHadschHallas.telemetry.selections).to.be.greaterThan(0);
expect(paired.telemetry.simulations).to.equal(paired.telemetry.selections);
expect(paired.candidateAsXenos.finalFixedFrameMargin).to.equal(
paired.candidateAsXenos.finalSeat0Score - paired.candidateAsXenos.finalSeat1Score
);
expect(paired.candidateAsHadschHallas.finalFixedFrameMargin).to.equal(
paired.candidateAsHadschHallas.finalSeat0Score - paired.candidateAsHadschHallas.finalSeat1Score
);
for (const game of [paired.candidateAsXenos, paired.candidateAsHadschHallas]) {
expect(game.fullGameReport.players.map((player) => player.score.finalScore)).to.deep.equal([
game.finalSeat0Score,
game.finalSeat1Score,
]);
expect(game.fullGameReport.players.every((player) => player.totalPasses === 6)).to.equal(true);
}
});
});

View file

@ -0,0 +1,135 @@
import Engine from "../engine";
import { Building, Planet, Spaceship, SpaceshipFederation, SpaceshipTechTile } from "../enums";
import { terraformingStepsRequired } from "../planets";
import Player from "../player";
/** Inspectable components of the expert opening-placement prior. */
export interface SetupMinePlacementScore {
shipAccess: number;
opponentColorAccess: number;
gaiaAccess: number;
asteroidAccess: number;
oneStepColorAccess: number;
nearbyPlanetDensity: number;
total: number;
}
const EMPTY_SETUP_SCORE: SetupMinePlacementScore = {
shipAccess: 0,
opponentColorAccess: 0,
gaiaAccess: 0,
asteroidAccess: 0,
oneStepColorAccess: 0,
nearbyPlanetDensity: 0,
total: 0,
};
/**
* The owner-labelled placement horizon: adjacent is best, then distances two and three. Anything
* farther away is deliberately ignored by this local opening prior.
*/
function proximity(distance: number): number {
return distance >= 1 && distance <= 3 ? 4 - distance : 0;
}
/**
* Base values describe the fixed action boards. Seeded tech/federation rewards are then added so
* the ranking responds to the actual setup rather than treating every spaceship as interchangeable.
*/
function spaceshipOpportunityMultiplier(engine: Engine, ship: Spaceship): number {
const boardValue: Record<Spaceship, number> = {
[Spaceship.Twilight]: 1.2,
[Spaceship.Rebellion]: 1.3,
[Spaceship.TFMars]: 1.3,
[Spaceship.Eclipse]: 1.7,
};
const techValue: Record<SpaceshipTechTile, number> = {
[SpaceshipTechTile.Range]: 0.6,
[SpaceshipTechTile.Terraform]: 0.3,
[SpaceshipTechTile.Resource]: 0.2,
};
const federationValue: Record<SpaceshipFederation, number> = {
[SpaceshipFederation.Credit]: 0.2,
[SpaceshipFederation.Knowledge]: 0.2,
[SpaceshipFederation.OreQic]: 0.2,
[SpaceshipFederation.PowerTokens]: 0.2,
[SpaceshipFederation.Range]: 0.2,
[SpaceshipFederation.Tech]: 0.3,
[SpaceshipFederation.Terraform]: 0.2,
[SpaceshipFederation.Vp]: 0.1,
};
const tech = engine.tiles.spaceshipTechs[ship]?.tile;
const federation = engine.tiles.spaceshipFederations[ship];
return boardValue[ship] + (tech ? techValue[tech] : 0) + (federation ? federationValue[federation] : 0);
}
export function scoreSetupMinePlacement(engine: Engine, player: Player, coordinates: string): SetupMinePlacementScore {
const origin = engine.map.getS(coordinates);
if (!origin) {
return { ...EMPTY_SETUP_SCORE };
}
const opponentPlanets = engine.players
.filter((candidate) => candidate.player !== player.player)
.map((candidate) => candidate.planet);
const score = { ...EMPTY_SETUP_SCORE };
for (const hex of engine.map.grid.values()) {
const distance = engine.map.distance(origin, hex);
const closeness = proximity(distance);
if (closeness === 0) {
continue;
}
const ship = hex.data.spaceship as Spaceship | undefined;
if (ship) {
score.shipAccess += closeness * spaceshipOpportunityMultiplier(engine, ship);
}
if (!hex.hasPlanet()) {
continue;
}
const planet = hex.data.planet as Planet;
score.nearbyPlanetDensity += closeness * 0.15;
if (opponentPlanets.includes(planet)) {
score.opponentColorAccess += closeness * 1.5 + (distance <= 2 ? 1 : 0);
}
if (planet === Planet.Gaia) {
score.gaiaAccess += closeness * 1.3;
}
if (planet === Planet.Asteroid) {
score.asteroidAccess += closeness * 0.9;
}
if (terraformingStepsRequired(player.faction, planet, player.data.lostFleetCost3Planets) === 1) {
score.oneStepColorAccess += closeness * 0.7;
}
}
score.total =
score.shipAccess +
score.opponentColorAccess +
score.gaiaAccess +
score.asteroidAccess +
score.oneStepColorAccess +
score.nearbyPlanetDensity;
return score;
}
/** Sum the still-relevant opening value of every setup Mine placed by this player. */
export function scoreSetupPlacements(engine: Engine, player: Player): SetupMinePlacementScore {
const score = { ...EMPTY_SETUP_SCORE };
for (const hex of player.data.occupied) {
if (hex.buildingOf(player.player) !== Building.Mine) {
continue;
}
const placement = scoreSetupMinePlacement(engine, player, hex.toString());
score.shipAccess += placement.shipAccess;
score.opponentColorAccess += placement.opponentColorAccess;
score.gaiaAccess += placement.gaiaAccess;
score.asteroidAccess += placement.asteroidAccess;
score.oneStepColorAccess += placement.oneStepColorAccess;
score.nearbyPlanetDensity += placement.nearbyPlanetDensity;
score.total += placement.total;
}
return score;
}

View file

@ -0,0 +1,177 @@
import { expect } from "chai";
import "mocha";
import Engine from "../../engine";
import { Command, Phase, Resource } from "../../enums";
import { expandAtomicDecisions } from "../actions/expand";
import { roundActionBudget, StrategyPlanMacroBot } from "../bots/strategy-plan";
import { challengeEngineOptions, LOST_FLEET_CHALLENGE } from "../challenge";
import {
assessEconomyPlan,
ECONOMY_PLAN_TRANSITION_WEIGHTS,
EconomyReserveBundle,
evaluateEconomyPlanTransition,
} from "./economy-plan";
function actorPrefix(engine: Engine): string {
return engine.player(engine.playerToMove).faction;
}
function roundMoveEngine(): Engine {
const engine = new Engine([...LOST_FLEET_CHALLENGE.scriptedPrefix], challengeEngineOptions());
let guard = 30;
while (engine.phase === Phase.SetupBuilding || engine.phase === Phase.SetupBooster) {
const candidate = expandAtomicDecisions(engine).candidates[0];
engine.move(`${actorPrefix(engine)} ${candidate.moveFragment}`);
expect(--guard).to.be.greaterThan(0);
}
return engine;
}
function clone(engine: Engine): Engine {
return Engine.fromData(JSON.parse(JSON.stringify(engine)));
}
const EMPTY: EconomyReserveBundle = { credits: 0, ores: 0, knowledge: 0, qics: 0 };
const KNOWLEDGE_BUNDLE: EconomyReserveBundle = { credits: 0, ores: 0, knowledge: 4, qics: 0 };
describe("AI-7 economy plan", () => {
it("scores wallet coverage of the needed combination, not raw stock", () => {
const source = roundMoveEngine();
const actor = source.playerToMove;
source.player(actor).data.knowledge = 0;
const covered = clone(source);
covered.player(actor).data.knowledge = 4; // buys exactly what the plan is short of
const unrelated = clone(source);
unrelated.player(actor).data.ores += 3; // piles on a resource the bundle does not need
const coveredReport = evaluateEconomyPlanTransition(
source,
covered,
actor,
Command.UpgradeResearch,
KNOWLEDGE_BUNDLE,
false
);
const unrelatedReport = evaluateEconomyPlanTransition(
source,
unrelated,
actor,
Command.Build,
KNOWLEDGE_BUNDLE,
false
);
expect(coveredReport.bundleCoverageDelta).to.be.closeTo(1, 1e-9);
expect(unrelatedReport.bundleCoverageDelta).to.equal(0);
expect(coveredReport.score).to.be.greaterThan(unrelatedReport.score);
});
it("does not credit coverage for stacking an already-covered resource", () => {
const source = roundMoveEngine();
const actor = source.playerToMove;
source.player(actor).data.knowledge = 4; // bundle already fully covered
const destination = clone(source);
destination.player(actor).data.knowledge = 10;
const report = evaluateEconomyPlanTransition(
source,
destination,
actor,
Command.UpgradeResearch,
KNOWLEDGE_BUNDLE,
false
);
expect(report.bundleCoverageBefore).to.equal(1);
expect(report.bundleCoverageDelta).to.equal(0);
});
it("detects value wasted past the resource caps under live income", () => {
const source = roundMoveEngine();
const actor = source.playerToMove;
// Round-1 challenge position has ore income 3, so a full ore wallet overflows the 15 cap.
expect(source.player(actor).resourceIncome(Resource.Ore)).to.be.greaterThan(0);
const atCap = clone(source);
atCap.player(actor).data.ores = 15;
const belowCap = clone(source);
belowCap.player(actor).data.ores = 7;
expect(assessEconomyPlan(atCap, actor, EMPTY).capWaste).to.be.greaterThan(0);
expect(assessEconomyPlan(belowCap, actor, EMPTY).capWaste).to.equal(0);
const spendDown = evaluateEconomyPlanTransition(atCap, belowCap, actor, Command.Build, EMPTY, false);
expect(spendDown.capWasteReduction).to.be.greaterThan(0);
});
it("penalizes spending resources with no durable progress", () => {
const source = roundMoveEngine();
const actor = source.playerToMove;
source.player(actor).data.credits = 15;
const destination = clone(source);
destination.player(actor).data.credits = 5; // spent, but no building/research/score change
const report = evaluateEconomyPlanTransition(source, destination, actor, Command.Special, EMPTY, false);
expect(report.durableProgress).to.equal(false);
expect(report.wastefulSpend).to.equal(true);
expect(report.score).to.be.lessThan(0);
});
it("does not penalize spending that advances the board", () => {
const source = roundMoveEngine();
const actor = source.playerToMove;
const destination = clone(source);
destination.player(actor).data.victoryPoints += 2; // durable progress despite any payment
destination.player(actor).data.credits = Math.max(source.player(actor).data.credits - 10, 0);
const report = evaluateEconomyPlanTransition(source, destination, actor, Command.Build, EMPTY, false);
expect(report.durableProgress).to.equal(true);
expect(report.wastefulSpend).to.equal(false);
});
it("rewards a resource-preserving Pass only when no productive alternative exists", () => {
const source = roundMoveEngine();
const actor = source.playerToMove;
const still = clone(source);
const onlyWaste = evaluateEconomyPlanTransition(source, still, actor, Command.Pass, EMPTY, false);
expect(onlyWaste.passPreservesResources).to.equal(true);
expect(onlyWaste.score).to.equal(ECONOMY_PLAN_TRANSITION_WEIGHTS.passPreserves);
const productiveExists = evaluateEconomyPlanTransition(source, still, actor, Command.Pass, EMPTY, true);
expect(productiveExists.passPreservesResources).to.equal(false);
expect(productiveExists.score).to.equal(0);
});
it("scores income compatible with the budget higher than an income-starved need", () => {
const engine = roundMoveEngine();
const actor = engine.playerToMove;
// Round-1 challenge position: ore income is positive, credit income is zero.
expect(engine.player(actor).resourceIncome(Resource.Credit)).to.equal(0);
const oreNeed = assessEconomyPlan(engine, actor, { credits: 0, ores: 3, knowledge: 0, qics: 0 });
const creditNeed = assessEconomyPlan(engine, actor, { credits: 6, ores: 0, knowledge: 0, qics: 0 });
expect(oreNeed.incomeCoverage).to.be.greaterThan(creditNeed.incomeCoverage);
expect(creditNeed.incomeCoverage).to.equal(0);
});
it("budgets a multi-action round, not just the single next prerequisite", () => {
const engine = roundMoveEngine();
const actor = engine.playerToMove;
expect(roundActionBudget(engine, actor, null, null)).to.deep.equal(EMPTY);
const mineSpread = roundActionBudget(engine, actor, "mine-spread", null);
expect(mineSpread.ores).to.be.greaterThan(1); // several mines, not one
expect(mineSpread.credits).to.be.greaterThan(0);
});
it("stays inert by default and only reports when explicitly enabled", () => {
const engine = roundMoveEngine();
const frozen = new StrategyPlanMacroBot().select(clone(engine));
expect(frozen.evaluation.economy).to.equal(null);
const enabled = new StrategyPlanMacroBot({ economyPlanning: true }).select(clone(engine));
expect(enabled.evaluation.economy).to.not.equal(null);
});
});

View file

@ -0,0 +1,316 @@
import Engine from "../../engine";
import { Building, Command, Phase, Player as PlayerEnum, ResearchField, Resource } from "../../enums";
import Player from "../../player";
/**
* Compatible-income / action-budget economic plan.
*
* The diagnosed AI-7 failure is not that the bot cannot afford actions; it is that its economy is
* *incompatible* with the actions it wants. Retained games end at 15 ore / 4 credits with capped
* wallets and stranded surplus, because the evaluator values each resource independently and never
* asks whether the wallet actually covers the *combination* the active plan needs next.
*
* This module scores a transition against the reserved cost bundle of the plan's next meaningful
* action. It rewards moving the wallet toward covering that combination, penalizes overflow past the
* hard resource caps and stranded surplus that ongoing income keeps feeding, penalizes spending that
* produces no durable progress, and — crucially — does not punish Pass when every alternative is only
* such a wasteful conversion. It is inspectable and ablatable; every term is reported.
*/
export const ECONOMY_PLAN_SCHEMA = "gaia-ai-economy-plan/v1" as const;
/** Hard engine storage caps (player-data.ts MAX_CREDIT / MAX_ORE / MAX_KNOWLEDGE). */
const RESOURCE_CAP = { credits: 30, ores: 15, knowledge: 15 } as const;
/** Shared marginal resource valuation, matching evaluation.ts RESOURCE_STOCK_VALUES / tempo.ts. */
const RESOURCE_WEIGHT = { credits: 0.22, ores: 0.8, knowledge: 1, qics: 1.2 } as const;
const RESOURCE_ENUM = {
credits: Resource.Credit,
ores: Resource.Ore,
knowledge: Resource.Knowledge,
qics: Resource.Qic,
} as const;
/**
* A modest operating buffer above a plan's declared need. Resources held beyond need + buffer, while
* income keeps arriving, are treated as stranded surplus rather than useful liquidity.
*/
const STRANDED_BUFFER = { credits: 6, ores: 4, knowledge: 4, qics: 2 } as const;
export interface EconomyReserveBundle {
credits: number;
ores: number;
knowledge: number;
qics: number;
}
export interface EconomyPlanAssessment {
schemaVersion: typeof ECONOMY_PLAN_SCHEMA;
bundle: EconomyReserveBundle;
/** Fraction of the required resource *combination* the current wallet covers (0..1). */
bundleCoverage: number;
/** Fraction of the budget's recurring resource needs that per-round income can refill (0..1). */
incomeCoverage: number;
/** Overflow value lost past the caps after the next income phase. */
capWaste: number;
/** Value of wallet held far above plan need while income keeps feeding it. */
strandedSurplus: number;
reasons: readonly string[];
}
export interface EconomyPlanTransitionReport {
schemaVersion: typeof ECONOMY_PLAN_SCHEMA;
command: Command;
bundleCoverageBefore: number;
bundleCoverageAfter: number;
bundleCoverageDelta: number;
incomeCoverageBefore: number;
incomeCoverageAfter: number;
incomeCoverageDelta: number;
capWasteBefore: number;
capWasteAfter: number;
capWasteReduction: number;
strandedSurplusBefore: number;
strandedSurplusAfter: number;
strandedSurplusReduction: number;
durableProgress: boolean;
resourceValueDelta: number;
wastefulSpend: boolean;
productiveAlternative: boolean;
passPreservesResources: boolean;
score: number;
}
/**
* Initial doctrine-aligned weights, deliberately not swept: covering the needed combination is the
* dominant term, cap waste and wasteful spend are real penalties, stranded surplus is a soft nudge,
* and Pass earns a small credit only when it is the resource-preserving choice.
*/
export const ECONOMY_PLAN_TRANSITION_WEIGHTS = {
coverage: 6,
incomeCoverage: 5,
capWasteReduction: 1,
strandedSurplusReduction: 0.4,
wastefulSpend: 4,
passPreserves: 1.5,
} as const;
function wallet(player: Player): EconomyReserveBundle {
return {
credits: player.data.credits,
ores: player.data.ores,
knowledge: player.data.knowledge,
qics: player.data.qics,
};
}
function remainingIncomePhases(engine: Engine): number {
if (engine.phase === Phase.EndGame) {
return 0;
}
if (engine.round <= 0) {
return 6;
}
if (engine.phase === Phase.RoundStart || engine.phase === Phase.RoundIncome) {
return Math.max(7 - engine.round, 0);
}
return Math.max(6 - engine.round, 0);
}
/** Whether at least one more income phase can still overflow the caps. */
function nextIncomeActive(engine: Engine): boolean {
return remainingIncomePhases(engine) > 0;
}
function resourceValue(player: Player): number {
const w = wallet(player);
return (
w.credits * RESOURCE_WEIGHT.credits +
w.ores * RESOURCE_WEIGHT.ores +
w.knowledge * RESOURCE_WEIGHT.knowledge +
w.qics * RESOURCE_WEIGHT.qics
);
}
/**
* Coverage of the *combination*: the fraction of each required resource the wallet holds, averaged
* over required resources. Piling on a resource already at 100% cannot raise coverage, so the term
* rewards buying what the plan is short of rather than more of what it already has.
*/
function bundleCoverage(available: EconomyReserveBundle, bundle: EconomyReserveBundle): number {
const keys = (Object.keys(bundle) as Array<keyof EconomyReserveBundle>).filter((key) => bundle[key] > 0);
if (keys.length === 0) {
return 1;
}
const total = keys.reduce((sum, key) => sum + Math.min(available[key] / bundle[key], 1), 0);
return total / keys.length;
}
/**
* Fraction of the budget's recurring needs that per-round income can refill. A flat mine economy
* has ore income but no credit/knowledge income, so a budget that needs credits/knowledge scores low
* here — rewarding the Trading Station / Lab income the diagnosed under-built engine never grew.
*/
function incomeCoverage(player: Player, bundle: EconomyReserveBundle): number {
const keys = (Object.keys(bundle) as Array<keyof EconomyReserveBundle>).filter((key) => bundle[key] > 0);
if (keys.length === 0) {
return 1;
}
const total = keys.reduce((sum, key) => {
const income = player.resourceIncome(RESOURCE_ENUM[key]);
const targetRate = Math.max(1, bundle[key] / 3);
return sum + Math.min(income / targetRate, 1);
}, 0);
return total / keys.length;
}
/** Value lost past the caps once the next income phase arrives (credits/ore/knowledge only). */
function capWaste(player: Player, engine: Engine): number {
if (!nextIncomeActive(engine)) {
return 0;
}
const w = wallet(player);
let waste = 0;
for (const key of ["credits", "ores", "knowledge"] as const) {
const resource = key === "credits" ? Resource.Credit : key === "ores" ? Resource.Ore : Resource.Knowledge;
const income = player.resourceIncome(resource);
waste += Math.max(w[key] + income - RESOURCE_CAP[key], 0) * RESOURCE_WEIGHT[key];
}
return waste;
}
/** Value held above plan need + buffer while income keeps feeding that resource (below the cap). */
function strandedSurplus(player: Player, engine: Engine, bundle: EconomyReserveBundle): number {
const w = wallet(player);
let stranded = 0;
for (const key of ["credits", "ores", "knowledge", "qics"] as const) {
const resource =
key === "credits"
? Resource.Credit
: key === "ores"
? Resource.Ore
: key === "knowledge"
? Resource.Knowledge
: Resource.Qic;
const income = key === "qics" ? player.resourceIncome(resource) : Math.min(player.resourceIncome(resource), 1);
if (income <= 0 && !nextIncomeActive(engine)) {
continue;
}
const excess = Math.max(w[key] - bundle[key] - STRANDED_BUFFER[key], 0);
stranded += excess * RESOURCE_WEIGHT[key];
}
return stranded;
}
export function assessEconomyPlan(
engine: Engine,
actor: PlayerEnum,
bundle: EconomyReserveBundle
): EconomyPlanAssessment {
const player = engine.player(actor);
const coverage = bundleCoverage(wallet(player), bundle);
const income = incomeCoverage(player, bundle);
const waste = capWaste(player, engine);
const stranded = strandedSurplus(player, engine, bundle);
return {
schemaVersion: ECONOMY_PLAN_SCHEMA,
bundle,
bundleCoverage: coverage,
incomeCoverage: income,
capWaste: waste,
strandedSurplus: stranded,
reasons: [
`bundle:c${bundle.credits}/o${bundle.ores}/k${bundle.knowledge}/q${bundle.qics}`,
`coverage:${coverage.toFixed(3)}`,
`income-coverage:${income.toFixed(3)}`,
`cap-waste:${waste.toFixed(3)}`,
`stranded-surplus:${stranded.toFixed(3)}`,
],
};
}
function buildingCount(player: Player, engine: Engine): number {
return Building.values(engine.expansions).reduce((sum, building) => sum + player.data.buildings[building], 0);
}
function researchCount(player: Player, engine: Engine): number {
return ResearchField.values(engine.expansions).reduce((sum, field) => sum + player.data.research[field], 0);
}
function federationCount(player: Player): number {
return player.data.tiles.federations.length + player.data.spaceshipFederations.length;
}
/**
* Durable progress is any gain in board/track/federation/exploration/Gaia development or score. It is
* intentionally independent of resource value: paying resources to advance the board is not waste.
*/
function durableProgress(source: Engine, destination: Engine, actor: PlayerEnum): boolean {
const before = source.player(actor);
const after = destination.player(actor);
return (
buildingCount(after, destination) > buildingCount(before, source) ||
researchCount(after, destination) > researchCount(before, source) ||
federationCount(after) > federationCount(before) ||
Object.keys(after.data.explorationShips).length > Object.keys(before.data.explorationShips).length ||
after.data.buildings[Building.GaiaFormer] + after.data.gaiaformersInGaia >
before.data.buildings[Building.GaiaFormer] + before.data.gaiaformersInGaia ||
after.data.victoryPoints > before.data.victoryPoints
);
}
export function economyPlanApplies(engine: Engine): boolean {
return engine.phase === Phase.RoundMove;
}
export function evaluateEconomyPlanTransition(
source: Engine,
destination: Engine,
actor: PlayerEnum,
command: Command,
bundle: EconomyReserveBundle,
productiveAlternative: boolean,
weights: typeof ECONOMY_PLAN_TRANSITION_WEIGHTS = ECONOMY_PLAN_TRANSITION_WEIGHTS
): EconomyPlanTransitionReport {
const before = assessEconomyPlan(source, actor, bundle);
const after = assessEconomyPlan(destination, actor, bundle);
const bundleCoverageDelta = after.bundleCoverage - before.bundleCoverage;
const incomeCoverageDelta = after.incomeCoverage - before.incomeCoverage;
const capWasteReduction = before.capWaste - after.capWaste;
const strandedSurplusReduction = before.strandedSurplus - after.strandedSurplus;
const progress = durableProgress(source, destination, actor);
const resourceValueDelta = resourceValue(destination.player(actor)) - resourceValue(source.player(actor));
const wastefulSpend = command !== Command.Pass && !progress && resourceValueDelta < -0.25;
const passPreservesResources = command === Command.Pass && !productiveAlternative;
const score =
bundleCoverageDelta * weights.coverage +
incomeCoverageDelta * weights.incomeCoverage +
capWasteReduction * weights.capWasteReduction +
strandedSurplusReduction * weights.strandedSurplusReduction -
(wastefulSpend ? weights.wastefulSpend : 0) +
(passPreservesResources ? weights.passPreserves : 0);
return {
schemaVersion: ECONOMY_PLAN_SCHEMA,
command,
bundleCoverageBefore: before.bundleCoverage,
bundleCoverageAfter: after.bundleCoverage,
bundleCoverageDelta,
incomeCoverageBefore: before.incomeCoverage,
incomeCoverageAfter: after.incomeCoverage,
incomeCoverageDelta,
capWasteBefore: before.capWaste,
capWasteAfter: after.capWaste,
capWasteReduction,
strandedSurplusBefore: before.strandedSurplus,
strandedSurplusAfter: after.strandedSurplus,
strandedSurplusReduction,
durableProgress: progress,
resourceValueDelta,
wastefulSpend,
productiveAlternative,
passPreservesResources,
score,
};
}

View file

@ -0,0 +1,59 @@
import { expect } from "chai";
import "mocha";
import { STRATEGY_PRINCIPLES, STRATEGY_SOURCES, strategyCoverageReport } from "./knowledge";
describe("AI-7 strategy knowledge traceability", () => {
it("gives every source and normalized principle a stable unique id", () => {
expect(new Set(STRATEGY_SOURCES.map((source) => source.id)).size).to.equal(STRATEGY_SOURCES.length);
expect(new Set(STRATEGY_PRINCIPLES.map((principle) => principle.id)).size).to.equal(STRATEGY_PRINCIPLES.length);
});
it("maps every retained principle to known sources and at least one inspectable AI disposition", () => {
const sourceIds = new Set(STRATEGY_SOURCES.map((source) => source.id));
for (const principle of STRATEGY_PRINCIPLES) {
expect(principle.statement.trim(), principle.id).to.not.equal("");
expect(principle.sourceIds.length, principle.id).to.be.greaterThan(0);
expect(principle.applications.length, principle.id).to.be.greaterThan(0);
for (const sourceId of principle.sourceIds) {
expect(sourceIds.has(sourceId), `${principle.id} -> ${sourceId}`).to.equal(true);
}
for (const application of principle.applications) {
expect(application.target.trim(), `${principle.id} -> ${application.kind}`).to.not.equal("");
}
}
});
it("keeps contested or rejected advice out of unconditional policy", () => {
for (const principle of STRATEGY_PRINCIPLES.filter((entry) => entry.confidence === "contested")) {
expect(
principle.applications.some(
(application) => application.kind === "documented-hypothesis" || application.kind === "rejected-universal"
),
principle.id
).to.equal(true);
}
expect(
STRATEGY_PRINCIPLES.filter((principle) =>
principle.applications.some((application) => application.kind === "rejected-universal")
).map((principle) => principle.id)
).to.include.members([
"opening-academy-strong-contextual",
"economy-spend-productively",
"research-focused-but-adaptive",
"technology-enables-plan",
"advanced-tech-remaining-uses",
"lost-fleet-ship-context",
"faction-identity-modifies-plans",
]);
});
it("reports source, confidence, and application coverage without losing hypotheses", () => {
const report = strategyCoverageReport();
expect(report.sourceCount).to.equal(STRATEGY_SOURCES.length);
expect(report.principleCount).to.equal(STRATEGY_PRINCIPLES.length);
expect(report.byApplication["active-plan"]).to.be.greaterThan(0);
expect(report.byApplication["active-feature"]).to.be.greaterThan(0);
expect(report.byApplication["documented-hypothesis"]).to.be.greaterThan(0);
expect(report.byApplication["rejected-universal"]).to.be.greaterThan(0);
});
});

Some files were not shown because too many files have changed in this diff Show more