Compare commits

...

584 commits

Author SHA1 Message Date
github-actions
415a24c7a9 🔖 powergrid-viewer 2.3.34
Some checks are pending
All / prettier (push) Waiting to run
Viewer - Test / test_and_build (push) Waiting to run
2026-11-21 23:09:01 +00:00
goldjohn6
a8a7718b50
Map zoom (#176)
* Zoom the map: buttons, pinch, wheel, and drag to pan

Players asked for a way to zoom in after the board is fitted to the
screen. This adds a zoom on the map alone, on top of the fitted layout,
in both the desktop and portrait layouts.

- + / − / reset buttons in the map's top-right corner, sized in screen
  pixels so they stay thumb-sized on a phone.
- Two-finger pinch on touch screens zooms the map, not the page. One
  finger pans once zoomed; at the fitted size it still scrolls the page.
- Trackpad pinch (ctrl+wheel) everywhere; a plain wheel also zooms on
  desktop, where the board fits the window.
- Mouse drag pans when zoomed. A press that moves more than 6 px is a
  pan, and the click that follows it is swallowed, so a drag never
  builds a city.
- Clamped between the fit and 4x, and the zoomed map always covers its
  own box. It is clipped to that box, so it never covers the market or
  player boards.

The zoom layer sits outside the measured map slot, so the layout's
getBBox() measurement never sees it. The maths is in util/map-zoom.ts
with unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Map zoom: a faint outline and a minimap while zoomed

Asked for with older players in mind, so a zoomed map never leaves
anyone lost. Nothing changes at the fitted size. While zoomed:

- a faint white outline round the map's box, so it reads as a zoomed view;
- a small overview of the whole map in the bottom-left corner (the
  buttons are top-right), rounded, with an orange box over the part on
  screen. Tapping the overview centres the view there.

The overview is a <use> of the map slot, so it always matches the board.
It is sized in screen pixels, from 72 to 128 px on its long side, and
keeps the map's own proportions in both the desktop and portrait
layouts. Gestures never start on the overview or the buttons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Map zoom: a plain wheel scrolls the page, Ctrl+wheel zooms

Someone scrolling down to the resources or the chat must never zoom by
accident, so a plain wheel over the map always scrolls the page. It also
shows a brief hint, "Hold Ctrl and scroll to zoom" (⌘ on a Mac), the way
embedded maps do. Ctrl/⌘ + wheel and trackpad pinch zoom the map, and
the + / − tooltips mention both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 15:02:26 -08:00
goldjohn6
1a8c74f55e
Seed the bots in the Spain & Portugal Step 2 test (#175)
The test seeded the game but not the bots, which choose with Math.random,
so a game could now and then draw the Step 3 card during Step 1 and skip
Step 2 (Engine - Test failed this way on master after #173, then passed on
re-run). A sweep of 400 bot seeds: deck2 skips Step 2 in 13 games (3.3%),
deck1 in 1. Seeding Math.random per deck, as wrapper.spec does, makes the
test the same on every run.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:25:51 -08:00
github-actions
03f9986bb1 🔖 powergrid-viewer 2.3.33 2026-11-20 19:25:15 +00:00
github-actions
b6f0910eb3 🔖 powergrid-engine 2.0.38 2026-11-20 19:23:09 +00:00
goldjohn6
49c2a80f7e
SwitzerlandCustom: the cheese cellar (#174)
* SwitzerlandCustom: the cheese cellar (garbage is cheese, and it ripens)

Cheese kept in a garbage plant that rests through Bureaucracy (does not fire)
ages; an aged cube burns as two, stays aged until burned, never ages again,
and still takes one storage space.

- Player.agedCheese (read through agedCheese(): never above garbageLeft, so
  cubes lost to storage go aged-first).
- cheeseMix: the engine offers the thriftiest mix (least waste, then fewest
  cubes); UsePowerPlant.agedSpent records the aged cubes burned.
- ripenCheese at the Bureaucracy pass: a resting plant ripens only the room it
  has left (aged cubes are counted in the plants that fired first). Logged.
- calculateMaxCitiesPowered counts aged cheese as double.
- Bots burn aged cheese first and fire fresh-cheese plants last, so spare
  cheese plants rest and ripen.
- Viewer: "N aged" above the player's garbage count.

Bot sims (150 games each, 3/4/5p): 3-5 cubes age per game, 18-25% of cheese
runs use aged cheese; Step 3 is reached more often (4p 79%->89%, 5p 34%->45%).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Cheese cellar: an aged cube stays aged after its neighbour burns

Found in John's local playtest (plant 6, two aged, used one): the aged count
was read after the cubes left, so the cap by cubes held wiped the remaining
aged cube. Count it before. The "N aged" label moves below the cheese count,
clear of the plant cards, and the pass warning counts aged cheese as double.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:19:34 -08:00
goldjohn6
d0f8c48547
SwitzerlandCustom: a new community custom map (#173)
* SwitzerlandCustom: a new custom map (Alpine hydro, neutral Geneva, helicopters)

The seven Swiss Grossregionen, 49 cities, 95 links priced from real distances
(+6 into an Alpine city, +2 over a named pass; Gotthard 16).

- Alpine hydro: each ecological or fusion plant fired powers one more city,
  but only as many of those plants as the player owns Alpine cities
  (City.alpine; alpineBonusLeft / alpineEligible; calculateMaxCitiesPowered).
- Geneva is neutral: all three spaces open from Step 1 (stepSlots [3,3,3]).
- Lake Geneva steamer (sea), Glacier Express, three outskirt helicopters
  (Connection.air, drawn dotted and curved clear of cities). The Glacier
  Express, Oberalp and helicopters never decide which regions are dealt
  together; Ticino gets the Gotthard Base Tunnel and the Lukmanier.
- Viewer: Swiss outline (landlocked: neighbours all round), and the faded
  unplayed regions now cover community custom maps too, without curved links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SwitzerlandCustom: green plants only for the Alpine +1; an expensive country

- The Alpine +1 is for green (ecological) plants only, never fusion (John:
  6 + 1 = 7 from one card is too strong). Rules text says so explicitly.
- Starting market: coal opens at $3 and oil at $4, while cheese is plentiful
  and opens at $5; uranium as usual ([18, 15, 12, 2], both editions).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the Central Europe comment on garbagePrice

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SwitzerlandCustom: power plants send the engine's offer; Alpine peaks

Found in John's local playtest: the viewer built its own UsePowerPlant move
from the printed card, so the engine refused a green plant with the Alpine
+1. A single-fuel plant now sends the engine's own offer (hybrids keep the
mix the player picked). freePlantMoves takes each offer after the previous
plant fires (on a copy), since the Alpine +1 is shared out; the powered-cities
count includes it. A snow-capped peak sits behind each Alpine city.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SwitzerlandCustom: cheese opens at $6 (John, after his playtest)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SwitzerlandCustom: the building-phase power capacity counts the Alpine +1

Found in John's playtest: 18 + 30 + 20 with Alpine cities showed 13, not 14.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* SwitzerlandCustom: the Glacier Express drawn as a red railway

Connection.rail (visual only): red rails over a pale bed, crossed by red ties.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:06:59 -08:00
c8bf10538f Release phase auto-pass engine 2.0.37 and viewer 2.3.32 2026-11-17 22:21:20 +00:00
github-actions
0c2f9b977d 🔖 powergrid-viewer 2.3.31 2026-11-17 20:59:13 +00:00
github-actions
ac81ccd52d 🔖 powergrid-engine 2.0.36 2026-11-17 20:55:24 +00:00
goldjohn6
0edd7fd8a7
HawaiiCustom: a new custom map (island prices, ferry, shipped-in fuel) (#172)
* HawaiiCustom draft: custom map, ferry curve, sea crossings, house-price legend

Local draft for the community custom-map thread (not for release yet).
- engine: HawaiiCustom map (44 cities, 6 regions, house prices by island,
  payout +1, Kauai-Big Island ferry); customMaps list (by name only, never
  Random); GameMap.paymentTable / houseLegend; Connection.via / sea /
  ignoreForRegions
- viewer: curved via-links, dashed blue sea crossings, house-price legend,
  Hawaii land outlines, ?fullmap=1 for layout checks
- tests: hawaii-custom.spec.ts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* HawaiiCustom: Kauai at standard prices, shipped-in fuel (coal 2, oil 4)

Kauai already had the cheapest links on the board, so cheap houses on top made
it too strong (BootlegTampico on Discord); it moves to the standard 10/15/20.
Fuel is shipped in: the market starts with the three cheapest coal and oil left
in the supply, so coal starts at 2 and oil at 4. Garbage and uranium start as
each variant has them (Recharged still fills garbage to 9). Rules text updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Achievements: community custom maps get no Champion badge

Master's achievements give every map a Champion badge typed as
Record<MapName, string>, so adding HawaiiCustom broke the build. A badge needs
its own artwork and a manifest publication, so custom maps are left out for
now (the lookup already handles a map with no badge). A test covers a
HawaiiCustom win: grid-champion and full-table, no map badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Geography test: cover custom maps (Hawaii has no neighbouring coast)

The catalog now holds Hawaii, so the count is standard maps plus custom maps,
and Hawaii is checked like the others. Its context is empty on purpose: it
sits in open ocean, with no other coast inside its frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:47:14 -08:00
MikeIsom
8052e1d592
It's Chile time! (#171)
* Count only wind plants as ecological, behind one switch

Benelux's extra market slot and Québec's protected plants now share one
isEcological() helper. Fusion is not ecological unless FUSION_IS_ECOLOGICAL
is flipped. New Benelux and Québec games store the ruling as
options.fusionEcological, so flipping it later only affects new games.

Québec's deck setup used to protect fusion plant 50 while its bureaucracy
and Benelux did not. Games without the stored flag rebuild their Québec
deck the old way via reconstructionOptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add a power plant deck option with Deck 1, Deck 2 and Random

New games choose a deck with options.powerPlantDeck: standard, deck1 (The
New Power Plants / Set 1, without 52-60), deck2 (Set 2) or random, which
resolves from the seed and stores the result. Only a non-standard deck is
stored.

Deck 1 deals from 01-08 with 11 on top in the Original edition and from
the 01-16 plug cards in Recharged. Deck 1 and Deck 2 are offered on maps
whose setup doesn't name standard-deck plant numbers; the rest fall back
to the standard deck until their per-deck changes land. Germany's uranium
phase-out triggers on 38 (Deck 1) or 37 (Deck 2).

The legacy alternatePowerPlants flag keeps its Europe/North America-only
behaviour and storage, so existing games set up identically.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Offer Deck 1 and Deck 2 on every map

Map rules that name plant numbers now look them up per deck in
deckChanges.ts: removed plants, market openers, top-of-deck plants and
Spain & Portugal's Step 2 plants, from the decks' 2024 map-changes sheets.
Map setup and the deck analysis share that table. Original-edition games
use the same numbers, except France with Deck 1, which follows The New
Power Plants rulebook (remove 11).

Australia, India, South Africa, Spain & Portugal and UK & Ireland now use
the shared default setup instead of their own copies. India has a version
of each deck. Italy's uranium phase-out uses Germany's plant per deck.
Northern Europe's regional cards replace the deck's plants by number, and
a regional plant the deck lacks is shuffled into the draw pile. Middle
East closes garbage purchases in Step 1, for Deck 2's garbage/oil hybrids.

Standard-deck setups are unchanged for old and new games. Also stops the
ecological replay test from comparing the transient pendingMessages queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add shuffled power plant decks: all decks, or one per number

powerPlantDeck now also takes 'shuffled' (every plant of the standard deck,
Deck 1 and Deck 2 together) and 'shuffledUnique' (one random copy of each
number, without Deck 1's 52-60). Extra copies are numbered n.1 (Deck 1) and
n.2 (Deck 2), so the market ranks duplicates Deck 2 > Deck 1 > Original and
moves keep identifying plants by number. Cards show the printed number, and
logs read "Power Plant 46 (Deck 2)"; the journal and the deck analysis
parse that label back to the copy.

Bids start at the printed number, the Original discard rule and plug
cards compare it, and each deck's own nuclear plant ends Germany's and
Italy's uranium resupply. The shuffled decks are only offered on maps
whose rules don't name plant numbers; Random still picks a single deck.

Standard-deck setups are unchanged for old and new games.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Offer the shuffled decks on maps with deck-specific rules

The shuffled decks follow all three decks' map rules at once, for the
copies dealt: Deck 1's and Deck 2's plant numbers become n.1 and n.2.
This opens them on Australia, Brazil, Bremen, China, France, India,
Manhattan, Middle East, Recharged Russia, South Africa and Spain &
Portugal.

Exceptions, where the decks' rules clash:
- Northern Europe and Quebec keep the single decks only.
- Original Russia keeps the single decks only (availableDecks now takes
  the variant).
- Original "top of the deck" plants use the standard deck's list.

Spain & Portugal stores the dealt held-back copies in heldPowerPlants
and puts them on top at Step 2. India's shuffled decks keep India's
garbage plants. Map setups deal the sampled deck and split plug cards
with isPlugPlant.

The analysis sampler now copes with shuffled decks: undealt top plants,
protected-plant overflow and plug-count estimates are capped. The
Middle East public replay resets the plant discount before refiltering
its opening market.

Single-deck setups are byte-identical to before for every map,
variant, deck, player count and seed checked.

* Offer the shuffled decks on Northern Europe, Quebec and Original Russia

Where the three decks' rules clash, the shuffled decks now follow each
rule's purpose:

- Northern Europe: each regional plant in play is always dealt. It takes
  the place of one dealt copy of its number, and every other copy leaves
  the game; a regional number that wasn't dealt is shuffled in. This
  also applies once the regions are drafted, which now also updates
  cardsLeft.
- Quebec: one plug card on top of the deck, then the two smallest dealt
  ecological plants not in the market. The Recharged market is drawn
  from the plug cards; the Original market is the eight smallest plants,
  with the standard deck's 13 (if dealt) or else the smallest plug card
  left on top. Ecological plants are never removed.
- Original Russia: the six smallest dealt plants open the market, the
  standard deck's 13 goes on top if dealt, and the 7th and 8th smallest
  plants are shuffled into the top five.

The analysis sampler mirrors all three. Maps can give a `shuffled` deck
note, which the viewer shows for the shuffled decks.

Single-deck setups are unchanged for every map, variant, deck, player
count and seed checked.

* Generate the rules tab's deck build from the deck tables

The rules dialog's "Deck build" section is now built from the same tables
the decks are dealt from (deckChanges.ts and each deck's card list), so
it names the right plants for Deck 1, Deck 2 and the shuffled decks
instead of always the Original deck's. Shuffled games list each rule's
plants as Original deck / Deck 1 / Deck 2, with a sentence explaining
that only the dealt plants count. Player-count lists show the game's
own player count.

Each sentence is a template with plant numbers as {pN} values, rendered
in its own span, so the catalogues translate it whole. The 54 new
templates are translated into all 16 languages; the 20 old deck-build
sentences are removed. The maps' hand-written deckBuild notes are gone.

Tests read the plant numbers back out of the generated text and compare
them with real setups for every map, edition, single deck and player
count, and check that every sentence translates in every language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Describe Central Europe's nuclear and Wien rules

Central Europe had no map rules text, though the engine limits nuclear
plants to players with a city in Czechia, Slovakia or Hungary and gives
a Wien network $1 off garbage (never below $1). The rules dialog now
says so, in all 17 languages, using each catalogue's own name for Wien.

The dialog reads a map's rules from the current map definition rather
than the copy saved in the game, so games already under way see rules
text added later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Outline buildable Bremen districts around the diamond

The blue build hint and the gold region-draft ring were fixed 18-unit
circles, which on Bremen's diamond tiles crossed the entry cost and slot
numbers. Bremen's tiles now get a diamond outline just outside their own
region border instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Begin Step 2 first when the Step 3 card comes early

The rulebooks: if the Step 3 card is drawn before Step 2 has begun,
carry out everything that begins Step 2, then prepare Step 3, back to
back. The engine only did this on UK & Ireland, and without Step 2's
own setup, so on Spain & Portugal the held-back plants never came back.

Step 2's setup (the smallest plant leaves, Spain & Portugal puts its
held-back plants on top, a new plant is drawn) is now one function.
Normal Step 2 uses it unchanged, and an early Step 3 card runs it first:
straight away outside the auction, or at the end of the auction phase
with Step 3's own setup, which then shuffles the draw pile again.
Middle East, China and Manhattan keep their own rules.

New games store step2BeforeStep3; games created earlier replay with
their old sequence.

The rules summary now lists what happens when Step 2 and Step 3 start,
and the early-Step-3 order, in all 17 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove a stale Manhattan line brought back by the master merge

Merging the fork's older master into combined-deck-rules restored
`const lastPlug = lastPlugPlant(powerPlantDeck)` in Manhattan's setup.
lastPlugPlant isn't imported there and the value is unused, so the
engine build failed and CI went red on the branch and on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile map: board generated from the design data

scripts/generate-chile-map.mjs writes engine/src/maps/chile-board.ts from the
design's chile-map-data.json: 43 cities (Salta in no region, single
occupancy), 59 connections, and the two Step 3 gates kept apart. Regions are
their colours, as on the other maps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Map rules: Chile (two markets on one supply, Step 3 gates, set-aside eco plants)

- maps/chile.ts: no uranium plants (11, 17, 23, 28, 34, 39), plants 33, 37
  and 44 set aside, none removed for the player count, under Original and
  Recharged. Standard deck only (other decks throw).
- Two markets on Korea's machinery: North (12 coal, 8 oil, no garbage) and
  Central (12 coal, 10 oil, 4 garbage), one shared 24/24/24 supply, no
  uranium. North restocks first from its own table.
- Buying: until Step 3 a player with cities buys only from their grid's
  market (marketSideOf); a player with no cities picks one for the turn.
- Gates live in GameMap.step3Connections, out of every build and path until
  Step 3, but they count when choosing play areas. A city in no region
  (Salta) is in play when it connects to one that is.
- applyChileStep3, beside each Step 3 start: merge the markets onto the
  standard tracks from the expensive end, open the gates, put 33/37/44 on
  top of the deck, and give every ecological plant +1 city (copies, never
  the catalogue's objects; fusion 50 unchanged). Runs once.
- Random map pick leaves Chile out, so every seed picks as before.
- chile.spec.ts: 36 tests for each mechanic, both variants, 2-6 players.

Every other map plays as before: 2,400 seeded games over all 24 maps
(Original and Recharged, 2-6 players, random and param bots) end in the
same states as on 28b88b5 (powergrid-manager engine-fingerprint).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile: hidden-deck replay, analysis scenarios, no randomized map

From an independent review of the Chile change:
- reconstructState (secret seed) took the live map, so a game past Step 3
  rewound to earlier states with its gates already open and replayed two
  log events short. closeChileGates puts the gates back for the replay, and
  the set-aside event is logged even when the known Step 3 deck is used.
- createAnalysisScenario dealt uranium plants and the set-aside plants into
  Chile's unknown deck. It now leaves them out, and in Step 3 keeps the
  set-aside plants on top in order and boosts ecological plants.
- randomizeMap on Chile throws: its gates and grids belong to its board.

Each new test fails without its fix. Other maps: 2,400 fingerprint games
still identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile update 1: northern regions cross the divide; grid per city

- Board regenerated from the redrawn design: Alto Hospicio merged into
  Iquique, Antofagasta N/S into Antofagasta, Putre and Pica removed;
  Taltal and Chañaral (brown), El Salvador (yellow) and Illapel (purple)
  added; Copiapó moved to yellow. 58 connections. Gates are now inside the
  northern regions: Antofagasta-Taltal and Sierra Gorda-El Salvador.
- Each city carries its grid (City.grid); marketSideOf reads the grids of
  a player's cities instead of whole regions. GameMap.northRegions is gone.
- GameMap.fixedRegions: brown and yellow are always in play; the random
  pick and the region draft add the remaining regions as usual (2-3P
  purple, 4P purple + red, 5-6P purple, red and green or pink).
- The gate-adjacency rule is removed: the region graph uses open
  connections only, as before Chile.
- chile.spec.ts: grids per city, gates the only North-Central links and
  one per northern region, fixed areas at 2-4P, the draft, Taltal and
  Copiapó buy from Central. The secret-seed replay test now compares the
  Step 3 events: a hidden-deck replay can drop one "drawn from the deck"
  entry around the Step 3 card on any map (USA seed r2 too).

Other maps: the 2,400 fingerprint games still end in identical states.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile: Salta pays a $10 house on top of its connection

A singleOccupancy city with a slot cost adds it to the build price (and to
the cities spent when totals are tracked). South Africa's spaces have no
slot costs and price as before; the board generator carries Salta's
slotCosts [10] from the design data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile: more Step 3 restock at 2-4P (2-3P coal 4 garbage 4; 4P coal 5 garbage 5)

Checkpoint 3 found the merged market short of fuel at 2-4P. Adds a test of
the Step 3 restock at every player count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile: Tacna and Jujuy border spaces, in play with 4-6 players

Cities may carry minPlayers; filterMapToRegions leaves them out below
that count (no other map uses the field). Tacna (Peru, off Arica, $12)
and Jujuy (Argentina, off San Pedro, $20) are one-house spaces like Salta.
Tests check they appear only at 4-6P, also after an area draft.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile: 5P Step 3 restock 4/5/4 (was 5/6/5)

Fuel scarcity in Step 3 caps the Central players' extra cities at 5P, as it
does at 4P: North vs Central placement goes from 0.629/0.468 to 0.543/0.489
with one North player and from 0.435/0.543 to 0.474/0.517 with two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile: separate 2P and 3P restock; 3P Step 1 coal is 1 North / 3 Central

A lone North player won far too often at 3P (North openers 40.7% wins,
Central 27.4%, fair 33.3%). Moving one Step 1 coal from the North market
to Central gives 33.4% / 33.3%. 2P keeps the old 2-3P row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile: the ladder board (two-lane Central corridor) with Mejillones-Maria Elena 12 and Taltal-El Salvador 14

Huasco, Melipilla, San Fernando, Santa Cruz and Cauquenes join; Coquimbo, Talcahuano and Coronel go; Los Angeles
moves to pink. No chokepoint city at any player count. The hidden-deck replay test skips seed r1, which now hits a
ChoosePowerPlant replay mismatch that is not Chile's (Germany r4 shows it too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile on the current engine: standard deck only, border-space house price in buildOptions

- STANDARD_DECK_ONLY_MAPS (Chile): setup refuses deck1, deck2 and the shuffled decks, and a random deck is the
  standard one; the every-map deck tests expect that.
- The border spaces' $10 house (slotCosts) is added in buildOptions, where building prices now live.
- The Chile spec uses powerPlantDeck.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile in the viewer: gates, Central market, backdrop and a landscape layout

- Map: the gated connections (step3Connections) are drawn with their cost, a dashed orange line and an S3 marker
  until Step 3; border spaces with a slot cost get their own tooltip (one house, $10 plus the connection).
- Markets: Chile's second market is titled Central, with no uranium row and no North garbage row.
- Geography: Chile's backdrop (Natural Earth 1:50m, from the Chile design's generator).
- Layout: the board turned to run left to right at 70%. GameMap.mapRotationCenter (optional) keeps a rotated board
  still whichever regions are in play; maps without it rotate around their cities as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile rulebook (docs/maps/chile.md) and board image

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile on Power Plant decks 1 and 2 (test branch)

Chile's deck setup, set-aside plants, Step 3 boost and analysis now follow the
deck in play. Per deck: uranium plants removed (deck 1: 8, 19, 24, 31, 38, 50;
deck 2: 13, 21, 32, 37, 50), the three largest ecological plants set aside
(deck 1: 26, 32, 39; deck 2: 31, 36, 44), and the smallest ecological plant on
top in the original edition (11 on both). The shuffled decks are still refused.
Standard-deck games are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile on the shuffled decks

The three largest ecological plants dealt are set aside (all of them when a
sampled deck deals three or fewer); in the original edition the smallest
ecological plant dealt that isn't in the market goes on top, or none if there
is none. Chile's setupDeck now returns its set-aside plants; analysis reads
them from the state, or from the Step 3 log once they have gone on top.
Standard-deck games are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile board stretched 2x east-west; backdrop cut along the board's axes

The design's cross-board scale doubles (city positions only: connections and
costs are unchanged; Rancagua nudged clear of the Santiago E-San Fernando
line). The viewer's backdrop is cut along the board's own axes, far past the
cities, so the turned board no longer shows slanted land edges. Layout refitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile turns to suit the screen: diagonal on wide screens, upright on tall ones

A map may set mapRotationPortrait, the turn the viewer uses in its stacked
(tall-screen) layout; only Chile sets it. Chile's board data is now written
upright (north up, east right), so the tall view needs no turn and the layout
measures it tightly; wide screens turn it 70 degrees, running from the top left
(north) to the bottom right. City positions only; play is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Format the Chile board generator with Prettier

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Translate Chile's deck-setup sentences in every viewer language

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Merge boardgamers/powergrid master (engine 2.0.35, viewer 2.3.30) into the fork

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Achievements: Chile, in testing, has no map badge yet

The published manifest keeps its 36 achievements; a Chile winner still earns
the general wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Prettier: leave the generated badge manifest and release receipts as recorded; format the rest

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Chile Champion: a map badge for Chile (achievements revision 4, 37 badges)

Chile's real outline (Natural Earth 1:50m), from Arica to Puerto Montt,
widened 2x east-west and turned like the game board so it reads at badge
size. The 36 published badges, their images and the evaluator are unchanged;
the checks now allow exactly this one addition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix the line break in the Chile line of the art checker

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:41:45 -08:00
621586b7ec Fix dropped-player setup progression and release engine 2.0.35 2026-11-14 18:19:54 +00:00
dda6a51a71 Record verified achievement artwork 2.0.34 revision 3 publication 2026-11-14 13:06:03 +00:00
1e4162a380 Frame achievement maps from scoped geographic silhouettes 2026-11-14 12:25:51 +00:00
242ffd7abd Add original artwork for all 36 Power Grid achievements 2026-11-14 12:15:29 +00:00
c52a87e4b9 Record verified BGS achievements 2.0.33 revision 2 publication 2026-11-14 01:31:36 +00:00
2f89876e71 Expand map victories and raise fully supplied achievement threshold 2026-11-14 01:26:13 +00:00
eb08aaf26d Record verified BGS achievements 2.0.32 publication 2026-11-14 00:52:41 +00:00
d4c4b236aa Release Power Grid engine 2.0.32 achievements 2026-11-14 00:51:02 +00:00
c8aae01636 Add Power Grid endgame achievements for coordinator review 2026-11-14 00:45:55 +00:00
abe1c841bd Release analysis money editing: engine 2.0.31 and viewer 2.3.30 2026-11-13 12:53:02 +00:00
cd400d019e Record verified BGS engine 2.0.30 publication 2026-11-12 21:57:46 +00:00
da164b00ba Release engine 2.0.30: reveal sealed bids in fixed seat order 2026-11-12 21:57:10 +00:00
github-actions
e433b2ad0d 🔖 powergrid-viewer 2.3.29 2026-11-11 21:50:21 +00:00
github-actions
65f9b9f073 🔖 powergrid-engine 2.0.29 2026-11-11 21:48:28 +00:00
MikeIsom
96f3dedd5e
Shuffled Decks on every map, deck rules on the rules window, skipping Step 2 fix (#169)
* Count only wind plants as ecological, behind one switch

Benelux's extra market slot and Québec's protected plants now share one
isEcological() helper. Fusion is not ecological unless FUSION_IS_ECOLOGICAL
is flipped. New Benelux and Québec games store the ruling as
options.fusionEcological, so flipping it later only affects new games.

Québec's deck setup used to protect fusion plant 50 while its bureaucracy
and Benelux did not. Games without the stored flag rebuild their Québec
deck the old way via reconstructionOptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add a power plant deck option with Deck 1, Deck 2 and Random

New games choose a deck with options.powerPlantDeck: standard, deck1 (The
New Power Plants / Set 1, without 52-60), deck2 (Set 2) or random, which
resolves from the seed and stores the result. Only a non-standard deck is
stored.

Deck 1 deals from 01-08 with 11 on top in the Original edition and from
the 01-16 plug cards in Recharged. Deck 1 and Deck 2 are offered on maps
whose setup doesn't name standard-deck plant numbers; the rest fall back
to the standard deck until their per-deck changes land. Germany's uranium
phase-out triggers on 38 (Deck 1) or 37 (Deck 2).

The legacy alternatePowerPlants flag keeps its Europe/North America-only
behaviour and storage, so existing games set up identically.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Offer Deck 1 and Deck 2 on every map

Map rules that name plant numbers now look them up per deck in
deckChanges.ts: removed plants, market openers, top-of-deck plants and
Spain & Portugal's Step 2 plants, from the decks' 2024 map-changes sheets.
Map setup and the deck analysis share that table. Original-edition games
use the same numbers, except France with Deck 1, which follows The New
Power Plants rulebook (remove 11).

Australia, India, South Africa, Spain & Portugal and UK & Ireland now use
the shared default setup instead of their own copies. India has a version
of each deck. Italy's uranium phase-out uses Germany's plant per deck.
Northern Europe's regional cards replace the deck's plants by number, and
a regional plant the deck lacks is shuffled into the draw pile. Middle
East closes garbage purchases in Step 1, for Deck 2's garbage/oil hybrids.

Standard-deck setups are unchanged for old and new games. Also stops the
ecological replay test from comparing the transient pendingMessages queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add shuffled power plant decks: all decks, or one per number

powerPlantDeck now also takes 'shuffled' (every plant of the standard deck,
Deck 1 and Deck 2 together) and 'shuffledUnique' (one random copy of each
number, without Deck 1's 52-60). Extra copies are numbered n.1 (Deck 1) and
n.2 (Deck 2), so the market ranks duplicates Deck 2 > Deck 1 > Original and
moves keep identifying plants by number. Cards show the printed number, and
logs read "Power Plant 46 (Deck 2)"; the journal and the deck analysis
parse that label back to the copy.

Bids start at the printed number, the Original discard rule and plug
cards compare it, and each deck's own nuclear plant ends Germany's and
Italy's uranium resupply. The shuffled decks are only offered on maps
whose rules don't name plant numbers; Random still picks a single deck.

Standard-deck setups are unchanged for old and new games.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Offer the shuffled decks on maps with deck-specific rules

The shuffled decks follow all three decks' map rules at once, for the
copies dealt: Deck 1's and Deck 2's plant numbers become n.1 and n.2.
This opens them on Australia, Brazil, Bremen, China, France, India,
Manhattan, Middle East, Recharged Russia, South Africa and Spain &
Portugal.

Exceptions, where the decks' rules clash:
- Northern Europe and Quebec keep the single decks only.
- Original Russia keeps the single decks only (availableDecks now takes
  the variant).
- Original "top of the deck" plants use the standard deck's list.

Spain & Portugal stores the dealt held-back copies in heldPowerPlants
and puts them on top at Step 2. India's shuffled decks keep India's
garbage plants. Map setups deal the sampled deck and split plug cards
with isPlugPlant.

The analysis sampler now copes with shuffled decks: undealt top plants,
protected-plant overflow and plug-count estimates are capped. The
Middle East public replay resets the plant discount before refiltering
its opening market.

Single-deck setups are byte-identical to before for every map,
variant, deck, player count and seed checked.

* Offer the shuffled decks on Northern Europe, Quebec and Original Russia

Where the three decks' rules clash, the shuffled decks now follow each
rule's purpose:

- Northern Europe: each regional plant in play is always dealt. It takes
  the place of one dealt copy of its number, and every other copy leaves
  the game; a regional number that wasn't dealt is shuffled in. This
  also applies once the regions are drafted, which now also updates
  cardsLeft.
- Quebec: one plug card on top of the deck, then the two smallest dealt
  ecological plants not in the market. The Recharged market is drawn
  from the plug cards; the Original market is the eight smallest plants,
  with the standard deck's 13 (if dealt) or else the smallest plug card
  left on top. Ecological plants are never removed.
- Original Russia: the six smallest dealt plants open the market, the
  standard deck's 13 goes on top if dealt, and the 7th and 8th smallest
  plants are shuffled into the top five.

The analysis sampler mirrors all three. Maps can give a `shuffled` deck
note, which the viewer shows for the shuffled decks.

Single-deck setups are unchanged for every map, variant, deck, player
count and seed checked.

* Generate the rules tab's deck build from the deck tables

The rules dialog's "Deck build" section is now built from the same tables
the decks are dealt from (deckChanges.ts and each deck's card list), so
it names the right plants for Deck 1, Deck 2 and the shuffled decks
instead of always the Original deck's. Shuffled games list each rule's
plants as Original deck / Deck 1 / Deck 2, with a sentence explaining
that only the dealt plants count. Player-count lists show the game's
own player count.

Each sentence is a template with plant numbers as {pN} values, rendered
in its own span, so the catalogues translate it whole. The 54 new
templates are translated into all 16 languages; the 20 old deck-build
sentences are removed. The maps' hand-written deckBuild notes are gone.

Tests read the plant numbers back out of the generated text and compare
them with real setups for every map, edition, single deck and player
count, and check that every sentence translates in every language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Describe Central Europe's nuclear and Wien rules

Central Europe had no map rules text, though the engine limits nuclear
plants to players with a city in Czechia, Slovakia or Hungary and gives
a Wien network $1 off garbage (never below $1). The rules dialog now
says so, in all 17 languages, using each catalogue's own name for Wien.

The dialog reads a map's rules from the current map definition rather
than the copy saved in the game, so games already under way see rules
text added later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Outline buildable Bremen districts around the diamond

The blue build hint and the gold region-draft ring were fixed 18-unit
circles, which on Bremen's diamond tiles crossed the entry cost and slot
numbers. Bremen's tiles now get a diamond outline just outside their own
region border instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Begin Step 2 first when the Step 3 card comes early

The rulebooks: if the Step 3 card is drawn before Step 2 has begun,
carry out everything that begins Step 2, then prepare Step 3, back to
back. The engine only did this on UK & Ireland, and without Step 2's
own setup, so on Spain & Portugal the held-back plants never came back.

Step 2's setup (the smallest plant leaves, Spain & Portugal puts its
held-back plants on top, a new plant is drawn) is now one function.
Normal Step 2 uses it unchanged, and an early Step 3 card runs it first:
straight away outside the auction, or at the end of the auction phase
with Step 3's own setup, which then shuffles the draw pile again.
Middle East, China and Manhattan keep their own rules.

New games store step2BeforeStep3; games created earlier replay with
their old sequence.

The rules summary now lists what happens when Step 2 and Step 3 start,
and the early-Step-3 order, in all 17 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove a stale Manhattan line brought back by the master merge

Merging the fork's older master into combined-deck-rules restored
`const lastPlug = lastPlugPlant(powerPlantDeck)` in Manhattan's setup.
lastPlugPlant isn't imported there and the value is unused, so the
engine build failed and CI went red on the branch and on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:45:47 -08:00
github-actions
f929ea8dd0 🔖 powergrid-engine 2.0.28 2026-11-11 19:13:03 +00:00
goldjohn6
bbe533ee8d
Show plug cards on the draw pile for every deck (#168)
* Show plug cards on the draw pile for every deck

The draw pile darkens when its top card is a plug card, and the engine
decided that by comparing the plant number with 15. That was right for the
standard deck only. Deck 1 has plug cards up to 16, and the shuffled decks
mix in copies such as 16.1 and 15.2, so in those games a plug card on top
was shown as an ordinary one.

Ask the deck instead, with the isPlugPlant() rule the decks already use.
For the standard deck (and India, and Deck 2) it is the same test as
before, so those games cannot change.

Measured over seeded 3p/5p Recharged games on Italy, USA and Germany:
before, 41/3112 states wrong on Deck 1, 40/3278 on shuffled, 31/3420 on
shuffled-unique, 0/3338 on standard; after, 0 on all four. The new test
fails on the old code ("deck1: 16 on top: expected false to equal true").

Found while answering Frankie_Stein's report on Italy_Rechrg_1103 (a
standard-deck game, so this is not the cause of that report).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix the engine lint error that has kept CI red since 2.0.26

`pnpm lint` fails on master since e954346: prefer-const flags `bidder` and
`plant` in sealed-bid-privacy.spec.ts, destructured with `let` alongside
`state`, which is reassigned. Split the destructuring; the test is unchanged
and still passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:09:28 -08:00
d381197fdc Release engine 2.0.27 and viewer 2.3.28: correct replay deck counts 2026-11-10 23:20:59 +00:00
e954346757 Release engine 2.0.26: redact sealed auction last moves 2026-11-10 18:23:57 +00:00
30dcc16f44 Format verified analysis release receipt 2026-11-10 09:36:38 +00:00
2667beccee Release analysis fixes: engine 2.0.25 and viewer 2.3.27 2026-11-10 09:36:25 +00:00
5fc0e22236 Fix interactive analysis cash and manual-seat policy 2026-11-10 08:25:37 +00:00
github-actions
0f0f3eb24d 🔖 powergrid-viewer 2.3.26 2026-11-08 17:16:42 +00:00
goldjohn6
ed4738e2ea
Show the printed price when you are the only buyer left (#167)
In the shuffled decks a plant's extra copies are numbered 13.1 / 13.2, and
the sole-buyer confirmation used that number as the price, so it asked
"Buy Power Plant 13 (Deck 1) for $13.1?". The engine already charges the
printed number (Math.floor), so only the dialog was wrong. Round it down
the same way; the Recharged $1 discount plant is unchanged.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 09:13:29 -08:00
github-actions
b06e7f3e66 🔖 powergrid-viewer 2.3.25 2026-11-08 16:53:19 +00:00
github-actions
3091336e6e 🔖 powergrid-engine 2.0.24 2026-11-08 16:51:57 +00:00
MikeIsom
fcc0a127d9
Deal a standard-sized deck for "all three decks shuffled" (#166)
Shuffled games put every plant of all three decks in play, leaving about
114 cards in the draw pile, so games rarely reached Step 3. New shuffled
games instead draw 42 plants at random from all three decks, keeping the
standard deck's 13 plug and 29 socket cards plus the Step 3 card; the
usual player-count removals still apply. Duplicates and missing numbers
are possible, unlike the one-per-number deck.

New games store options.shuffledSample. Older shuffled games have none
(reconstructionOptions forces it off), so they keep the full pile and
replay exactly as before.
2026-11-08 08:50:04 -08:00
github-actions
4e22d0f19c 🔖 powergrid-viewer 2.3.24 2026-11-04 22:17:14 +00:00
github-actions
c7f899c62a 🔖 powergrid-engine 2.0.23 2026-11-04 22:14:53 +00:00
goldjohn6
de6f0703fb
End a game nobody can finish, and never sell a 9999 city (#165)
UK & Ireland's island jump needs an empty city, so a player locked on one
island tops out at its cities (14 and 12 on a 4-region board). If nobody
crosses before the other island fills, no one can ever reach the end count
and the game never ended. Two seeded bot games showed how master escaped:
after ~105 rounds a player saved $9999 and bought a city priced 9999, the
engine's "impossible" marker (occupied, or across the sea).

New games store options.stallEnds. For them, the game ends after a Step 3
Building phase in which no active player could ever build again (whatever
their money), scored as usual; and a 9999 price is never affordable.
Older games have no stamp (reconstructionOptions forces it off), so they
play and replay exactly as before.

Build pricing moves out of availableMoves into buildOptions() so the
money-filtered moves and noPlayerCanBuild() share every map rule.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:11:27 -08:00
MikeIsom
57b7e75f95
Update middleeast.ts Rules (#164)
* Update middleeast.ts Rules

* Translate the Middle East garbage rule in every language

The map's rules text is also its translation key, so the new sentence
("During step 1, garbage cannot be bought.") needs the key and each
translation updated, or every non-English player falls back to English.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: John Gold <goldjohn6@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:09:59 -08:00
MikeIsom
75b9d5f69f
Plant Deck Set 1 (#163)
* Count only wind plants as ecological, behind one switch

Benelux's extra market slot and Québec's protected plants now share one
isEcological() helper. Fusion is not ecological unless FUSION_IS_ECOLOGICAL
is flipped. New Benelux and Québec games store the ruling as
options.fusionEcological, so flipping it later only affects new games.

Québec's deck setup used to protect fusion plant 50 while its bureaucracy
and Benelux did not. Games without the stored flag rebuild their Québec
deck the old way via reconstructionOptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add a power plant deck option with Deck 1, Deck 2 and Random

New games choose a deck with options.powerPlantDeck: standard, deck1 (The
New Power Plants / Set 1, without 52-60), deck2 (Set 2) or random, which
resolves from the seed and stores the result. Only a non-standard deck is
stored.

Deck 1 deals from 01-08 with 11 on top in the Original edition and from
the 01-16 plug cards in Recharged. Deck 1 and Deck 2 are offered on maps
whose setup doesn't name standard-deck plant numbers; the rest fall back
to the standard deck until their per-deck changes land. Germany's uranium
phase-out triggers on 38 (Deck 1) or 37 (Deck 2).

The legacy alternatePowerPlants flag keeps its Europe/North America-only
behaviour and storage, so existing games set up identically.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Offer Deck 1 and Deck 2 on every map

Map rules that name plant numbers now look them up per deck in
deckChanges.ts: removed plants, market openers, top-of-deck plants and
Spain & Portugal's Step 2 plants, from the decks' 2024 map-changes sheets.
Map setup and the deck analysis share that table. Original-edition games
use the same numbers, except France with Deck 1, which follows The New
Power Plants rulebook (remove 11).

Australia, India, South Africa, Spain & Portugal and UK & Ireland now use
the shared default setup instead of their own copies. India has a version
of each deck. Italy's uranium phase-out uses Germany's plant per deck.
Northern Europe's regional cards replace the deck's plants by number, and
a regional plant the deck lacks is shuffled into the draw pile. Middle
East closes garbage purchases in Step 1, for Deck 2's garbage/oil hybrids.

Standard-deck setups are unchanged for old and new games. Also stops the
ecological replay test from comparing the transient pendingMessages queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add shuffled power plant decks: all decks, or one per number

powerPlantDeck now also takes 'shuffled' (every plant of the standard deck,
Deck 1 and Deck 2 together) and 'shuffledUnique' (one random copy of each
number, without Deck 1's 52-60). Extra copies are numbered n.1 (Deck 1) and
n.2 (Deck 2), so the market ranks duplicates Deck 2 > Deck 1 > Original and
moves keep identifying plants by number. Cards show the printed number, and
logs read "Power Plant 46 (Deck 2)"; the journal and the deck analysis
parse that label back to the copy.

Bids start at the printed number, the Original discard rule and plug
cards compare it, and each deck's own nuclear plant ends Germany's and
Italy's uranium resupply. The shuffled decks are only offered on maps
whose rules don't name plant numbers; Random still picks a single deck.

Standard-deck setups are unchanged for old and new games.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:41:57 -08:00
ddfae0915f Release viewer 2.3.23 with text actions and consistent board controls 2026-11-02 21:04:17 +00:00
8e3e41587b Release viewer 2.3.22 with remaining-card count on the draw pile 2026-11-02 20:32:15 +00:00
776aad8d22 Release viewer 2.3.21: phase-aware skip controls and consistent icon hover 2026-11-01 21:49:04 +01:00
06bb0aebf6 Release viewer 2.3.20: consistent action controls and stable resource previews 2026-11-01 21:28:18 +01:00
fcf31f459e Release viewer 2.3.19 with phase/action pictograms and simpler preferences 2026-11-01 18:52:11 +01:00
github-actions
087d514be4 🔖 powergrid-viewer 2.3.18 2026-11-01 16:26:51 +00:00
github-actions
e39daffab6 🔖 powergrid-engine 2.0.22 2026-11-01 16:24:40 +00:00
goldjohn6
3c6719acaa
Wien garbage never free in Central Europe; UK & Ireland "completely vacant city" wording (#162)
* Never let the Wien discount make garbage free in Central Europe

Both Central Europe rulebooks (Original 2006/2011 and Recharged) give a
player connected to Wien garbage at $1 off "with the stipulation that his
cost per piece may not be 0": from the first space he pays $1. The engine
and the market box subtracted $1 with no floor, so a full market sold
garbage for $0. Engine, available moves and the box now share one price.

Six ended games on the server did buy garbage for $0. A game whose log
already shows such a buy is rebuilt with the old discount
(reconstructionOptions), so history and analysis replay them as played;
no live game has one, so they all get the floor from their next buy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Say UK & Ireland island jumps need a completely vacant city

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Reword the UK & Ireland jump rule in every language

"An EMPTY spot" read like a free slot in an occupied city; the engine only
allows a jump to a city with no houses at all. Re-keys the 17 catalogues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:20:20 -08:00
github-actions
bf4433dd84 🔖 powergrid-viewer 2.3.17 2026-10-31 16:46:35 +00:00
github-actions
596f929469 🔖 powergrid-engine 2.0.21 2026-10-31 16:44:59 +00:00
goldjohn6
aa29b7cf7c
Recharged starting garbage for Brazil and France. (#161)
* Start France and Brazil Recharged with garbage on spaces 6-8

Both Recharged rulebooks fill garbage (biogas in Brazil) on spaces 6-8, i.e.
9 tokens, but the maps' single startingResources array held the Original
count of 6 for both variants. startingResources can now name each variant.

Games created before this keep their original market when rebuilt: setup
records rechargedStartingResources for new games, and replay/reconstructState
treat a missing flag as the old behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Format PlayerBoard.vue with Prettier

Whitespace only; master's prettier check has failed on this file since 3adad0c.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 09:39:44 -07:00
github-actions
d3ecf28424 🔖 powergrid-engine 2.0.20 2026-10-31 16:38:57 +00:00
3adad0cc0d Release auction auto-pass with a personal player-card setting 2026-10-26 20:42:38 +01:00
22d4a0b80c Release viewer 2.3.14 with stable board layout and readable player column 2026-10-25 14:09:57 +01:00
295d50da8b Add optional Recharged plant discount cutoff at Step 3 2026-10-24 21:51:58 +02:00
ee31b0be68 Show regional power plants correctly in the journal 2026-10-24 21:46:17 +02:00
537e41e318 Add hand-authored Simplified Chinese game localization 2026-10-20 14:12:18 +02:00
github-actions
4873f48657 🔖 powergrid-viewer 2.3.11 2026-10-19 19:40:20 +00:00
github-actions
7ff589d3b3 🔖 powergrid-engine 2.0.17 2026-10-19 19:38:25 +00:00
goldjohn6
3f9295292a
Make Bremen easier to read: larger district tiles and a tighter board (#160)
Amy (70s eyes) found Bremen's district text hard to read.

- Viewer: every part of a node-weighted district tile scales by one factor
  (TILE_SCALE = 1.3): the diamond, house slots, slot numbers, entry-cost coin
  and the houses placed in them, so the pieces keep their relative places.
- Engine: Blumenthal, Vegesack and Burglesum move down and right (placed with
  the coord picker), which narrows the board so the adaptive layout zooms it
  in. Hofen moves down 20 so the Burglesum-Seehausen link no longer clips it.
  Adjacency and rules are unchanged; only x/y move.
- Geography: Bremen's outline is regenerated from the updated anchors, so the
  land follows the new positions. Other maps' assets are untouched.

New district positions reach new games only (map data is stored at setup);
the larger tiles reach every game on reload.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:32:33 -07:00
a28bf041c0 Refresh custom player colours when live preferences change 2026-10-17 22:52:37 +02:00
464b8e5d88 Use custom BGS colours without replacing other players' colour choices 2026-10-17 22:49:03 +02:00
287343f11c Release viewer 2.3.8 preserving custom BGS colours after colour selection 2026-10-17 22:35:40 +02:00
github-actions
ef972c74fc 🔖 powergrid-viewer 2.3.7 2026-10-12 03:02:02 +00:00
github-actions
42861a256e 🔖 powergrid-engine 2.0.15 2026-10-12 02:59:39 +00:00
mmunson99
c50b5951a1
Add an alternate power plant deck option for Europe and North America (#159)
* Add an alternate power plant deck option for Europe and North America

New game option `alternatePowerPlants`. On the Europe and North America maps it
replaces the standard deck with the alternate deck: same card numbers, new
fuels and outputs. The option is ignored on every other map.

The deck adds a garbage/oil hybrid plant type (plants 8, 22 and 35). It burns
any mix of garbage and oil and has one shared storage tank, like the coal/oil
hybrid. Buying, storage, discarding, powering and end-game scoring all handle
the shared tank. Players without that plant keep the existing coal/oil logic
unchanged, and games without the option keep their exact state shape.

* Draw alternate-deck plants in the journal from the alternate deck

The journal drew every plant through getPowerPlant(number, mapName), which
only knew the India and standard catalogues. In an alternate-deck game the
journal showed the standard card for each number: 22 appeared as a wind 2,
27 as a wind 3 and 33 as a wind 4.

getPowerPlant now looks plants up through plantCatalogue, so it takes an
alternatePowerPlants flag. The journal passes the game's option through.
Every other caller passes no flag and gets the same card as before.

Found in a hand playtest of this PR on Europe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: John Gold <goldjohn6@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:55:02 -07:00
aac09f231d Release viewer 2.3.6 with mobile resource buying and refill previews 2026-10-10 10:26:33 +02:00
e90041904b Offer "Undo my move" in games against bots
BGS lets the only human of a game against bots take back their last saved
move (protocol 0.10.0 `undo:available` / `undo`). The board's Undo button
offers it once the turn in progress has nothing left to undo locally, and
never during replays, analyses or round planning, for spectators, or while a
move is on its way. A double click on Undo cannot reach it.

BGS then sends the earlier state. A committed state that takes back the
player's own moves drops the turn buffer, a bid being edited, open dialogs,
a hybrid plant's fuel choice and the bid dialled into the calculator.

The label is translated in all 16 languages. Unit tests and the protocol
browser smoke cover the control, and the development sandbox mimics BGS's
undo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:41:51 +02:00
6555a17222 Repair the viewer build and formatting checks
The viewer lockfile still pinned @babel/preset-env 7.14, which rejects the
plugin names babel.config.js has listed since 126de02: a clean install could
not build the viewer, and Viewer - Test has failed since then. Lock the
versions the viewer on BGS was built with instead. With them, ca9882a rebuilds
the published viewer (game version 13) byte for byte. The lockfile keeps its
lockfileVersion 5.4 Prettier layout.

Also sorts the imports of two unit tests, as the Prettier check requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:15:45 +02:00
873d5e0cab Add a Random map option that picks a map at setup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 22:56:43 +02:00
ca9882a5c9 Show building capacity only on the viewing player turn 2026-10-06 16:20:47 +02:00
3e7abbbebc Show plant power capacity on the city track during building 2026-10-06 16:14:48 +02:00
55581e0f6d Use consistent outlined ownership symbols for all house markers 2026-10-05 18:36:07 +02:00
48ae6ee863 Enlarge and center map ownership symbols with white outlines 2026-10-05 18:31:44 +02:00
b597ae7b33 Keep desktop cities readable by allowing taller boards 2026-10-05 16:40:33 +02:00
126de02ea2 Reuse auction controls for pending bids and distinguish phase actions 2026-10-05 16:18:56 +02:00
26c4e5c245 fix: replace pending powering choices without growing history 2026-10-05 02:10:09 +02:00
9dbb0df766 feat: allow revising sealed bids and powered plants 2026-10-05 01:36:01 +02:00
8bdce611bb chore: align formatting checks with generated geography data 2026-10-05 01:35:46 +02:00
62afa6c272 Release viewer 2.3.2 2026-10-04 23:25:51 +02:00
1784b25243 Compact board controls when city markers are too small 2026-10-04 23:24:38 +02:00
712883af4b Release viewer 2.3.1 2026-10-04 23:10:36 +02:00
96c10c8826 Expand maps into unused space beside board labels 2026-10-04 23:09:42 +02:00
1c1ab91e43 Release viewer 2.3.0 with adaptive layout and faded map regions 2026-10-04 21:43:07 +02:00
68f3f106ee Clip geographic backgrounds to fitted board bounds in viewer 2.2.1 2026-10-04 20:48:58 +02:00
ec0f68d4f2 Document the geographic background release 2026-10-04 20:45:25 +02:00
a1496b05ee Release Power Grid viewer 2.2.0 with geographic backgrounds 2026-10-04 20:44:46 +02:00
bc642716de Restore Australia's resource slot grid and centre market tokens 2026-10-04 20:40:44 +02:00
8ffae33978 Reuse the uranium token for Australia's mine market and card badges 2026-10-04 20:36:57 +02:00
ad585972a7 Show Australia's uranium removal beside resource refill badges 2026-10-04 20:33:22 +02:00
d53bba2858 Extend geographic backgrounds across the full board and clear Australia's income track 2026-10-04 20:24:47 +02:00
80435911ea Add fitted geographic backgrounds for all Power Grid maps 2026-10-04 19:54:45 +02:00
38cb279038 Prototype geographic backdrops for Germany and UK Ireland 2026-10-04 19:15:02 +02:00
0a86852f05 Save AI research handoff and completed diagnostic audit 2026-10-04 19:02:47 +02:00
face347f25 Use red outlines for power plant discard choices 2026-10-04 18:48:53 +02:00
1e73e53664 Integrate AI research and harden analysis autoplay 2026-10-04 11:38:12 +02:00
7b1ea78987 Add automatic powering with activation UI and replay support 2026-10-04 11:12:43 +02:00
46cca521b0 Use shared BGS preferred colourblind player symbols 2026-10-02 11:07:51 +02:00
9ce6a154aa Announce Power Grid step changes in chat and journal 2026-10-02 02:32:06 +02:00
dba2aaff5e Place Supporter badge beside the player name 2026-10-02 01:38:40 +02:00
2e778ca976 Show platform Supporter badges and preferred player colours 2026-10-01 23:56:32 +02:00
f2c1c6887b fix: don't count Australia's uranium mines in the resources pass warning
canPowerAllPlants() summed the fuel cost of every plant in hand, including
Australia's uranium plants (11/23/28/34/39), which are mines that never
power cities — and uranium cannot even be bought in the main market there.
That made the 'skip buying resources without enough to power all your
plants?' confirmation fire every Resources phase, no matter what.

Skip mines via the engine's isUraniumMine() helper, mirroring how the
bureaucracy move list and the hand-limit count already treat them.
2026-10-01 20:20:03 +02:00
4bc256a8b1 Launch paired continuation-policy and larger-budget teacher audit 2026-10-01 10:47:00 +02:00
1835c4ccd3 Measure teacher target instability across independent search batches 2026-10-01 10:44:05 +02:00
0809d7022f Capture paired search outcomes and launch teacher reliability audit 2026-10-01 10:41:45 +02:00
882be043f9 Complete primary league-admission comparison and record failed strength gates 2026-10-01 10:37:38 +02:00
c2f64b2152 Validate completed league pilot checkpoints and launch primary paired screens 2026-10-01 10:33:45 +02:00
c155d15863 Complete geographic final-checkpoint evaluation and reject qualification 2026-10-01 10:12:53 +02:00
75657b5253 Record first geographic final-checkpoint screens and two-player failure 2026-10-01 10:09:29 +02:00
06774fe7df Record completed geographic training and launch final checkpoint research screens 2026-10-01 10:08:29 +02:00
53cedd10ee Compare complete update9 league arms on paired held-out games 2026-10-01 09:05:34 +02:00
0ab6cefe8c Launch scheduled periodic league update9 screening 2026-10-01 09:00:11 +02:00
5b77919991 Record complete geographic update69 screens and qualification failures 2026-10-01 08:35:44 +02:00
f812d5aa56 Screen geographic update69 with strict export parity and cap audit 2026-10-01 08:32:18 +02:00
944e3a45d2 Verify periodic snapshot opponents in live HF training 2026-10-01 08:22:45 +02:00
b8ec00a3c4 Prepare immutable league checkpoints and paired screening plans 2026-10-01 07:42:47 +02:00
50c7f3f293 Verify first complete HF updates for league comparison 2026-10-01 07:39:55 +02:00
c904152f15 Fix paired evaluation protocol for league admission pilot 2026-10-01 07:35:27 +02:00
be7d4015b8 Launch matched league admission pilot on HF Jobs 2026-10-01 07:34:03 +02:00
dabc9e2703 Decouple optional league admission from heuristic checkpoint selection 2026-10-01 07:26:20 +02:00
d41cf40614 Complete final H200 screening and reject universal qualification 2026-10-01 07:24:24 +02:00
70d0bcc446 Record successful completion of H200 training horizon 2026-10-01 07:22:27 +02:00
8dc608a2b1 Validate final H200 update79 export and launch strength screening 2026-10-01 07:20:47 +02:00
5015675a97 Complete geographic update59 screening and document regressions 2026-10-01 07:06:00 +02:00
16b75dea2e Record first geographic update59 screening results 2026-10-01 07:04:11 +02:00
f9b0e2b9f5 Pin geographic update59 and launch cross-count research screens 2026-10-01 07:02:28 +02:00
2c953b5b1d Benchmark precise export on AMD8840U with matched inference fixtures 2026-10-01 06:16:38 +02:00
83ec009ed8 Verify higher-precision export resolves update69 numeric mismatch 2026-10-01 06:14:41 +02:00
9104e9ddbe Complete update69 screening and retain qualification failures 2026-10-01 06:02:08 +02:00
dae1f15078 Record four completed update69 economic screens 2026-10-01 06:00:01 +02:00
8f1ffe0a4a Pin H200 update69 export diagnosis and launch research screening 2026-10-01 05:58:11 +02:00
89ec44100f Complete paired six-player search comparison and record supported PPO gain 2026-10-01 05:51:06 +02:00
580f93ab74 Record three validated six-player search extension shards 2026-10-01 05:46:30 +02:00
f96638530a Complete geographic update49 research screening without promotion 2026-10-01 05:31:16 +02:00
1c7502d884 Diagnose geographic update49 export and launch research-only screens 2026-10-01 05:26:46 +02:00
ef26735555 Complete update59 screening and retain existing stronger-opponent candidates 2026-10-01 04:47:34 +02:00
b48f3461de Validate update59 export and launch paired multiplayer strength screens 2026-10-01 04:43:54 +02:00
73c26307e4 Verify extended comparison jobs and record observed scheduling states 2026-10-01 04:40:44 +02:00
67307f3b0e Record update49 search result and extend paired six-player comparison 2026-10-01 04:39:17 +02:00
8cbe344bf9 Reject cheaper-plant shortcut after complete sealed nomination comparison 2026-10-01 04:21:00 +02:00
cc25990ae5 Verify affordable uranium omission in sealed counterfactual endgame 2026-10-01 04:17:16 +02:00
05840e34cf Record worse outcome after legal auction pass on second sealed deal 2026-10-01 04:15:21 +02:00
5d2a6cc772 Identify forced building pass and legal auction alternatives in second replay 2026-10-01 04:12:36 +02:00
216ee4894b Record exact sealed auction replay on a second independent deal 2026-10-01 04:11:07 +02:00
420c316d63 Audit auction-mode performance and training gains across player counts 2026-10-01 04:05:02 +02:00
3e4c264d98 Complete geographic update39 screening without candidate promotion 2026-10-01 03:56:33 +02:00
247174b64d Complete 1280-game strong-opponent transfer audit across player counts 2026-10-01 03:50:29 +02:00
e978b0ba80 Collect first geographic update39 research screens 2026-10-01 03:49:26 +02:00
7e9c8dd6a6 Screen geographic checkpoint39 and record six-player rule imbalance 2026-10-01 03:48:21 +02:00
ef790594e1 Test legal lower sealed bid in exact replay without claiming strength 2026-10-01 03:40:47 +02:00
89e0bf5755 Capture exact original-sealed replay for spending and growth diagnosis 2026-10-01 03:36:33 +02:00
e4d0295a32 Diagnose city and capacity deficits in sealed-auction losses 2026-10-01 03:31:58 +02:00
7a4504ff06 Complete H200 update49 screening and test six-player gain against search 2026-10-01 03:30:32 +02:00
1cc4937c7b Collect first three H200 update49 paired screens 2026-10-01 03:28:11 +02:00
b3290f9718 Validate H200 update49 export and dispatch paired screening 2026-10-01 03:26:34 +02:00
4456df54b8 Resolve five-player paired gains and isolate original sealed gap 2026-10-01 03:24:51 +02:00
ee9d5bc3cc Identify sealed-auction weakness hidden by five-player aggregate gain 2026-10-01 03:23:44 +02:00
f575135dba Record supported four-player PPO transfer gain without qualification 2026-10-01 03:05:20 +02:00
5d1c2f4a28 Record four-player strong-opponent screening result 2026-10-01 03:03:23 +02:00
5fdc669394 Measure three-player PPO transfer gain and remaining strength gap 2026-10-01 02:50:52 +02:00
d04b770a11 Record paired two-player transfer result against strong search 2026-10-01 02:47:12 +02:00
3b3b7900d1 Record clean two-player search-baseline failure of retained PPO model 2026-10-01 02:46:22 +02:00
c7a9491f25 Screen raw PPO transfer against geographic search across player counts 2026-10-01 02:41:55 +02:00
c10a327e97 Audit sparse league snapshot selection against independent screens 2026-10-01 02:38:43 +02:00
b2697f884c Complete H200 update39 screen and retain earlier candidates 2026-10-01 02:21:34 +02:00
3167294603 Launch independent screen for verified H200 update39 checkpoint 2026-10-01 02:18:09 +02:00
8b052f9c56 Complete geoleague update29 screen without promotion 2026-10-01 02:16:44 +02:00
663a9075f8 Screen strictly verified geoleague update29 checkpoint 2026-10-01 02:12:12 +02:00
7ee9c29f6d Audit held-out replay policy changes before choosing further training 2026-10-01 01:58:09 +02:00
907ced895e Reject regressed replay candidate and audit stronger teacher label ambiguity 2026-10-01 01:55:47 +02:00
e2d6d49ed1 Record replay epoch10 two-player regression and three-player comparison 2026-10-01 01:53:10 +02:00
33ff9c5732 Record completed replay training and final export diagnostics 2026-10-01 01:52:13 +02:00
c81fa1f931 Diagnose epoch5 rounding and screen strictly verified replay epoch10 2026-10-01 01:50:42 +02:00
b10fda5e2b Diagnose replay epoch5 numeric export discrepancy across all fixtures 2026-10-01 01:48:48 +02:00
2cbc77fa3d Validate replay training pilot and launch full fifteen-epoch HF run 2026-10-01 01:41:12 +02:00
2789dfc971 Audit all repaired teacher data and launch HF replay distillation pilot 2026-10-01 01:34:46 +02:00
9836ed887c Complete H200 update29 screening with supported five- and six-player gains 2026-10-01 01:26:30 +02:00
4ebefda6a2 Record H200 update29 three-player paired economic screen 2026-10-01 01:25:51 +02:00
b7f4c6ac12 Record H200 update29 two-player paired screen 2026-10-01 01:24:08 +02:00
474cbd0997 Launch capped teacher-game repair and verified H200 update29 screening 2026-10-01 01:21:49 +02:00
5b7fc22e9c Complete corrected six-player strong search screen with rule-specific limitations 2026-10-01 00:51:05 +02:00
534777795e Record sixth clean corrected six-player evaluation shard 2026-10-01 00:49:42 +02:00
b8eef051fd Record fifth clean corrected six-player evaluation shard 2026-10-01 00:49:24 +02:00
1f992aff86 Verify four corrected six-player shards and paired horizon outcomes 2026-10-01 00:47:44 +02:00
b7346c47c0 Audit complete five-player stronger-opponent teacher data 2026-10-01 00:46:43 +02:00
4de5289f1d Record geoleague update19 paired strength results and first corrected six-player shard 2026-10-01 00:45:28 +02:00
2ea1e8cb59 Screen geoleague update19 after full export parity verification 2026-10-01 00:41:17 +02:00
9699df3944 Audit complete four-player stronger-opponent teacher data 2026-10-01 00:17:26 +02:00
d0fa8f0181 Prepare selective regeneration of teacher games with capped rollouts 2026-10-01 00:01:59 +02:00
4239d08f17 Record significant stronger-opponent gain and two-player regression at update19 2026-09-30 23:57:10 +02:00
ad35564cf0 Verify twenty-batch H200 export and launch paired held-out comparisons 2026-09-30 23:52:58 +02:00
a9b47204ce Separate diagnostic job provenance from corrected runtime provenance 2026-09-30 23:51:11 +02:00
bd895ef006 Extend search horizon with captured regression and launch six-player screen 2026-09-30 23:50:59 +02:00
c067f25204 Audit completed two-player stronger-opponent teacher shard 2026-09-30 23:43:35 +02:00
f3b60714b6 Complete forty-deal five-player search screening with rule-level intervals 2026-09-30 23:41:28 +02:00
9d1ebc5305 Collect three further five-player search evaluation shards 2026-09-30 23:39:35 +02:00
13eccc74bd Collect two more expanded five-player search shards 2026-09-30 23:38:01 +02:00
dc5948c0dd Collect first completed expanded five-player search shard 2026-09-30 23:37:24 +02:00
bd4a7179ad Audit completed three-player stronger-opponent teacher shard 2026-09-30 23:35:19 +02:00
b7fb490f8f Replay capped six-player search with isolated longer-horizon diagnostic 2026-09-30 23:34:03 +02:00
e3178fca2f Record full six-player screen and flag one truncated search rollout 2026-09-30 23:31:24 +02:00
fdba04dcb3 Record first completed six-player strong search shard 2026-09-30 23:28:12 +02:00
5a35c87ca5 Diagnose terminal capacity and expansion gaps against frozen neural bot 2026-09-30 23:12:08 +02:00
12042f9a38 Record paired stronger-league checkpoint screening across player counts 2026-09-30 23:11:01 +02:00
93152e5676 Verify first stronger-league checkpoint and launch paired screening 2026-09-30 23:06:59 +02:00
188e91fdf5 Expand five-player strong search screening to forty deals 2026-09-30 23:00:09 +02:00
f0870163ad Record five-player search screen and prepare audited replay job 2026-09-30 22:58:30 +02:00
ec556f375c Prepare verified warm-start distillation with balanced teacher replay 2026-09-30 22:51:09 +02:00
e9fa0e00e4 Audit strong-opponent teacher pilot and scale balanced data generation 2026-09-30 22:48:01 +02:00
d399128f5a Pilot stronger teacher data from games against geographic-search opponents 2026-09-30 22:41:10 +02:00
51131ef9cf Complete forty-deal three-player geographic-search evaluation 2026-09-30 22:32:31 +02:00
16ef52e8a1 Complete larger frozen-opponent and four-player search screening analyses 2026-09-30 22:31:31 +02:00
67ef3bdf38 Confirm standalone neural gains at two and six players with paired tests 2026-09-30 22:30:14 +02:00
297add08d2 Record completed expanded frozen-opponent evaluation shard 2026-09-30 22:28:04 +02:00
59c2cf1647 Verify ten-update neural checkpoint and launch paired standalone screening 2026-09-30 22:26:21 +02:00
a1cd6b4175 Record first four-player geographic-search screening shard 2026-09-30 22:23:15 +02:00
1f94fdc78b Measure small neural search-proposal contribution in paired ablation 2026-09-30 22:21:23 +02:00
46d294f8ed Use verified asynchronous multiplayer arenas and isolate final settings 2026-09-30 22:13:39 +02:00
5c43f8d728 Verify exact HF asynchronous arena equivalence and measured speedup 2026-09-30 22:12:28 +02:00
bed83210cb Pilot asynchronous independent arenas with exact outcome equivalence checks 2026-09-30 22:03:55 +02:00
823437e55a Expand promising three-player search-assisted screening to forty deals 2026-09-30 22:00:11 +02:00
9fb82dfeb6 Record combined three-player frozen-opponent screening with uncertainty 2026-09-30 21:55:44 +02:00
bc04fe0d31 Combine two-player strong-opponent probe without claiming superiority 2026-09-30 21:54:37 +02:00
d39c420201 Record first independent two-player geographic-search screening shard 2026-09-30 21:52:57 +02:00
aa1d6c6d37 Verify first complete asynchronous geographic league training update 2026-09-30 21:43:41 +02:00
d710b80923 Record completed synchronous 240-worker timing comparison 2026-09-30 21:39:32 +02:00
e1a633ca53 Screen search-assisted model against strong bots across all player counts 2026-09-30 21:38:18 +02:00
7d70626ede Retire slower synchronous refinement after asynchronous validation 2026-09-30 21:37:10 +02:00
b5274d00d7 Measure neural proposal contribution separately from rollout search 2026-09-30 21:36:44 +02:00
d41b815ff1 Verify asynchronous pilot and launch stronger league and search tests 2026-09-30 21:33:18 +02:00
9bf47b1ccb Guard complete rollout batches before optimization 2026-09-30 21:26:42 +02:00
24f6c6f101 Distinguish ready and in-flight games in asynchronous telemetry 2026-09-30 21:23:44 +02:00
435bcbaf77 Record first balanced H200 refinement update and rollout bottleneck 2026-09-30 21:23:01 +02:00
f45fa12487 Pilot asynchronous frozen-policy game collection on HF 2026-09-30 21:20:03 +02:00
7a859fde6a Test per-game engine processes to reduce search-worker imbalance 2026-09-30 21:12:36 +02:00
816bca0542 Validate completed CPU pilot timing, balanced episodes and trained export 2026-09-30 21:10:47 +02:00
5484552d2d Launch balanced CPU refinement against stronger geographic-search league 2026-09-30 21:02:34 +02:00
579bd90de8 Expose rollout progress and separate engine from policy timing 2026-09-30 20:58:32 +02:00
b2cb7ed6f5 Record failed six-player search-opponent probe for early baseline 2026-09-30 20:55:17 +02:00
a12deca177 Run HF CPU-training pilot to measure a fallback for GPU queues 2026-09-30 20:53:01 +02:00
8d92a5ce91 Hoist rollout resource lookups with verified semantic equivalence 2026-09-30 20:50:42 +02:00
d177f44469 Verify rollout speedup on 8840U and pin optimized source for future jobs 2026-09-30 20:47:23 +02:00
d989a9f742 Avoid unused replacement fuel calculations during rollout planning 2026-09-30 20:45:34 +02:00
a4999e1e1a Move queued refinement to H200 with more rollout workers 2026-09-30 20:41:06 +02:00
9889fd8e2b Complete soft-target screening across all player counts 2026-09-30 20:40:30 +02:00
b29f60953d Record soft-target screening and paired comparison with hard supervision 2026-09-30 20:38:48 +02:00
b6d7e96dc1 Screen completed soft-target model and measure search latency on 8840U 2026-09-30 20:36:16 +02:00
1b87302d63 Launch paired search recovery experiment and track active soft-target training 2026-09-30 20:30:43 +02:00
9162188e2f Quantify paired multiplayer gains and unresolved two-player weakness 2026-09-30 20:26:38 +02:00
2787ffb065 Record multiplayer screening and launch balanced terminal-reward refinement 2026-09-30 20:25:49 +02:00
9ab5fd70e7 Audit ambiguous teacher labels and broaden independent ordered-model screening 2026-09-30 20:23:35 +02:00
fe89ded8b8 Benchmark trained ordered model on 8840U and retain best teacher epoch 2026-09-30 20:21:11 +02:00
5614ffe55c Screen ordered teacher model on independent two-player and frozen-policy arenas 2026-09-30 20:19:20 +02:00
a4f3d54b84 Prepare balanced multiplayer refinement from screened teacher checkpoint 2026-09-30 20:17:03 +02:00
42ed8416f1 Record restored HF access and completed multiplayer baseline 2026-09-30 20:15:40 +02:00
41843e5652 Launch ordered-opponent teacher distillation on separate GPU pools 2026-09-30 20:09:34 +02:00
f2a258e863 Preserve opponent identity in multiplayer policy context 2026-09-30 20:07:58 +02:00
4e486495b3 Record two-player screening weakness before teacher refinement 2026-09-30 20:00:01 +02:00
7559d3ef00 Freeze multiplayer update-5 checkpoint and launch independent screening 2026-09-30 19:59:34 +02:00
61db004862 Validate complete teacher data and launch multiplayer distillation comparison 2026-09-30 19:56:14 +02:00
3b9de204fd Support balanced mixed-count PPO updates with full seat coverage 2026-09-30 19:31:04 +02:00
04332cad8d Audit multiplayer teacher data and generalize held-out final validation 2026-09-30 19:27:06 +02:00
e43194c281 Prepare multiplayer distillation and record 8840U prototype verification 2026-09-30 19:21:06 +02:00
4110d727eb Extend multiplayer evaluation, distillation and CPU serving with independent gates 2026-09-30 19:18:29 +02:00
f318df73ef Record multiplayer teacher jobs and completed specialist baselines 2026-09-30 19:10:28 +02:00
df6ae86a95 Launch multiplayer training validation and extend search teacher data 2026-09-30 19:09:19 +02:00
6967682bdd Generalize league rollouts and PPO targets to 2–6 players 2026-09-30 19:06:59 +02:00
8bab029c23 Add versioned 2–6 player observations and masked multiplayer policy 2026-09-30 19:03:56 +02:00
1bf68a1c4c Freeze reproducible worker entrypoint and final arena source 2026-09-30 18:55:33 +02:00
8b8f1ab9a3 Expose completed-game progress during long CPU arenas 2026-09-30 18:45:36 +02:00
06e7cad8eb Audit raw held-out matches and CPU evidence against fixed gates 2026-09-30 18:44:02 +02:00
e870986671 Retry failed setup and pin CPU arena dependencies 2026-09-30 18:40:43 +02:00
f2ea96eb60 Prepare immutable held-out evaluation dispatch plan 2026-09-30 18:38:51 +02:00
41ca348b57 Record uncommitted source state in runtime provenance 2026-09-30 18:35:54 +02:00
aa8ab7cd6c Compose public-rule specialists and scope search to sealed Recharged 2026-09-30 18:35:24 +02:00
139b4c3081 Fix final validation protocol and report rollout completeness 2026-09-30 18:19:20 +02:00
74aef1f93d Package isolated CPU runtime and record deep search gains 2026-09-30 17:59:22 +02:00
8ab39d131b Record final A checkpoint screening and fixed comparison cohort 2026-09-30 17:53:37 +02:00
8b982867a4 Record stronger-opponent evidence and phase-specific latency reporting 2026-09-30 17:50:11 +02:00
7d5be47d2b Validate stronger A260 checkpoint and refine corrected inputs 2026-09-30 17:37:48 +02:00
8d991f9c85 Record paired screening jobs for new checkpoints 2026-09-30 17:33:29 +02:00
586021568a Version strategic observations and expand search evaluation 2026-09-30 17:30:34 +02:00
822e1307d6 Add search supervision, paired arenas and CPU-guided inference 2026-09-30 16:31:52 +02:00
1c7645b594 Fix fuel teacher and launch economic-policy league training 2026-09-30 16:00:54 +02:00
e8c83925fb Pin the verified CPU serving runtimes 2026-09-30 15:28:48 +02:00
d6e6085835 Add experimental Germany AI training and CPU worker 2026-09-30 15:27:44 +02:00
4e49df1e89 Merge commit '76988deb8a' into feat/ongoing-analysis-scenarios 2026-09-30 14:26:32 +02:00
365fc51990 fix: hand floating chat reminders over to the BGS rail 2026-09-30 14:25:52 +02:00
ddd4d06848 Document complete viewer uploads 2026-09-30 00:27:36 +02:00
31fafa1aea Load selected language separately and reduce viewer bundle size 2026-09-29 23:56:42 +02:00
76988deb8a docs: add Boardgamers play link 2026-09-28 22:47:29 +02:00
d441d1f83f fix: use protocol 0.6.2 and remove chat scroll backports 2026-09-28 19:51:14 +02:00
14de23dd28 Release engine 2.0.10 with safe analysis scenarios 2026-09-27 19:32:03 +02:00
657e5ece7b Defer regional plant substitutions until the region draft completes 2026-09-27 19:22:49 +02:00
247dee9a67 Add ongoing analysis with independently reconstructed hidden futures 2026-09-27 19:22:01 +02:00
ba031305f8 Fix slow scrolling in chat and journal, including active legacy games 2026-09-27 10:05:43 +02:00
b6d2823130 Improve board controls and resource resupply indicators 2026-09-27 09:20:42 +02:00
bc66da8ab1 Add Persian viewer and tutorial translations 2026-09-27 00:52:39 +02:00
8d582bddfe Keep color-blind region borders behind board pieces and connections 2026-09-26 16:03:53 +02:00
bde47fa076 Distinguish color-blind regions with patterned city borders 2026-09-26 15:48:04 +02:00
9c3d99b680 Add shared color-blind mode with player and region markers 2026-09-26 15:16:35 +02:00
421546a136 fix(viewer): prevent translated button overlap and restore unread chat 2026-09-26 12:00:53 +02:00
5d1ca5878d Review viewer translations and translate complete game messages 2026-09-25 22:07:20 +02:00
25834723ee feat(viewer): localize interface and tutorials in 15 languages 2026-09-25 16:30:05 +02:00
09de708a47 feat(viewer): add player hover cards and board thumbnails 2026-09-24 11:44:12 +02:00
da6ce4cd6d feat(viewer): support editing chat messages 2026-09-21 22:40:10 +02:00
5921c3c1d0 fix(viewer): make chat translation controls compact 2026-09-21 21:53:12 +02:00
4bf7a2aa90 Support manual analyses and translated chat 2026-09-21 20:32:10 +02:00
github-actions
7fd6a0911c 🔖 powergrid-viewer 2.1.8 2026-09-20 13:43:27 +00:00
d24263501d Remove queued move notices from the viewer 2026-09-20 15:40:16 +02:00
990580a820 Hide successful premove notices in the viewer 2026-09-20 15:37:58 +02:00
github-actions
b114df84a9 🔖 powergrid-viewer 2.1.7 2026-09-18 17:45:55 +00:00
github-actions
9bbbb6bcfb 🔖 powergrid-engine 2.0.8 2026-09-18 17:43:46 +00:00
Eliott C.
f9c4d7dc05
Add current-round planning and city/powering premoves (#156)
* Add current-round planning and city/powering premoves

* Hide empty premove containers after cancellation

* Simplify premove review and cancellation and fix clean-checkout checks

* Run premove browser checks in CI and serve the preview favicon

* Validate premoves directly and reopen them through Plan

* Show saved premoves in Plan button and use board Undo

* Remove redundant preview label from planning controls

* Rename queue cancellation to Cancel premoves

* Use board Done control to skip simulated plant purchases

* Remove root docs and repository screenshots
2026-09-18 10:35:54 -07:00
github-actions
2c7ae95085 🔖 powergrid-engine 2.0.7 2026-09-16 17:19:00 +00:00
github-actions
9fc81fd0bf 🔖 powergrid-viewer 2.1.6 2026-09-16 17:14:57 +00:00
Eliott C.
5f2406ebb9
Add playable Powergrid tutorials and city income reference (#155)
* Add playable Powergrid tutorials and city income reference

* Space houses that share a city count so each one stays readable

The income row shortened the city-count cells, and the house markers were
packed to fit: 6px between columns against a 12px-wide house, and 3px
between rows. Two players on the same number — the ordinary case for most
of a game — overlapped by half and read as a single smudge; five or six at
the start of a game read as one blob.

Lay them out bottom-aligned in the cell instead, growing upward from the
income strip so the number above stays legible, a house-width between
columns and a house-height between rows. Five or six sharing go three wide
rather than three tall: a third row starts at the top of the cell and hides
the number completely, which is every game's opening position.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Lift dialogs above the status bar and complete the payment table

The status bar is sticky at z-index 10 and every modal sat at z-index 1, so
the bar painted over the top of any open dialog. Modals open 10vh down and
the bar is a fixed 40px, so on a short viewport — a phone held sideways —
the bar landed across the dialog's own header and covered the close button,
leaving no way out of the dialog at all. Put the modal above it; the bar is
then dimmed behind the overlay like the rest of the page.

The payment table counted to citiesToEndGame, which stopped one column short
of the number that ends the game, and a player can finish holding more cities
than that by building in the same phase as whoever triggered the end. Render
the whole table instead, so it agrees with the city track on the board.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: John Gold <goldjohn6@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 10:10:47 -07:00
mmunson99
93d1490a4f
Fix per-player timer inflating from client clock skew (#154)
The per-player game clock could show one player using nearly the whole
game's elapsed time. Root cause: `move.time` was the acting client's
Date.now(), and `updateClocks` banks a stretch by subtracting one
player's stamp from another's (`ts - clockStartedAt`, where the two come
from different players' moves). Browsers disagree on the wall clock, so a
player whose clock ran fast charged that skew to themselves on every
turn; over a game's many turns it accumulated toward the total elapsed
time (observed in a real game: one player at ~46s of skew reached ~86%
of the game's wall-clock duration, while the player who followed them was
under-charged, clamped to 0 by the existing Math.max guard).

Drive the clocks from a single clock instead. `wrapper.move` — the
authoritative move processor, never reached during a deterministic
replay — now stamps each turn with the server clock as `serverTime`, and
`updateClocks` prefers it over the client `time`. AI turns are already
server-stamped, so human turns now match. The client `time` is kept
untouched: it is the move's identity for reconciling the turn buffer
against the server's echo (viewer turn-buffer helpers), and it still
drives the local preview clock on the acting player's own board.

Determinism is preserved: the server stamp is written into the log and
reused on replay. Added a wrapper test that plays with absurd client
stamps and asserts the timers track the server clock, plus a replay
check; pinned Date.now across the wrapper suite so buffers replay to
byte-identical states.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-16 09:55:08 -07:00
github-actions
1dcbcfb99c 🔖 powergrid-viewer 2.1.5 2026-09-14 20:45:41 +00:00
Eliott C.
3e8f55c0ad
Fix China Done freezing on a hidden deck (#153) 2026-09-14 22:45:08 +02:00
github-actions
e84d00d2a7 🔖 powergrid-viewer 2.1.4 2026-09-14 00:48:43 +00:00
goldjohn6
e20f0b2215
Show the chat shortcut only for unread messages, beside the settings gear (#152)
A player reported that the floating "Chat" tag hovers in the lower left and
blocks things (on a phone it covered the journal and the uranium market),
while the chat itself is always reachable below the board.

- Only show the shortcut when there is an unread message and the chat feed
  is not already on screen.
- Move it bottom-right, 89px from the edge: just left of the platform's
  settings gear (fixed at right:25px, 45px wide), the slot the platform's own
  chat button used. Restyled as a pill with the unread count.
- protocol-smoke: the Journal-tab check now expects no shortcut without
  unread chat; added checks for the count, the anchor, not covering the
  game buttons, and that clicking it brings the chat into view and it hides
  once read.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-13 17:44:11 -07:00
github-actions
b0442bf9ce 🔖 powergrid-viewer 2.1.3 2026-09-13 21:00:35 +00:00
Eliott C.
41829b9c5a
Use shared BGS viewer and chat protocol (#151)
* Use shared BGS viewer and chat protocol

* Use the viewer TypeScript config in every build worker

* Use shared chat panel and preserve mobile journal shortcut

* Update shared chat visibility and show date separators

* Keep typing after completing a chat mention
2026-09-13 22:54:10 +02:00
github-actions
d85e117dff 🔖 powergrid-viewer 2.1.2 2026-09-12 18:46:56 +00:00
44a7c49eb8 Scroll restored feeds to latest when they become visible 2026-09-12 20:40:40 +02:00
github-actions
8b7a27c914 🔖 powergrid-viewer 2.1.1 2026-09-12 18:39:29 +00:00
bb39505b28 Add mobile chat and journal tabs with unread count 2026-09-12 20:37:48 +02:00
github-actions
a48e69ab0d 🔖 powergrid-viewer 2.1.0 2026-09-12 17:11:01 +00:00
Eliott C.
f51db1d657
Add inline journal cards, embedded chat and action sounds (#149) 2026-09-12 19:10:23 +02:00
github-actions
ac62adf13b 🔖 powergrid-viewer 2.0.14 2026-09-11 18:49:00 +00:00
goldjohn6
8c4eee03bb
Show what a city would cost to build, in its tooltip (#148) (#150)
In Step 3 the cost of a city depends on how many players are already
there, so two cities a player can reach can differ by 10 Elektro with
nothing on the board to say so. #148 asked for that number.

It did not need computing. `available-moves` already totals the
shortest-path connection cost and the slot cost for the current
occupancy (10/15/20 in the standard build, per-map `slotCosts`
otherwise) and drops every city the player cannot afford — the viewer
was throwing that total away and keeping only the names.

So the change is to stop discarding it: `getBuildableCityPrices()`
passes the per-city totals to the map, and a buildable city's tooltip
reads "Suwon — build for 17" instead of "Suwon".

A tooltip rather than a printed label, deliberately. Measured across
every recharged map at 2-6 players, a Step-3 build turn offers a median
26-52% of the cities in play and sometimes all of them, so a label on
each would bury the board it is meant to explain — and there is nowhere
to put one in portrait. Only three tooltips needed changing: the map
already draws tap-target overlays on actionable cities, and SVG
hit-testing gives the tooltip to the topmost element.

Japan's free jump quotes the same city at two prices, so both are shown.

Verified by executing 11,533 offered build moves across every recharged
map at 2-6 players and asserting the quoted price equals the money
actually deducted: zero mismatches. Free-jump quotes were only 16 of
those — correct in all 16, but thin. Live-checked in the browser on
Korea in portrait.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 11:45:56 -07:00
github-actions
ff063e6f5e 🔖 powergrid-engine 2.0.6 2026-09-03 17:25:41 +00:00
goldjohn6
b7a6c5a8ef
Spell out the UK & Ireland first-house cost in the map rules (#146)
* docs(engine): spell out the UK & Ireland first-house cost in the map rules

The cross-island rule said "an extra 20 Elektro on top of the normal
first-house cost" without naming that cost, so the total for starting a
second network was not obvious at the table. Name it ($10) and set FIRST
apart, per Mike's read of the dialog.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Update engine/src/maps/ukireland.ts

Co-authored-by: Eliott C. <coyotte508@gmail.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Eliott C. <coyotte508@gmail.com>
2026-09-03 10:23:40 -07:00
github-actions
74f3c7b42c 🔖 powergrid-viewer 2.0.13 2026-09-01 11:50:24 +00:00
Eliott C.
c8df08ef29
Fix crash on hard refresh (TypeError: can't access property "phase", e is null) (#147) 2026-09-01 13:49:18 +02:00
github-actions
062382b78a 🔖 powergrid-viewer 2.0.12 2026-08-31 18:41:01 +00:00
Eliott C.
5ffe75604a
docs(viewer): mention the all-cities-built Step 2 start in the rules dialog (#145)
Step 2 also fires when every city has a house (all Step 1 slots filled),
even if no player reached the citiesToStep2 threshold — relevant on
small maps like UK & Ireland 3p where the total can be 18 cities. The
engine already implements this; document it.
2026-08-31 11:38:27 -07:00
Eliott C.
56a7150e49
fix(viewer): don't warn about unused plants when used ones power all cities (#144)
The pass confirmation in Bureaucracy fired whenever the player had any
unused power plant, even when the plants already used were enough to
power every city they own. Only warn when the used plants cannot cover
the owned cities.
2026-08-31 11:36:48 -07:00
github-actions
90a380075e 🔖 powergrid-viewer 2.0.11 2026-08-31 11:37:17 +00:00
github-actions
3cf49051f4 🔖 powergrid-engine 2.0.5 2026-08-31 11:33:28 +00:00
Eliott C.
6aff7593eb
fix(engine): replay scrubber broken on Russia/China after Step-3 boundary (#143) 2026-08-31 13:30:07 +02:00
github-actions
1b8a4256c2 🔖 powergrid-viewer 2.0.10 2026-08-28 17:15:46 +00:00
goldjohn6
89212753e3
Read the player order without rewriting it (#141) (#142)
Toggling "adjust player order" on and off landed on inconsistent states. The
setting was correct on its first activation, wrong on the second, right again
on the third.

`Array.reverse` works in place. `adjustedPlayerOrder` ended in
`this.G.playerOrder.reverse()`, so a getter whose whole job was to READ the
turn order rewrote the game state every time it ran -- and returned the state's
own array rather than a value of its own. Two things fell out of that one line:

- The toggle. The getter re-runs when the preference changes, and each run
  flipped the same array again. Turning the setting off returned seat order
  without unflipping anything, so turning it back on reversed an
  already-reversed order back to the original -- the setting meaning something
  different on every second activation.
- The order track on the board. `PlayerOrder.createPieces` lays out the
  goldenrod 1-6 track straight off `G.playerOrder`, in a `$nextTick` that runs
  AFTER the render that evaluates this getter. While the preference was on and
  the phase was not Auction, the track printed backwards on every state update.

The engine already spreads before it reverses, in both places it walks the
order backwards; only the viewer mutated.

The logic moves to `util/player-order.ts` so it can be tested against real
engine states, the same way `util/resource-rows.ts` is -- being unreachable
from a test is how it stayed wrong. The spec covers the property rather than
the arrow: reading is repeatable, reading leaves the board alone, and the
on/off/on sequence from the issue lands where it started. One of those tests
was itself bent at first -- comparing two reads compared the same array object
to itself and could not fail until the first read was copied.

Reported by coyotte508.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 10:13:04 -07:00
github-actions
ee28d9db9e 🔖 powergrid-viewer 2.0.9 2026-08-26 16:47:50 +00:00
goldjohn6
3dcdfde1d2
Portrait: a switch between the box market and the printed price track (#140)
The box market (#134) is the buying surface: one box per buyable source, the
price this player pays, and the whole box a tap target. What it throws away is
the price LADDER -- how far the next cube is, where the fuel actually sits --
and on maps where a resource is scarce and its prices are far apart, that ladder
is most of what there is to know. India's Step 1 / Step 2 lines exist only there.

So the boxes stay the default and stop being the only option: a two-way switch
sits between the plant market and the resource row, held to the same 0.94 width
budget as the market below it so the two share an edge. 188x44 css px per half at
414x896, on the tap guideline. Landscape and desktop are untouched -- the switch
renders only inside the stacked layout, and the preference cannot reach them.

The printed track fills itself imperatively and createPieces only ever ran on a
state update, so a track switched on mid-turn drew an EMPTY market until the next
move landed -- and on Korea it also lost the North market entirely, since
`isKorea` is set inside createPieces. Filled on the switch, before measuring: the
cubes are what give the group its size.

Asked for by coyotte508.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 09:44:32 -07:00
github-actions
94538427e9 🔖 powergrid-viewer 2.0.8 2026-08-25 19:01:26 +00:00
goldjohn6
6158fbc8e2
Send a move the server offered, even when we cannot preview it (#131 follow-up) (#139)
Passing in a fastBid auction did nothing. The button was lit, the click was
real, and the move never left the browser.

Since 2.0.5 every move is replayed locally before being sent, so a click made
against a stale list cannot poison the turn (#131). That replay runs on the
state THIS player holds — which is stripped of everything they may not see. A
fastBid auction keeps the other players' sealed bids hidden, so the response
that RESOLVES the auction reaches for a bid that was stripped out and throws.
`sendMove` read the throw as "the engine refused this" and returned without
sending. Bots answer instantly, so a human is nearly always the last to
respond: in practice this swallowed almost every Pass in a fastBid auction.

Verified against the engine: over 40 such auctions, the pass throws on the
player's own copy every single time and on the server's full state never.

So distinguish the two failures instead of treating both as refusal. The engine
refuses with an AssertionError; a copy that cannot carry a move fails reaching
for what was stripped out. Only when the engine actually asserted — or when the
server never offered the move — is it dropped; otherwise it is sent unpreviewed
and the server replays it from the full state.

The discriminator checks the error NAME, not its code: Node stamps
`code: 'ERR_ASSERTION'` and the browser build of `assert` does not, so the first
version of this passed every test in Node while letting illegal moves through in
the bundle. Caught by re-running eric-hu's over-buy case in a real browser.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 11:52:14 -07:00
github-actions
5181e6b4bb 🔖 powergrid-viewer 2.0.7 2026-08-25 18:20:52 +00:00
goldjohn6
52fbafc512
Ask again for the viewport when the board is revealed (#138)
On a phone the board could load in the landscape layout with no toggle to leave
it. The platform mounts the viewer in an iframe that is `display: none` until
the game state arrives, so the first measurement inside it is 0x0 — and
`0 < 900 && 0 > 0` is false, so the viewer settled on "landscape" against a
viewport that did not exist yet.

Measured on the live site at 390x844: the iframe exists at t=513ms as
`display: none` at 0x0, and only becomes 390x788 at t=1486ms. Recovery then
depended entirely on the browser dispatching `resize` when the iframe was
revealed. Chromium does; Safari does not reliably, which is why a fresh load
righted itself after a moment while arriving from the lobby stayed landscape.

So stop depending on that event. `relayout` refuses to answer while there is
nothing to measure, and a ResizeObserver on the document asks again the moment
being revealed gives it a box. Resize handling is now deduplicated by viewport
size, because the observer also fires for the board's own output.

Reproduced by mounting the viewer in a hidden iframe with `resize` and
`orientationchange` deaf inside it: before, the frame reached 390x788 and
portrait never turned on; after, it turns on within 100ms of the reveal. With
events working normally the behaviour is unchanged, desktop still lays out
landscape, and the observer settles in two relayouts with no loop.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 11:18:50 -07:00
github-actions
e0a28d944f 🔖 powergrid-viewer 2.0.6 2026-08-25 18:02:47 +00:00
goldjohn6
d5fadc9696
Take back a resource bought earlier in the same turn (#127) (#137)
Clicking an empty space in the resource market gives back a cube bought this
turn: the market's empty spaces become clickable while the turn buffer still
holds a purchase from that source, and the brightened ones are the spaces the
cubes actually left.

This is not an engine undo. Since 2.0.0 there is no Undo move at all — undo is
buffer truncation — so a take-back drops that one buy from the buffer and
replays the rest, exactly as undo() drops the last move. Removing a purchase
only ever frees money and plant capacity, so the remainder always replays
(checked over 653 mid-buffer removals across 109 buffers and 8 maps).

Which spaces light up is computed from each market's own fill line: the two
families of builder index their slots in opposite directions, so every push
site now stamps a ghostRank counting outward from the line it fills against.

The portrait box market replaced the printed track's empty spaces, so it gets a
take-back button on the affected row instead, sized for a thumb.

Two sources cannot honour a take-back through the track: South Africa's storage
pool and USA-recharged's supply are drawn by count, so they leave no space
behind. The portrait button covers both, and on a bare USA track the coal
spaces no longer offer a take-back that would return the cube to the pile
instead.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 10:58:05 -07:00
github-actions
4c680256bf 🔖 powergrid-engine 2.0.4 2026-08-24 18:44:51 +00:00
github-actions
9bf5f93832 🔖 powergrid-viewer 2.0.5 2026-08-24 18:43:28 +00:00
goldjohn6
203454e243
South Africa: storage coal only when the track has nothing cheaper (#136)
Mike's ruling, 2026-08-24: the $8 storage pool should not be on offer while there
is cheaper coal sitting on the printed track. You cannot reach past a $4 cube to
pay $8 for a stored one.

It had been available unconditionally whenever storage held cubes, which made a
strictly worse purchase one tap away all game — and on portrait, where the two
coal sources sit as two boxes side by side, it read as a real choice rather than
a trap. That is what surfaced it.

The track tops out at $8, so in practice storage now opens once the market
reaches its last price band or empties. This is the same shape as USA recharged's
$8-from-supply, which was already gated on the market being bare, so the two flat
pools finally behave alike.

Replay-affecting in principle: it removes a legal move, and a recorded game
containing one would fail a fresh replay. Measured across 30 South Africa AI
games (5 player counts x 6 pinned dice): 58 storage buys, every one of them made
while the market was already EMPTY, and none while cheaper coal existed — the AI
takes the cheapest option, so it never made the wasteful buy. NOTE the regime:
that says nothing about a human, who could have made it in a live game. Deploy as
duplicate-to-next-version, as behavioural changes do.

Differential sweep, 23 maps x 2-6 players x 3 pinned dice = 345 games:
345 identical, 0 changed.

Regression spec teeth-checked against the old behaviour, covering all three
bands: a full track ($1 next) refuses storage, the last band ($8) opens it, and
an empty track leaves storage as the only coal there is.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 11:38:33 -07:00
goldjohn6
db84315a69
India: let a player pass when they cannot fire anything (#135)
India requires powering as many cities as possible, and that was implemented as
"you may not pass while below your target". A player who runs out of fuel short
of the target is then offered NOTHING in Bureaucracy: no plant to fire, no pass.
Nothing to click at all. Bureaucracy is simultaneous, so the whole table waits on
that seat until they are dropped for inactivity.

Bots never hit it — `player.isAI` is an explicit escape on the same line — which
is exactly why it survived: it only ever bites humans, and only on India.

Measured with the AI dice pinned, five player counts x six games each:

    humans   24/30 India games freeze a seat in Bureaucracy
    bots      0/30
    every other map, humans   0/30

"As many cities as possible" is already satisfied once there is nothing left that
CAN be fired, so that is the added clause. Afterwards humans go 24/30 -> 0/30.

Differential sweep, 23 maps x 2-6 players x 3 pinned dice = 345 games, comparing
outcome, move count, final round/step and a state hash with the clock fields
stripped: 333 identical, and the only 12 that differ are the India games that
used to freeze. Every other map is untouched, which the India-gated condition
already implies but is worth measuring rather than asserting.

The regression spec was teeth-checked against the old behaviour, and its first
draft passed for the wrong reason — at setup a player owns no plants at all, so
"cannot fire anything" was vacuously true. It now gives the seat a coal or oil
plant from the opening market, so the no-fuel case is a real one, and asserts the
other direction too: while a plant CAN still be fired, India still refuses the
pass.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 11:30:33 -07:00
goldjohn6
ab0ee2610f
Portrait: draw the resource market as one box per source (#134)
* Portrait: draw the resource market as one box per source

The printed price track is a beautiful object and an unreadable one on a phone.
Eight to ten price columns of three-cube slots, drawn at whatever width the map
author chose, get squeezed into a strip: the cubes end up a few pixels across,
and telling which price column a cube is standing in is guesswork.

So on portrait the track is replaced by one box per buyable source, carrying only
what a purchase actually needs — what the next cube costs, what it costs after
that, how many are left at the current price, how many are left at all. Each box
is the whole tap target. Landscape and desktop are untouched: this is an
either/or on the stacked layout, never an overlay, and a player who switches the
portrait layout off gets the printed board back.

Every number comes out of the engine state rather than the printed geometry, so
the map-specific markets come along without special cases: Europe's nine price
columns, Korea's two sides as two labelled blocks (north correctly without a
uranium row), Australia's Step-3 CO2 shift, Bremen's missing nuclear, India's
per-step price cap shown on the rows it locks, South Africa's $8 storage pool,
USA recharged's $8-from-supply once the track is bare. What a player may tap is
not decided here either — that is the engine's own availableMoves, so money,
storage capacity, the hybrid tank and Korea's side lock are already accounted for.

Two things a box has to get right that the printed board never had to:

- A flat-price pool has no "buyable at this price" number, because every cube in
  it costs the same. It says so rather than drawing an arbitrary three dots.
- Central Europe sells garbage a dollar cheaper to whoever holds Wien, and the
  engine really does charge the lower price. A box shows the price THIS player
  would pay, because that is the only number a tap can act on.

The row model lives in `util/resource-rows` rather than in the component so it can
be tested against the engine directly, and that is what the spec does: for every
buyable row on ten maps, buy one cube and assert the engine took exactly what the
box said it would. Both halves of that were teeth-checked — an off-by-one in the
price index fails it, and so does dropping the Wien discount.

Measured on an iPhone XR (414x896): each box renders 405x55 css px, against a
44x44 guideline, on every map. Korea's seven rows are the tallest at 494px, still
inside the peek budget. A tap dispatched at real screen coordinates on South
Africa's storage box emits {resource: coal, fromStorage: true}.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Portrait: breathing room, a horizontal mine market, the two coals together

John's notes on the first cut, at the phone.

The boxes ran to both screen edges, which read as though the row had been
cropped rather than laid out. They now take 94% of the canvas like the plant
market does — and because each box is narrower it also scales taller, so the tap
targets grew from 55 to 57 css px rather than shrinking.

Inside a box the cubes were pinned to a fixed left edge, so a row with one cube
left a long dead gap before the count. They are centred in the band between the
price and the count now, whatever the count. The middle caption is centred on
them too, and shortened, because at the narrower width it ran into CUBES LEFT.

Australia's uranium mine market was a 104x430 vertical strip, which is the worst
possible shape for a full-width row: it can only grow until its HEIGHT fills the
row, so it ended up a sliver with the whole width empty beside it. Turned through
90 degrees the six prices run left to right in the same order they ran top to
bottom. Australia's page went from 2.05 screens to 1.62. Landscape keeps the
vertical strip exactly as it was.

South Africa's storage coal now sits directly under the market coal instead of at
the bottom of the list, so the two coal prices are read together — the track is
usually the cheaper of the two, and that should be obvious without hunting for
it. Deliberately NOT hidden or dimmed when the market is cheaper: it is a legal
move, and a viewer that greys out a legal move is the same class of bug as #131.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 11:25:49 -07:00
goldjohn6
4426f78810
Show every player's cash when replaying a finished game (#130) (#133)
eric-hu, #130: discussing a game afterwards, "we couldn't evaluate whether
someone ending early would have changed the outcome" without each player walking
back through their own replay viewer and reporting their cash at the same step.

The data was never missing. The replay scrubber rebuilds each step with
reconstructState, which replays the log from a fresh setup and therefore derives
every player's true cash — it is only the display that hides it. That gate asked
`gameEnded(G)`, and during a replay `G` is a reconstructed MID-game state whose
own ended() is false however long ago the game finished. So cash stayed blacked
out for every step but the very last one, which is the one step nobody needs to
scrub to.

Ask whether the game is over instead, remembered from the states the platform
actually served. An in-progress game is untouched and still hides everyone
else's wallet, which coyotte508 asked for on the issue — and matters more than
it looks, since the reconstruction has the true numbers either way, so this gate
is the only thing standing between a mid-game replay and hidden information.

Checked against a real finished game pulled from the live API (Inert-ship-4128,
Central Europe 5P, 681 moves): all 681 steps reconstruct, every player's cash is
present at every one, and only the last step passed the old gate.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 11:17:45 -07:00
goldjohn6
6762c63f6a
Preview a move locally before sending it (#131) (#132)
eric-hu, #131: "Wrong argument for the command BuyResource" appearing at the end
of a game, when he "tried to buy more resources than I needed", and clearing only
after a couple of page refreshes.

sendMove pushed the move into the turn buffer and emitted it without previewing
it, so `this.G` — and with it `availableMoves` — stayed frozen on the last state
the server sent. Every click made while a response was in flight was therefore
judged against a stale list, and the platform replays the WHOLE buffer from the
last committed state, so one click past what a player's plants can hold is
rejected wholesale.

Two things made it stick rather than flicker. The viewer has no error path at
all, so nothing removes the offending move again: it stays in the buffer and
every later action resends it and fails the same way. And a refresh is the only
thing that empties the buffer, which is exactly the recovery he found.

Previewing first is what undo() already does, and the replay is exact — a move
with hidden side effects commits, which ends the buffer. So the cube goes dead
the instant the engine stops offering it, and the illegal buffer can no longer
be built. Measured over 258 seats (10 maps x 2/4/6 players x rounds 1/5/8), one
click past the limit: 492 buffers rejected by the platform before, 0 after.

Only a still-tentative preview is adopted. A committing move replays hidden
outcomes — deck draws, upkeep — on a state whose deck and seed are stripped, so
its preview would flash bogus results; the server's committed answer is waited
for instead. The preview is also silent: the authoritative echo of the same
buffer lands next and owns the sound, and playing it twice would double it.

Two tests, covering the mechanism the fix leans on rather than the wiring: that
previewing a move advances availableMoves so the next illegal click is never
offered, and that a resource buy past storage capacity is truncated by the
replay instead of reaching the server.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 11:10:08 -07:00
Eliott C.
8d97fe4c22
Make preferences reactive and inline static assets in build (#128) 2026-08-22 18:04:41 -07:00
github-actions
25a9857b3c 🔖 powergrid-viewer 2.0.4 2026-08-20 16:13:33 +00:00
goldjohn6
933d11aa45
Bigger tap targets for cities, and a tidier button row on portrait (#126)
* Let a city be tapped anywhere inside its printed circle (#125)

eric-hu, reviewing #125: city slots are only buildable in the gray area, and
later in the game you have to click around the houses already standing there.
Both are the same mechanism — houses are drawn after the city's own circle, and
SVG hit-testing takes the topmost element, so a house physically covers the
target underneath it.

One transparent hit circle per actionable city, drawn last so it sits above the
houses. Its radius reaches out to the coloured region ring, which is what the eye
reads as the edge of the city — but never past half the distance to the nearest
city, because the maps disagree wildly about spacing: Bremen's closest pair is
90.8 apart and South Africa's Johannesburg N/S is 21. A fixed 25 would have had
neighbours stealing each other's taps on seven maps. It is also never smaller
than the disc the target has always been.

Measured at 414x896 on a round-9 board, sampling each city's printed disc:

  Northern Europe   mean tappable share  60.8% -> 100%
  South Africa      mean tappable share  54.5% -> 93.1%   (worst city 22.5% -> 50%)
  Bremen            mean tappable share  42.0% -> 100%

Johannesburg N was the worst case anywhere: two houses took 22% of its disc, its
twin took 10%, and the ring was never clickable at all. No city's centre was ever
blocked, on any map, before or after — so nothing was unbuildable; it was just
much harder to hit than it looked.

Only rendered while the city can actually be built on or drafted, so houses keep
their own tooltips the rest of the time. Nothing is painted: on a 1440x900
desktop the rendered SVG is identical apart from these transparent circles.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Stop the layout toggle hanging into the market on a portrait phone

On a portrait viewport the icon column beside Pass / Undo / Log gains a fourth
button — the layout toggle — in a space authored for three. At the authored
41-unit pitch it hung 41 units below everything else in the group, and since the
group's height sets the row's height, the toggle ended up sitting on "Actual
Market:" and the first plant in the row below it. John, at the phone.

Three parts:

- On portrait only, the icons shrink to the 26-unit height of the text buttons
  beside them and re-pitch to 30, so all four end level with Log. Landscape and
  desktop keep the authored positions exactly — verified by comparing the emitted
  transforms at 1440x900, which are the same literals as before.

- The round/step/phase readout gives up a little more scale (2.2 -> 1.9). It is
  text you glance at; the buttons next to it are what a thumb has to hit.

- What a capped slot declines is now handed to the slots that can still grow.
  Until now it just became margin either side of the row: the readout was giving
  up ~130 units of width and nobody was picking them up. The row this affects is
  the only row on any map with both a capped and an uncapped slot, so nothing
  else moves.

At 414x896 the buttons group goes from 98px wide to 123px — Pass is now 80x26
rather than 63x20 — and the row is 8 scene units shorter than before, so no page
grew. Swept all 24 maps at 2 and 6 players: no row overlaps another, nothing
overflows horizontally, no row exceeds 72% of the screen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 09:09:53 -07:00
github-actions
8960f6f952 🔖 powergrid-viewer 2.0.3 2026-08-19 19:46:39 +00:00
github-actions
6dd8d36ed7 🔖 powergrid-engine 2.0.3 2026-08-19 19:45:27 +00:00
goldjohn6
b8a8959514
Mobile portrait and rulesPortrait layout for phones, the deck build on every map, and India rules (#123) (#125)
* wip: portrait stacked layout + modal table overflow fixes

* Portrait layout: John's row plan, centred market, no-store dev headers

* Add stackOnPortrait preference (default on) with an in-board toggle

* Move the layout toggle clear of the turn-order table; cap any row at 72% of the screen

* Budget the market row by width, not by scale, so every map's market clears the edges

* Show the deck build on every map: standard build per variant, plus each map's difference

* India (#123): state the outage trigger and step price caps, and give the step markers real margin

* Name the plug plants in the standard deck build (John, at the table)
2026-08-19 12:43:43 -07:00
github-actions
059801b1e6 🔖 powergrid-viewer 2.0.2 2026-08-19 18:45:45 +00:00
github-actions
20ed98e167 🔖 powergrid-engine 2.0.2 2026-08-19 18:42:30 +00:00
mmunson99
87f4c62771
India: start uranium at $6, and only warn on skipping fuel if none was bought (#124)
Two India fixes:

- Starting uranium price was $7, not the $6 the map comment intends. India's
  resource price is uraniumPrices[length - count], so a starting count of 2 gives
  uraniumPrices[6] = $7; bump startingResources uranium to 3 so it reads
  uraniumPrices[5] = $6. Applies to both variants (shared map object).

- The Resources-phase "skip buying resources without enough to power all your
  plants?" warning fired whenever a player couldn't power everything. India's
  market is restrictive (per-step price caps, price tiers, one purchase at a time),
  so a player often can't buy enough even when trying, and the nag is just noise.
  On India, only show that warning when the player bought nothing this turn;
  buying some but not enough is a deliberate choice. Every other map is unchanged.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-19 11:33:14 -07:00
github-actions
52c17d9a78 🔖 powergrid-viewer 2.0.1 2026-08-17 18:05:27 +00:00
goldjohn6
972de2b299
Refetch committed states instead of adopting them from the log payload (#121)
The gamelog channel carries two different things: the move response, whose state
may be tentative, and the plain log fetch. Only the first needs to be applied
directly -- tentative states are never persisted or broadcast, so that response is
the only way one can reach the acting player's viewer.

The second is served by GET /gameplay/:id/log, which is not logged-in. It resolves
the player with findIndex, yielding -1 when there is no user, and stripSecret then
blanks EVERY player's availableMoves. Adopting that state left the acting player
with a fully rendered board and nothing clickable after a page refresh, recovering
only by leaving and re-entering the game (which takes the fetchState path).

Measured on a live v10 game: the log endpoint reported currentPlayers [3] with
players[3].availableMoves == {}.

So adopt a state from this channel only while it is tentative, and refetch
otherwise -- which is what the viewer did before the tentative-turn model. This
also fixes the bug against engine 2.0.0, where the state is always present;
2.0.1 additionally omits it when it cannot attribute it, and both are covered.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 11:02:36 -07:00
github-actions
a74aa9a75c 🔖 powergrid-engine 2.0.1 2026-08-17 17:50:46 +00:00
goldjohn6
29956b424e
Only return a state from logSlice when the player is known (#120)
The viewer now adopts `data.state` from the gamelog payload instead of always
refetching, so it inherits how that payload was stripped. `GET /gameplay/:id/log`
is not logged-in: it resolves the player with `findIndex`, which yields -1 when
there is no user, and `stripSecret` then blanks EVERY player's availableMoves.

The acting player therefore got a live board with nothing clickable after a page
refresh, recovering only by re-entering the game (which takes the fetchState
path). Measured on a live v10 beta game: the log endpoint reported
currentPlayers [2] with players[2].availableMoves == {}.

The blanking predates the tentative-turn model and was harmless while the viewer
ignored this payload. Offer `state` only when the index actually identifies a
player; without it launch.ts falls back to fetchState, i.e. the old behaviour.
The log itself keeps being served either way.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:48:46 -07:00
github-actions
47efcd19e1 🔖 powergrid-viewer 2.0.0 2026-08-17 16:26:39 +00:00
github-actions
b81bfc27fe 🔖 powergrid-engine 2.0.0 2026-08-17 16:22:50 +00:00
Eliott C.
b90b5c63bf
Tentative-turn model: per-turn time increments, free undo, append-only log (engine+viewer 2.0.0) (#119)
* engine!: replace destructive undo with the tentative-turn model

- engine.move computes a per-state committed flag (G.newTurn): committed once
  the mover can no longer undo — i.e. the negation of the old undo-availability
  rule (last visible log entry is the mover's own move, mover still current,
  move not a Pass). Old saves without the flag are treated as committed.
- wrapper.move now accepts the whole current-turn buffer (Move[] or a bare
  move) and replays it atomically from the committed state; a buffer that
  continues past a turn boundary is rejected (one committed turn per call).
- toSave returns undefined for tentative states, so the platform neither
  persists them nor grants a time increment; undo becomes buffer truncation
  in the viewer (replaying preserves each move's original time stamp, keeping
  the in-engine clocks deterministic across resends).
- MoveName.Undo, Moves.MoveUndo, the manual per-case reversal block, the
  isUndo parameter (and its issue-8 DiscardPowerPlant leniency) and the
  lastMove-from-log recomputation are gone; the saved log is append-only.
- wrapper.moveAI wraps engine.moveAI to always land on committed states
  (capped loop + console.error telemetry); dropPlayer force-commits and no
  longer null-derefs availableMoves when dropping a non-current player.
- wrapper.replay replays [...log, ...hiddenLog] so states saved mid-fastBid
  auction (bids live in the hidden log) reproduce faithfully.
- logSlice now returns the stripped state, the only channel through which the
  acting player's viewer receives tentative states.

BREAKING CHANGE: engine major bump — the Undo move no longer exists and move
payloads are turn buffers.

* tests: cover the tentative-turn wrapper model

Wrapper specs exercising the platform contract end to end: tentative states
never persisted / committed states saved (Auction, Resources, Building via the
Bureaucracy script, color draft, fastBid), undo-by-truncation equivalence,
malformed-buffer atomicity, one-turn-per-call boundary rejection, hidden-log
replay of mid-fastBid saves, deterministic clocks across buffer resends, an
engine-level Bureaucracy rebase (two simultaneous players committing
independently), and moveAI/dropPlayer always landing on committed states.

* viewer!: tentative-turn buffer instead of engine Undo moves

- Game.vue keeps a turnMoves buffer plus the last committed state; every action
  is stamped with time ONCE when it enters the buffer, and the WHOLE buffer is
  re-sent on each action (the platform replays it from the committed state).
- Undo honors the undoWholeTurn preference locally: pop one move or scrap the
  whole tentative turn; the shortened buffer is re-sent (or nothing at all when
  it empties — the committed state IS the turn start). No engine Undo exists.
- Incoming states: tentative echoes are applied only when they match exactly
  committedState.log + turnMoves (stale-echo guard); committed states clear the
  buffer when they contain it (own commit echoed) and REBASE it otherwise —
  another player's simultaneous Bureaucracy commit replays our buffer on the
  new base, dropping a now-illegal tail gracefully.
- Turn-buffer logic lives in src/util/turn-buffer.ts (pure, unit-tested).
- launch.ts feeds move-response states (the only channel carrying tentative
  states) into the app; self-contained.ts mimics the platform: replay the
  buffer, echo tentative results, persist + broadcast only committed ones.
- Sidebar log wiring (logReversedSimple / @Watch('G.log') / replaceLog) is
  untouched: one line per atomic action, live, removed on undo.
- Replaced the dead example.spec.ts (imported a HelloWorld.vue that no longer
  exists — pre-existing test:unit breakage) with turn-buffer unit tests.

BREAKING CHANGE: viewer major bump — move events now carry the whole turn
buffer and require an engine with tentative-turn support.

* chore: prettier formatting

* chore: sort turn-buffer imports; export LogMove from the engine root

Commits the pending cosmetic import reordering in the turn-buffer module
and its spec, and replaces the deep import of LogMove from
powergrid-engine/src/log with a proper re-export from the package root.

* viewer: scrap unreplayable turn-buffer leftovers; guard committing rebase previews

rebaseTurnBuffer now drops any leftover buffer when the mover can no
longer act on the new committed base (not in currentPlayers). This is
how moves whose effects are hidden get cleaned up: a fastBid bid commits
to the engine's hidden log, so a chooser's [choose, bid] buffer echoed
back showed only the choose and left [bid] behind — previously discarded
only by the replay's illegal-move error path (console noise, load-bearing
on an incidental assert). Covered by a new fastBid unit test.

The Game.vue rebase path now only previews a rebased buffer while its
replay stays tentative: a buffer ending in a committing move (e.g.
Bureaucracy [UsePowerPlant, Pass] racing another player's commit) would
replay hidden outcomes on the STRIPPED state (empty deck) and flash
bogus results; show the new committed base instead and let the server
echo land.

* chore: leave the version bumps to the release workflows

Both publish workflows compute `semver.inc(<version in package.json>, <input>)`
and commit the bump themselves, so a pre-written 2.0.0 makes 2.0.0 unreachable:
a `major` run would publish 3.0.0 and a `patch` run 2.0.1. Restoring the current
published versions lets a `major` run land engine 2.0.0 / viewer 2.0.0, which is
what this breaking change wants.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: John Gold <goldjohn6@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 09:20:50 -07:00
github-actions
69b08987a8 🔖 powergrid-viewer 1.11.23 2026-08-15 22:24:44 +00:00
github-actions
473aa029e5 🔖 powergrid-engine 1.15.24 2026-08-15 22:23:06 +00:00
goldjohn6
8489a974b4
Stop a resource discard from refilling the power plant market (#67) (#118)
* China: trim the Step 3 market down to four plants (partial fix for #67)

PARTIAL. This fixes one cause of #67 and demonstrably reduces it, but a second
path remains -- do not close #67 on this commit.

Mike reported in Aug 2024 that a China game "got to step 3 but kept five plants
in play". The rulebook (RIO 573, China) states the invariant twice:

  "Important: in Step 3, there are always 4 power plants in the power plant
   market regardless of the number of players."

Steps 1-2 hold the market at players-1, which is FIVE at six players. The Step 3
branch of rebuildPlantMarketForChina only ever filled UP (`while length < 4`), so
a market that arrived at the transition already larger than four simply stayed
large. Added the matching trim-down, smallest-first -- mirroring the step 1/2
branch directly below it, and the rulebook's "remove the smallest power plant
from the market".

rebuildPlantMarketForChina is now exported, matching applyAustraliaStep3Shift /
applyManhattanMarketLifecycle, so the transition can be asserted directly.

Tests: 71 specs (+2), tsc clean. The trim spec is teeth-checked -- with the trim
loop removed it fails on "Step 3 market is exactly four: expected 5 to equal 4".
The second spec guards the fill-up direction the trim could have broken.

WHAT IS STILL WRONG: a 125-game AI soak (pc 2-6 x 25 seeds) asserting the
"always 4 in Step 3" invariant went from 3/90 violations to 1/90 -- but the
survivor is a TWO-player game whose market reaches five during Step 3, which the
six-player mechanism above cannot explain. rebuildPlantMarketForChina is only
called at step <= 2 (engine.ts ~1057), so after the transition round the Step 3
market is maintained by the generic remove-lowest-then-draw path instead; the
remaining leak is somewhere in there. Not diagnosed yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* China: stop a resource discard from refilling the market (#67)

Completes the fix begun in 98e6459, and corrects that commit's stated next step, which
was wrong on both counts: the surviving soak failure was NOT a two-player game, and the
leak was NOT in China's generic remove-lowest-then-draw path.

The soak behind "3/90 -> 1/90" is non-deterministic. moveAI picks its moves with raw
Math.random (engine.ts:2090/2103/2107 and chooseRandom at :2189), so a game's seed only
seeds the deck shuffle -- every run plays different games. Re-running that same file
unchanged gave 0/80, then 0/84, then 0/83, then 1/80 on a SIX-player game. The count was
noise and the player count inside it was noise too.

Root cause, from a tripwire inside addPowerPlant: 31 hits across 4000 games, every stack
landing on engine.ts:1501 or :1561. The draw at the end of the over-capacity discard
chain is the refill a PURCHASE is owed -- but available-moves offers DiscardResources to
ANY over-capacity player during the auction phase, purchase or not. A player merely
carrying a resource their plants can no longer hold completed a discard and pulled a
free plant into the market. On China that lands in actualMarket, which is Mike's "got to
step 3 but kept five plants in play"; on every other map it inflates the future market
instead, the same symptom class as PR #100.

Three defects, all in shared code, none of them China's:

1. available-moves computed the hybrid-tank overflow unguarded while both engine
   handlers guarded it with `hybridCapacity > 0`, so a player with no hybrid plant who
   was over on coal was offered an OIL discard. Both sides now call one helper,
   coalOilOverCapacity. It also refuses to name a resource the player does not hold: an
   oversubscribed shared tank fails both tests at once, and the handler used to
   decrement an empty stock to -1.

2. The DiscardResources handler stepped down by a single cube and dropped it on the
   floor, so a player over by two stayed over by one -- and got prompted again later,
   which is what turned the residue into a second draw. It now calls
   discardDownToCapacity, the same clamp-and-return-to-supply its sibling in the
   DiscardPowerPlant handler already used.

3. endAuction marks the purchase (pendingMarketRefill) and refillMarketAfterPurchase
   consumes it, so all seven refill sites draw exactly once per purchase and never for a
   discard with no purchase behind it. The China/step-3 condition those sites repeated
   now lives in the helper.

Tests: 74 specs (+3), tsc clean, no new lint errors. Each new spec teeth-checked against
its own fix reverted -- the #67 one reads 5 where it wants 4, the offer one still lists
"oil", the clamp one leaves the player one cube over.

Evidence beyond the specs, since the change is engine-wide:

- All three replay fixtures (Germany, USA, supply) stay green.
- Differential sweep, every map x 2-6 players x both variants, 720 games with the AI's
  dice pinned, run on this tree and on its parent: 707 games byte-identical; 13 changed,
  every one a game where the discard chain fires. No map's market size changed anywhere.
  Games leaving a player holding a negative resource: 7 -> 0.
- China: 1000 seeded games (678 reaching Step 3) 0 violations; 4000 unseeded games (2649
  reaching Step 3) 0 violations. The same unseeded harness read 3/1331 and then 8/2631
  while hunting the cause. It is teeth-checked: with the previous commit's trim removed
  it reports 7/134.

NOT fixed here, deliberately. discardDownToCapacity clamps to capacity and ignores the
hybrid tank, byte-matching the DiscardPowerPlant sibling, which over-discards for a
player holding a hybrid plant. Correcting that turns the `supply` replay fixture red --
meaning the path is live in recorded games -- so it needs its own change and its own
evidence rather than a ride on this one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 15:21:06 -07:00
github-actions
37926ab02c 🔖 powergrid-viewer 1.11.22 2026-08-14 16:47:02 +00:00
github-actions
36fba7529a 🔖 powergrid-engine 1.15.23 2026-08-14 16:36:10 +00:00
goldjohn6
6fb432a041
China: correct seven city names and the Changchun-Jilin cost (#59) (#117)
yvessl reported in September 2023 that the China map does not match the printed
board. Every item still held; nothing had been applied.

Names (enum values, so the strings players actually see):
  Qiqhaer  -> Qiqha'er     Qingoad  -> Qingdao
  Badtou   -> Baotou       Kuerle   -> Ku'erle
  Xian     -> Xi'an        Chiyang  -> Guiyang
  Yinchjan -> Yinchuan

Four of these were plain transcription errors (Qingoad/Badtou/Chiyang/Yinchjan);
the other three were missing apostrophes. Enum KEYS were renamed only where the
key itself was misspelled -- Qiqhaer/Kuerle/Xian keep their identifier-safe keys
and carry the apostrophe in the value.

Connection: Changchun-Jilin was cost 5, the board says 2.

Also: engine/.eslintrc.js `quotes` gains `avoidEscape: true`. Three of the new
names contain an apostrophe, and without that option the rule and Prettier
deadlock -- Prettier rewrites 'Xi\'an' to "Xi'an" to minimise escapes, and the
rule then errors on exactly what Prettier produced. avoidEscape is the standard
companion setting; engine-wide lint is unchanged at 0 errors / 30 warnings.

Tests: 72 specs (+3). China had no coverage at all before this. The two
regression specs are teeth-checked against the pre-change map (they fail with
"Qiqha'er is on the map" and "expected 5 to equal 2"); they assert on the map
module rather than through setup(), because setup() trims cities by player count
and would quietly stop covering whichever names fell out of play. The third spec
walks every connection endpoint against the city list, so a rename that missed a
reference fails loudly.

DEPLOY NOTE -- this is the replay-breaking class, not an inert one, though the
blast radius is small and recoverable. Live game state stores its own map, so a
China game already in progress keeps playing on the old names. What breaks is
the replay view: wrapper.replay() rebuilds from a fresh setup() and re-applies
logged moves, so a logged Build on "Qingoad" no longer matches a map that says
"Qingdao". Measured against a real 6P China game -- it throws
"Wrong argument for the command Build", i.e. it fails loudly rather than
diverging silently. The player-facing path (GET /gameplay/:id/log?end=N) is
read-only, so a player who hits it can refresh and carry on; the variant that
persists (POST /gameplay/:id/replay) is admin-only. At time of writing exactly
one live China game exists.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 09:26:23 -07:00
goldjohn6
0a15decdf2
Harden the AI auto-play path now that it drives live bots (#116)
PR #112 re-exported moveAI so the platform could drive bot players with it, and
boardgamers has since switched bots on for Power Grid (the descriptor now reads
meta.bots: true). That promoted moveAI from an internal helper -- reached only
when a player timed out -- to a hot production path. Three things it was not
ready for, all found by reading it from that new seat:

- engine.ts: the Building-phase capacity sum used reduce() with no initial
  value, so a player holding no power plants threw "Reduce of empty array with
  no initial value" instead of scoring zero capacity.

- engine.ts: picking the cheapest Build / the smallest UsePowerPlant sorted
  availableMoves IN PLACE. That array is player.availableMoves -- part of the
  game state, and served to clients -- so choosing a move quietly rewrote the
  order players are shown. Both now sort a copy.

- engine.ts: a per-move console.log('ai move', ...) shipped to production. Bots
  move roughly every 1.5s, so this writes a log line per bot per turn into the
  platform's log pipeline. Removed; it was also the only console.log left in the
  engine's move path.

- wrapper.ts: dropPlayer auto-plays through moveAI in `while
  (G.currentPlayers.includes(playerNum))`, an unbounded loop. A state moveAI
  cannot advance would spin a game-server worker forever at 100% CPU with no
  request ever returning. Now capped at MAX_AUTO_MOVES (1000, orders of
  magnitude above any legitimate turn) and throws a diagnostic instead: a thrown
  error is recoverable and greppable, a hung worker is neither. This matters
  more now that the platform auto-drops inactive players.

Checked and NOT changed: every availableMoves key moveAI reads is length-guarded
at the source (available-moves.ts Build :576, UsePowerPlant :695,
ChoosePowerPlant :145, DiscardResources :85), so there is no empty-array hazard
there. DiscardPowerPlant :62 is the one unguarded assignment, but it can never
be empty -- countHeldPowerPlants excludes Australia mines, so the >3 threshold
guarantees at least three candidates survive the filter.

Tests: 69 specs (+3), tsc clean, eslint unchanged at 0 errors / 30 warnings.
The two new regression specs were teeth-checked against the pre-fix engine --
the empty-plants one fails with the exact TypeError, the ordering one fails on
"the stored Build list keeps its original order". The ordering spec also asserts
its own setup is not already price-sorted, so it cannot silently lose its teeth.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 09:06:48 -07:00
github-actions
3cd69e49ed 🔖 powergrid-viewer 1.11.21 2026-08-13 18:52:38 +00:00
github-actions
5373b7ae2c 🔖 powergrid-engine 1.15.22 2026-08-13 18:42:53 +00:00
goldjohn6
cb2c8fdb37
India original: plant 13 on top, found by number (#114)
Mike's follow-up ruling on #113: original-variant India follows the
standard rule after all - plant 13 goes on top of the deck. The pre-#113
code intended this but grabbed 14 (splice by index on a list with no
plant 11); #113 briefly made the top random. Now 13 is set aside by
number, UK&I-style, so the list shape can never shift it again.

Regression spec updated: 10-seed sweep asserts 13 on top every time -
it fails against both prior behaviors (14 pinned / random). Deck build
dialog line updated to match. 66/66 specs, tsc + lint clean.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 11:00:05 -07:00
github-actions
58d1af19c6 🔖 powergrid-viewer 1.11.20 2026-08-13 17:17:59 +00:00
github-actions
5d0e2ad151 🔖 powergrid-engine 1.15.21 2026-08-13 17:16:17 +00:00
goldjohn6
7f3462c526
Add "Deck build" setup text to map rules; India original: random top card (#113)
Every map whose deck preparation differs from the base game now ends its
mapSpecificRules with explicit "Deck build" lines (recharged/original per
Mike's format; one combined line where the variant makes no difference):
Australia, Brazil, Bremen, China, Europe, France, India, Manhattan,
Northern Europe, Quebec, Russia, South Africa, Spain & Portugal, UK&I.

India fix (per Mike): India removes plant 11 from the game, so the
original-variant splice(2, 1) written for the standard list landed on
plant 14 and pinned it to the top of every deck. India sets no plant
aside - a random plant now starts on top. Regression spec sweeps 10
seeds and fails against the old behavior (14 on top every time).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 10:13:59 -07:00
github-actions
c4bf04bd27 🔖 powergrid-engine 1.15.20 2026-08-12 20:08:25 +00:00
Eliott C.
f34947d509
feat: export moveAI for bot players (#112) 2026-08-12 22:07:44 +02:00
github-actions
d119a29518 🔖 powergrid-viewer 1.11.19 2026-08-04 00:07:19 +00:00
github-actions
93be0f70a5 🔖 powergrid-engine 1.15.19 2026-08-04 00:06:19 +00:00
mmunson99
38c0153b65
Confirm the purchase when you are the only remaining buyer (#111)
When every other player has passed or bought, choosing a plant buys it outright at
the minimum price (there is no one to bid against), with no prompt. A stray click
therefore commits a purchase. Add a confirmation box for that case: choosing a
plant as the sole remaining buyer asks "Buy Power Plant X for $Y?" — Buy commits it,
Cancel returns to the market to pick a different plant or pass.

Viewer-only. The dialog is gated by the same condition the engine uses to
short-circuit the auction (the current player is the only one who is neither
skipping nor dropped), so it appears exactly in the cases that auto-buy today and
never in a contested auction. It also covers Manhattan's discount-bonus purchase
for free, since that re-prompts the same sole buyer. The price shown mirrors the
engine's minimum bid (the plant number, or $1 for the recharged discount plant).

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 17:04:22 -07:00
github-actions
f5220c1694 🔖 powergrid-viewer 1.11.18 2026-07-25 21:59:33 +00:00
github-actions
0986218eca 🔖 powergrid-engine 1.15.18 2026-07-25 21:55:49 +00:00
mmunson99
26a8f04078
Mark the no-nuclear regions on the other restricted maps (#110)
Central Europe already shows the struck-through nuclear marker; extend it to the
other maps that ban nuclear plants in some regions, by setting the generic
noUraniumRegions field the viewer already renders:

- Spain & Portugal: yellow (Portugal)
- UK & Ireland: green (Republic of Ireland)
- Northern Europe: red (Norway), orange (Denmark)

Each list is the complement of the nuclear-allowed regions enforced per-map in
available-moves, cross-referenced in comments. No rendering changes — the marker
placement is the same generic, self-adjusting logic added with Central Europe.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-25 14:53:17 -07:00
github-actions
b64a022f03 🔖 powergrid-viewer 1.11.17 2026-07-25 05:43:55 +00:00
github-actions
6892220c7c 🔖 powergrid-engine 1.15.17 2026-07-25 05:21:09 +00:00
mmunson99
58af53c14a
Mark Central Europe's no-nuclear regions on the board (#109)
Central Europe only lets players with a city in Czechia, Slovakia or Hungary use
nuclear plants; the physical board prints a struck-through nuclear plant in each of
the three Polish regions. Render that marker: a nuclear-plant tile under a
prohibition sign (ring + diagonal bar) tinted in the region's own colour, one per
banned region.

Adds a generic noUraniumRegions field to GameMap (set to blue/red/yellow for
Central Europe) so other restricted maps can adopt it later; the auction rule
itself is unchanged in available-moves, and both sides cross-reference each other.
The viewer places each marker at the most central open spot in its region — the
point nearest the region centre that keeps a safe gap from every city node and
connection cost label — computed from the already-adjusted city coordinates, so it
covers nothing and needs no per-map tuning.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 22:15:56 -07:00
github-actions
5cd89eb68b 🔖 powergrid-viewer 1.11.16 2026-07-22 21:17:13 +00:00
github-actions
1e30e72624 🔖 powergrid-engine 1.15.16 2026-07-22 21:15:44 +00:00
goldjohn6
958cb6cc62
Bremen: spell out deck preparation in the rules dialog (#108)
Players asked what Bremen actually removes from the deck, and whether the
low ("plug") plants were being stacked on top of the draw deck rather than
shuffled in.

The setup was correct — two finished live games replay card-for-card off
their seeds, and the leftover low plants land all over the deck — but the
rules dialog never said any of it. It listed "no nuclear" and nothing about
deck prep, which is also slightly wrong: plant 50 burns no fuel and stays in
the 5-6 player deck.

So: add a deck-preparation paragraph naming the removed plants (the six
uranium plants plus the three that power 7 cities, plus 31 and 50 for 2-4
players), noting that no further plants are removed for the player count,
and describing the opening market of eight, the one low plant on top of the
deck and the rest shuffled in. Reword the uranium line to match, and split
the text into paragraphs so it reads in the dialog.

New spec pins the deck structure across every player count so the question
has an answer in code: eight low plants open the market, exactly one is
guaranteed on top, the leftovers are spread through the deck, Step 3 is on
the bottom and the deck size shows no extra player-count reduction.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:00:11 -07:00
github-actions
a31cffb296 🔖 powergrid-viewer 1.11.15 2026-07-20 00:50:25 +00:00
github-actions
fa3789de52 🔖 powergrid-engine 1.15.15 2026-07-20 00:47:48 +00:00
mmunson99
fd63116586
Player timers (#107)
* Add a Cost per City row to the end-of-game stats popup

Shows what each city effectively cost a player: the house price plus the
connection cost paid to reach it, divided by the number of cities built. Sits
directly under the two rows it derives from (Spending: Cities and Spending:
Connections). Displayed to one decimal; a player with no cities shows "-" rather
than dividing by zero.

The table picked each cell's value through a nested ternary on the row index,
which a sixth row would have made unreadable, so the rows are now data-driven via
a spendingRows getter. Row order and every existing value are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Track per-player time and show it during the game and in the stats popup

Each player now has a clock that runs exactly while they are a current player.
Their board shows a live total that ticks while it is their turn (bold for the
player on the clock), and the end-of-game stats popup gains a Time Used row.
Durations are formatted at a precision that suits the magnitude, since games range
from minutes per player to correspondence games running for days: 45s, 12m 34s,
3h 22m, 5d 3h.

Because a clock runs per player rather than dividing up elapsed wall time, every
player in a simultaneous phase accrues time independently — if a fast-bid round
takes 10 minutes and two players answer after 1 and 10 minutes, they are charged 1
and 10 minutes, so the players' total can legitimately exceed the wall clock.

Timestamps arrive as data on the move (Move.time, set by the viewer) and live in
the log rather than being read from the system clock inside the engine, so
replaying a game reproduces identical times — wrapper.replay() is used in
production by logSlice, so a Date.now() call in move() would corrupt the totals on
every replay. Engine-generated moves (AI, dropped players) carry no timestamp and
leave the clocks untouched, and stretches are clamped at >= 0 so clock skew between
players' browsers can never subtract time.

The live ticker lives inside PlayerBoard so the per-second update re-renders only
the player boards rather than the whole board SVG.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Keep the per-player clocks running across auto-played turns

moveAI submitted its moves without a timestamp, so updateClocks never ran for an
auto-played turn and no clock started. Anyone waiting after a bot or a dropped
player's auto-played turn therefore sat on an un-started clock reading zero — in a
game whose opening turns are all auto-played, every timer stayed at zero.

Stamp the AI's move so the clock chain stays unbroken. Reading the wall clock is
safe here: moveAI is a live move generator that is never re-run on replay (it is
already non-deterministic via chooseRandom) and the timestamp it produces is
written into the log, so replays re-apply the recorded value.

The opening move of a game still records no time — there is no earlier timestamp
to measure it against.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: John Gold <goldjohn6@gmail.com>
2026-07-19 17:45:35 -07:00
mmunson99
9c158057e2
Add a Cost per City row to the end-of-game stats popup (#106)
Shows what each city effectively cost a player: the house price plus the
connection cost paid to reach it, divided by the number of cities built. Sits
directly under the two rows it derives from (Spending: Cities and Spending:
Connections). Displayed to one decimal; a player with no cities shows "-" rather
than dividing by zero.

The table picked each cell's value through a nested ternary on the row index,
which a sixth row would have made unreadable, so the rows are now data-driven via
a spendingRows getter. Row order and every existing value are unchanged.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 17:38:12 -07:00
github-actions
a7920a9424 🔖 powergrid-viewer 1.11.14 2026-07-07 18:54:27 +00:00
github-actions
dd77bee496 🔖 powergrid-engine 1.15.14 2026-07-07 18:52:10 +00:00
goldjohn6
fb7594a356
Start the Manhattan deck's next cycle the moment it runs dry mid-round (#105)
Manhattan's power-plant market is driven by deck depletions, but the two
depletion transitions (first depletion -> reshuffle the recycle pile into a
fresh deck; second depletion -> open the whole market) only ran inside the
Bureaucracy lifecycle. A Manhattan deck routinely runs dry mid-round during
the auction, and when it did the market stalled: no reshuffle fired, the
buyable (actual) market decayed below four as plants were bought without a
replacement, and every big plant sat stranded on the recycle pile until the
end of the round.

Mike reported it on ManhattanJune28 -- "3 in the top row and 4 in the bottom,
the new deck should start, but it didn't." The stored game confirmed it:
stage 0, deck empty, ten plants on the recycle pile, players offered a
two-plant market (actualMarket [22,23], futureMarket [31,33,37,38]).

Fire the depletion transition the instant the deck empties, from the auction
refill path (addPowerPlant) and not only at Bureaucracy. A new helper,
applyManhattanDepletionOnEmptyDeck, reshuffles (first depletion) or collapses
the market (second depletion) but deliberately does not draw -- addPowerPlant
still owns the single post-buy refill, so the market cannot double-fill. The
Bureaucracy lifecycle is unchanged and stays the backstop for a deck that
empties during its own peel/refill.

The regression test replicates June28's exact market and fails without the fix
(the reshuffle never fires); a 25-game AI soak with a buyable-market
choice-point invariant went from 8-10 stalls per run to zero.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 11:49:49 -07:00
github-actions
8acd1ceb8d 🔖 powergrid-viewer 1.11.13 2026-07-04 19:14:03 +00:00
github-actions
17354e795d 🔖 powergrid-engine 1.15.13 2026-07-04 19:12:49 +00:00
goldjohn6
e84af934f2
Fix Manhattan all-buyable market overlap; describe the deck cycle in the rules dialog (#104)
* Fix Manhattan all-buyable market hiding its two biggest plants

The futureMarket-empty layout in PowerPlantMarket.vue assumed Step 3's
6-plant maximum: x wrapped modulo 3 and y was clamped to the second row,
so in Manhattan's second-depletion 8-plant market, cards 7 and 8 painted
exactly on top of cards 4 and 5. The market looked out of order (the
June 26 "44 after 50" report) and two plants were invisible, while the
stored engine market was correctly sorted the whole time (verified via
/api/gameplay ground truth). Wrap at 4 per row when the market holds
more than 6 plants, and widen the choose-highlight to match; standard
Step 3 positions are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Describe the Manhattan deck cycle in the rules dialog

The rules dialog said nothing about Manhattan's power plant market
lifecycle, and the Step 1 summary claimed the highest plant is removed
each Bureaucracy, which is wrong for Manhattan in every stage. Add the
full deck cycle (discard pile, first-depletion reshuffle,
biggest-under-deck, second-depletion all-buyable + smallest boxed) to
mapSpecificRules and make the Step 1 Bureaucracy line Manhattan-aware.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 12:11:06 -07:00
github-actions
090bc67c03 🔖 powergrid-viewer 1.11.12 2026-07-02 17:20:01 +00:00
github-actions
45eadf6cf3 🔖 powergrid-engine 1.15.12 2026-07-02 17:08:56 +00:00
goldjohn6
730b158212
Fix stale bid-calculator floor + AI discard picking illegal candidates (#103)
* Fix bid calculator showing a stale floor from the previous auction

The calculator initialized its value once in created() and never followed
minValue again. When a client resumes from coalesced updates (async games,
tab wake-ups), Vue reuses the component instance across auctions, so the
visor kept displaying the prior auction's floor — e.g. $24 pre-filled while
plant 26 was up for bid (NorthernEuropeJune20, fastBid).

- Key the Calculator by the auctioned plant so each auction mounts fresh
- Watch minValue and lift a stale value to the floor (never lowers a
  higher bid the player already dialed in, e.g. mid-auction outbids)

Server-side move validation always rejected such stale bids; this was
display-only.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix AI discard picking an illegal candidate

moveAI discarded powerPlants[0] blindly instead of choosing from the offered
candidates. On Australia the oldest-held card is often a uranium mine (plant
11 is a natural first buy), which is never a legal discard candidate — and
dropPlayer() auto-plays the pending prompt through moveAI when a player times
out, so the illegal pick threw inside the platform drop path. 14 of 45
regular-board Australia AI games hit it; 45/45 clean after the fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add AI-discard regression spec + Manhattan market sort-order guards

The regression spec reproduces the dropPlayer scenario (mine held first at a
forced discard) and fails on the unfixed engine with the exact live error.
The strengthened Manhattan lifecycle specs feed deliberately out-of-order
market inputs and assert the collapse/churn keeps the buyable market sorted
ascending — a tripwire for the out-of-order market observed live on June 24
(root cause still under investigation).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:56:43 -07:00
github-actions
c8d5e8f53a 🔖 powergrid-viewer 1.11.11 2026-06-30 13:50:06 +00:00
github-actions
db19d38067 🔖 powergrid-engine 1.15.11 2026-06-30 13:48:23 +00:00
mmunson99
ab559e0e17
Fix round 1 player order not updating after a contested/bonus auction (#102)
Round 1 starts in seating order and is reordered by the plants bought once the
auction ends (there are no cities yet). That reorder lived only in the uncontested
ChoosePowerPlant branch, so any round-1 auction that finished through another
completion path kept the seating order. Manhattan's discount-bonus purchase makes
this reachable in normal play: a buyer of the discounted plant stays eligible, so
round 1 can end via the contested-bid / bonus path, and players were left in
seating order instead of plant order (reported on ManhattanJune28).

Move the round-1 reorder into toResourcesPhase — the single funnel into the
resources phase — so every auction-completion path reorders. Baden-Württemberg
keeps its own every-round ordering there; later rounds are unaffected (their order
is set at round start).

Adds a deterministic Manhattan regression test (a contested round-1 auction that
previously left [0,1,2,3,4]) and confirms all existing full-game replays still
pass.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 06:46:16 -07:00
github-actions
daf79f3e7d 🔖 powergrid-viewer 1.11.10 2026-06-29 21:25:03 +00:00
github-actions
6b151c0641 🔖 powergrid-engine 1.15.10 2026-06-29 21:23:52 +00:00
mmunson99
838591a72e
Choose colors (#101)
* Add chooseColors option: players draft their colors at game start

When the chooseColors game option is set, each player picks their own color (in
seating order, one each) before play begins, instead of colors being assigned by
seat.

Engine changes:
- GameOptions.chooseColors, Phase.ColorSelection, GameState.colorDraft,
  Player.color, and a MoveName.ChooseColor move.
- The default palette moves to gamestate.ts as the single source of truth and is
  re-exported from engine.ts (engine.playerColors still works). factions() and the
  log name coloring now use player.color ?? playerColors[id], so unchosen players
  fall back to the default exactly as before.
- setup() starts in ColorSelection when chooseColors is set; finalizeColors() then
  hands off to the region draft if chooseRegions is also pending, otherwise to the
  auction. Color selection therefore runs before region selection when both are on.
- moveAI auto-picks a color for bots/dropped players.

Behavior is unchanged when the option is off (color stays undefined → default
palette). Adds tests for the draft flow, the default-off path, and the
chooseColors + chooseRegions ordering. All existing tests still pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Viewer: color draft UI for the chooseColors option

During the ColorSelection phase the current player gets a modal of the remaining
color swatches; clicking one drafts that color. The status bar prompts "Choose
your color". playerColors becomes a getter that overrides the default palette with
each player's drafted color (by id), so the board, player boards, and houses all
render in the chosen colors; with the option off it returns the default palette
unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 14:20:45 -07:00
github-actions
a47855d991 🔖 powergrid-viewer 1.11.9 2026-06-24 23:41:25 +00:00
github-actions
e1698c179a 🔖 powergrid-engine 1.15.9 2026-06-24 23:40:25 +00:00
goldjohn6
3016edab9e
Manhattan: fix discount-bonus double market refill + Step-1-only viewer cleanups (#100)
Follow-up to #99 (discount-plant bonus purchase), addressing two playtest
reports from Mike:

1. Buying the discounted plant while already at the plant limit grew the
   power plant market by one. The Site-1 auto-win bonus branch refilled the
   market unconditionally, but when the purchase forces a discard the discard
   handler also refills — two draws for one purchase. Now the bonus branch
   refills only when the buy did NOT exceed the plant limit, mirroring the
   deferred-refill logic used on every other auction path.

2. Manhattan runs only in Step 1, but the city-count tracker still outlined
   the (dead) Step-2 threshold tile, and the rules modal still listed Step 2
   and Step 3. Suppress the Step-2 tracker marker and the Step 2 / Step 3
   rules-modal sections for Manhattan.

- engine: Site-1 bonus branch refills only when not over the plant limit
- engine spec: regression test — an over-cap discount buy keeps the market at 8
- viewer: no citiesToStep2 marker, no Step 2/3 rules sections for Manhattan

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 16:38:09 -07:00
github-actions
339dbefe7f 🔖 powergrid-viewer 1.11.8 2026-06-24 22:43:00 +00:00
github-actions
3d8d30ec85 🔖 powergrid-engine 1.15.8 2026-06-24 22:41:28 +00:00
goldjohn6
69b68fb0a1
Manhattan: buying the discounted plant grants a second purchase (#99)
Implements the Manhattan rule (RIO 686): "If you buy the discounted power
plant, you can purchase another power plant during this phase."

The recharged discount (cheapest plant, minimum bid lowered to 1) was
already in place; this adds the extra purchase on top. The discount buyer
is simply kept eligible for the auction (skipAuction stays false), so the
existing turn machinery carries them for one more, optional purchase.
Round 1's mandatory-buy rule is relaxed for that bonus turn so it can be
declined (and so a buyer who cannot afford another plant is not soft-locked).
Whoever wins the discounted plant gets the bonus, initiator or outbidder.

- gamestate: new transient discountBonusPlayer
- endAuction: flag the discount winner; clear it once they buy again
- auto-win path: refill the market and re-prompt the buyer instead of
  ending the phase
- available-moves: offer Pass to the bonus buyer even in round 1
- manhattan.ts rules text + 2 specs (bonus fires and is declinable in
  round 1; no false bonus on a normal buy)

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 14:57:41 -07:00
github-actions
7df482b454 🔖 powergrid-viewer 1.11.7 2026-06-24 17:08:38 +00:00
github-actions
e5c2a5ddb5 🔖 powergrid-engine 1.15.7 2026-06-24 17:07:20 +00:00
goldjohn6
1bf9362825
Add Manhattan map (RIO 686 Bremen/Manhattan expansion) + Northern Europe Riga typo fix (#98)
* Manhattan S1: engine core (single region, flat-5 transit, custom deck)

Manhattan (RIO 686 Bremen/Manhattan expansion) engine layer:
- New maps/manhattan.ts: single region; one house per space at its printed
  building cost via slotCosts:[price]; a flat 5-Elektro-per-transit connection
  model via connectionCost:5 on every space; custom setupDeck (box the Step 3
  card + the 2-3P plants 20/22/37; opening market drawn from the <=15 plug
  pool); flat resupply with uranium live; startingResources [18,18,9,4]. The
  geometry is a placeholder 4x5 grid -- the real ~80-space board is Session 3.
- engine.ts: citiesToEndGameManhattan [18,17,17,15,14]; exclude Manhattan from
  the Step 2 trigger so the game stays in Step 1 (Step 3 card is boxed).
- available-moves.ts: refund the target space's own transit-5 (you pay its
  building cost, not a transit fee) -- reuses Bremen's connectionCost dijkstra.
- Register in maps[]/mapsRecharged[]; add 'Manhattan' to MapName.
- 3 specs: thresholds + Step-1 freeze; deck box/plug-pool/uranium; flat-5
  transit math.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Manhattan S2: market lifecycle + per-player space-blocking

Deck-depletion market lifecycle (peel-to-recycle -> reshuffle -> all-buyable -> box-smallest), held in Step 1 throughout; blockSpaces hook + G.blockedCities (transitable but unbuildable). 46 engine specs, AI-sim clean across player counts 2-6.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Manhattan S3: real ~80-space board (coords, prices, street adjacency)

Replaces the S1 placeholder grid with the actual Manhattan board, authored
from the clean board photo: 83 building spaces (M1..M83) with printed prices
(10-40) and orthogonal street adjacency (154 links), verified live against
the physical board with John.

- manhattan.ts: 83 cities + 154 connections; blockSpaces tier policy is now
  exact (price counts 40x6 35x8 30x10 25x13 20x14 15x15 10x17).
- engine.spec.ts: the two Manhattan mechanic tests (flat-5 transit, blocked-
  but-transitable) rewritten to derive their cases from the live map graph,
  so they hold as the board is tuned.
- Map.vue: Manhattan spaces render as small translucent price tiles (single
  house per space; no entry-cost circle since connection is a flat 5).

Fully connected (no soft-lock); 41/41 engine specs pass; tsc + lint clean.
Coordinates are raw photo pixels; viewer render config + real house pieces +
2p-6p playtests are S4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Manhattan S4: viewer framing, legible price tiles, centered houses, blocked-space styling

- manhattan.ts: render frame for a normal game — portrait viewBox 1480x1400,
  adjustRatio 1.15, mapPosition, and supplyPosition dropped clear of the board's
  southeast spaces (coords were raw photo pixels until now).
- Map.vue: enlarged, high-contrast price tiles (26px box, 17px bold price) so the
  build costs read for older players; blocked spaces (2-3P) now render as dark
  transit-only tiles, wired through the new blockedCities prop; Manhattan houses
  are centered on their space and enlarged so they fill the tile with no white.
- House.vue / ui-data.ts: optional per-piece scale prop (default 0.035; only the
  Manhattan branch overrides to 0.085, so every other map is untouched).
- Game.vue: pass G.blockedCities to the map.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Northern Europe: fix city name "Rica" -> "Riga"

Riga is the Latvian capital; "Rica" was a typo. Renames the enum key and value
and all its connection references.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 10:04:49 -07:00
github-actions
5a91fc2d8f 🔖 powergrid-viewer 1.11.6 2026-06-23 15:41:32 +00:00
github-actions
44677a9403 🔖 powergrid-engine 1.15.6 2026-06-23 15:40:11 +00:00
mmunson99
2a95fa12c3
Choose regionsAdd chooseRegions option: draft in-play regions instead of random selection (#97)
* Add chooseRegions option: draft in-play regions instead of random selection

When the chooseRegions game option is set, the regions in play are drafted by
the players at game start instead of being chosen randomly during setup.

Engine changes:
- GameOptions.chooseRegions, Phase.RegionSelection, GameState.regionDraft, and a
  MoveName.ChooseRegion move.
- setup() keeps the full map and enters the RegionSelection phase when
  chooseRegions is set and the map has more regions than are used (and the map
  isn't randomized). The map filtering + regionalPowerPlants swap are deferred to
  finalizeRegions(), which runs once the draft completes and hands off to the
  auction with the starting player to move.
- Players draft in seating order, repeating until enough regions are chosen
  (e.g. 2p picks in order 1st, 2nd, 1st). Picks are restricted to regions that
  keep the board connected, reusing the exact connectivity rules of the random
  selector (extracted into computeRegionGraph / regionPickable in available-moves
  as the single source of truth), with the existing UK & Ireland (fresh-landmass)
  and Australia (any-region) exceptions.
- moveAI auto-picks a legal region for bots/dropped players.

Existing seeded setup tests are unchanged (the random path refactor is
rng-equivalent). Adds tests covering the draft flow, 2p wrap order, connectivity
restriction, and replay determinism.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Viewer: region draft UI for the chooseRegions option

During the RegionSelection phase the current player picks regions by clicking the
map: every city in a pickable region is outlined in gold (shown regardless of the
help preference, since the draft can't proceed without it) and a click drafts
that whole region. The status bar prompts "Choose a region to play in (N of M)",
including on the very first pick before any moves are logged.

Map.vue gains a pickableRegions prop and emits pickRegion; a shared onCityClick
handler routes a click to either build or region-pick depending on phase.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: John Gold <goldjohn6@gmail.com>
2026-06-23 08:37:32 -07:00
github-actions
dd417af26e 🔖 powergrid-viewer 1.11.5 2026-06-18 02:26:02 +00:00
github-actions
e00ea3cded 🔖 powergrid-engine 1.15.5 2026-06-18 02:15:36 +00:00
goldjohn6
ebca2312b4
Japan: cap round 1 at two houses + clarify rules dialog (#96)
* Japan: cap round 1 at two houses (initial placement + free jump)

Round 1 building offered every starting city at slot-cost-only with no
check on how many a player already owned or whether the free jump was
spent, so a player could place a third, fourth, ... starting-city house
in round 1 for just the slot fee — effectively unlimited free jumps. The
rules allow at most two round-1 houses: the initial placement plus the
one free jump (auto-consumed on the second starting-city build).

Gate the round-1 starting-city offer on !player.usedFreeJump: once the
jump is spent no further round-1 builds are offered. The skipper path
(0 houses in round 1) is unaffected — the initial placement never
consumes the jump, so a player who passes in round 1 still places their
first house in a starting city in round 2 and keeps the jump.

Adds regression tests: round-2-first-house restriction for a round-1
skipper, keep-then-spend of the jump in that case, and the round-1 cap.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Japan: rewrite map rules dialog for clarity

Restructure the mapSpecificRules text to match how the rules actually
play out: round-1 build count (0-2), the first house always landing in a
starting city (round 1 or later), the free jump being limited to the six
starting cities and auto-used on a second round-1 build, the Step 3 third
spot, and the X markers for limited-slot cities.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:07:10 -07:00
github-actions
caeac65476 🔖 powergrid-viewer 1.11.4 2026-06-16 18:56:34 +00:00
github-actions
71ec52ab64 🔖 powergrid-engine 1.15.4 2026-06-16 18:47:40 +00:00
goldjohn6
dd56a60c15
Fix Japan free jump (track explicitly, not via topology) + clarify Bremen rules dialog (#95)
* Fix Japan free jump: track usage explicitly, not via network topology

Free-jump availability was gated on countNetworks(ownedCities) < 2 as a
proxy for "has the player started a second network". But Power Grid networks
connect *through* unowned cities, so a single intended network routinely
shows as multiple components — wrongly hiding the free jump even though the
player never spent it (Sapporo unreachable while the indicator still showed
the jump as available). Prior fixes (#89, #94) layered more detection
heuristics on top; this removes the proxy and relies solely on the explicit
player.usedFreeJump flag.

- available-moves: offer the jump whenever !usedFreeJump
- undo: return the jump only when the undone build was the one that spent it
  (a round-1 second starting-city build, or a freeJump:true move), fixing a
  latent bug where undoing any normal build could hand the jump back once the
  network had become fully connected
- remove the now-unused countNetworks import
- add regression tests for both availability and post-use suppression

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Bremen: clarify asymmetric district-cost example, drop confusing river note

The flat district-cost connection rules confused players, especially the
direction-dependent (asymmetric) cost. Add a short worked example to the
in-game rules dialog. Also remove the "Weser and Lesum rivers can be crossed
without extra cost" line: the online map shows no rivers, so the note caused
confusion rather than clarity (the zero-cost crossings remain in the map
data and code comments).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 11:40:20 -07:00
github-actions
0885b2db33 🔖 powergrid-viewer 1.11.3 2026-06-15 18:36:17 +00:00
github-actions
e90e4e1111 🔖 powergrid-engine 1.15.3 2026-06-15 18:34:50 +00:00
mmunson99
ef5ffb2f2a
Fix Japan free jump indicator and clarify map rules (#94)
Fix the free-jump indicator showing a jump as "used" when it wasn't:
playerHasUsedFreeJump previously inferred usage from network topology
(countNetworks >= 2), but countNetworks only traverses a player's own
cities, so any two non-adjacent owned cities looked like two separate
networks even when connected via the normal map. Replace that heuristic
with a log scan that only counts an explicit Build move recorded with
freeJump: true, plus the authoritative player.usedFreeJump engine flag.

Also reframe the Japan rules text as "one network with one free jump"
rather than "two separate networks", which better matches the mechanic.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 11:32:55 -07:00
github-actions
2604afcf87 🔖 powergrid-viewer 1.11.2 2026-06-15 01:12:21 +00:00
github-actions
782a250faf 🔖 powergrid-engine 1.15.2 2026-06-15 01:11:09 +00:00
mmunson99
e3fb40cdb8
Improve free jump detection: add log scan as third fallback (#89)
* Improve free jump detection: add log scan as third fallback

The topology check misses cases where the free-jumped city is reachable
via the normal network (e.g. Sapporo is connected to the mainland via
Hakodate-Admori). Scan the game log for any Build move with
freeJump:true by the player — that flag is stored in the log even on
older server builds that don't track usedFreeJump in engine state.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Update Japan map rules text with round 1 and X-marker explanations

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Remove log scan fallback from free jump detection

Engine flag and topology check are sufficient now that PR #85 is merged.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix lint: use single quotes in japan.ts mapSpecificRules

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix prettier-check: double-quote japan.ts rules strings containing apostrophes

Prettier (singleQuote: true) flips a string to double quotes when it contains
more single quotes than double quotes, to avoid escaping. The two expanded
mapSpecificRules strings used escaped single quotes ('10', 'X'), which the
prettier-check CI job rejects. Use double-quoted form so the check passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix lint/prettier quote deadlock in japan.ts: drop inner quote marks

ESLint (quotes: single) requires single quotes; Prettier flips a string to
double quotes when it contains apostrophes, to avoid escaping. The two
expanded mapSpecificRules strings used '10' and 'X', making the two checks
mutually unsatisfiable. Remove the inner quote marks so the single-quoted
strings need no escaping, satisfying both prettier-check and eslint.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: John Gold <goldjohn6@gmail.com>
2026-06-14 18:10:09 -07:00
github-actions
40cd018673 🔖 powergrid-viewer 1.11.1 2026-06-12 22:33:43 +00:00
github-actions
11c1d9c2c2 🔖 powergrid-engine 1.15.1 2026-06-12 22:32:24 +00:00
goldjohn6
111e121429
Bremen: $7/$8 market spaces hold two cubes each; Korea-North-style market render (#93)
The printed Bremen board's resource track has only two spaces per resource
at $7 and $8 (three everywhere else), so a full market is 22 cubes per
resource -- exactly the in-play supply (2 of each go back in the box).
Spotted by Mike after the initial map landed.

- engine: per-cube price arrays for coal/oil/garbage (22 slots); starting
  market corrected to 22/16/16 (oil & garbage fill $3-$8, 6 in reserve)
- viewer: Bremen renders like Korea's North table -- three resource rows,
  no uranium row or hollow uranium cubes, no $10-$16 corner spaces
- spec: lock in track shape and opening market fill

Improvement reported by Mike. Map by John and Cici.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 15:30:58 -07:00
github-actions
35172ceed7 🔖 powergrid-engine 1.15.0 2026-06-11 07:37:52 +00:00
github-actions
1a25ab7f1d 🔖 powergrid-viewer 1.11.0 2026-06-11 07:29:49 +00:00
goldjohn6
5ad940d1f0
Add Bremen map / UK & Ireland step2 jump fix / North America city nudges (#92)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 08:57:06 +02:00
github-actions
c87ba88ed7 🔖 powergrid-viewer 1.10.1 2026-06-03 22:03:28 +00:00
github-actions
cf9a265b88 🔖 powergrid-engine 1.14.1 2026-06-03 22:01:34 +00:00
goldjohn6
99246dd3ad
UK & Ireland: prevent region soft-lock by keeping each landmass internally connected (#91)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 00:00:57 +02:00
github-actions
39447f2f78 🔖 powergrid-viewer 1.10.0 2026-06-02 09:12:26 +00:00
github-actions
5395446671 🔖 powergrid-engine 1.14.0 2026-06-02 08:54:23 +00:00
goldjohn6
2e1f50edb8
Add Australia map, Europe setup-deck + spacing fixes, recharged 2P deck-reduction fix (#90)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 10:53:38 +02:00
github-actions
5d9c9464df 🔖 powergrid-viewer 1.9.8 2026-05-27 18:20:40 +00:00
goldjohn6
7d2a4a7156
Northern Europe: fix cities clipped below the map and covered by resupply (issue #87) (#88)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 20:19:58 +02:00
github-actions
063d5e4183 🔖 powergrid-viewer 1.9.7 2026-05-26 16:03:45 +00:00
github-actions
baad7d9bf1 🔖 powergrid-engine 1.13.6 2026-05-26 16:02:25 +00:00
goldjohn6
9771e7ef6d
Northern Europe: visibility fixes and plant 18 fuel-type correction (#86)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 18:01:42 +02:00
github-actions
e306748ceb 🔖 powergrid-viewer 1.9.6 2026-05-25 13:26:20 +00:00
github-actions
52199180f6 🔖 powergrid-engine 1.13.5 2026-05-25 13:22:56 +00:00
fc4db3e01e japan free jump 2026-05-25 13:20:16 +00:00
Eliott C.
a80cf7ab6f
Merge branch 'master' into master 2026-05-25 12:43:18 +02:00
Mike Munson
587bd26ea1 Fix crash when city name not found in map during building phase
Guard against cityData being undefined in toBuild.forEach (triggers
'cannot read transregional of undefined' on games where the stored map
and current map code are out of sync). Also guard dijkstra against a
missing starting node. Both cases now gracefully mark the city as
unreachable (price 9999) instead of crashing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 18:33:18 -07:00
Mike Munson
dac774525b Fix free jump indicator for games started before usedFreeJump was tracked
Fall back to network-topology detection (countNetworks >= 2) when
player.usedFreeJump is undefined, so the indicator correctly shows
the jump as spent on existing games where the engine flag was never set.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 18:17:20 -07:00
github-actions
6d091dea2d 🔖 powergrid-viewer 1.9.5 2026-05-22 08:53:00 +00:00
github-actions
51abc0bbd5 🔖 powergrid-engine 1.13.4 2026-05-22 08:51:36 +00:00
mmunson99
c84b954b61
Japan update (#84)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 10:50:49 +02:00
Mike Munson
bf8e45d49c Add Japan free jump explicit choice dialog
- Player now chooses whether to use the free jump when clicking a starting
  city in round 2+: a modal offers "Use Free Jump" vs "Pay Full Price"
  (full price option shown only when the city is also reachable normally)
- Round 1 second starting-city build still automatically consumes the jump
- Engine detects free jump via explicit freeJump flag on the move rather
  than network topology inference, making detection reliable
- AI players automatically take the cheapest (free jump) option as before
- Adds freeJump?: boolean to MoveBuild data and AvailableMoves Build type

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 14:15:08 -07:00
Mike Munson
968a6c4ce1 Fix free jump detection: check network count before building
Check countNetworks before pushing the city so we only set usedFreeJump
when the free jump override was actually in effect (player had < 2 networks).
Previously a normal paid build into a non-adjacent starting city could
incorrectly consume the flag.

Viewer now uses only the engine flag instead of recomputing topology,
which had false positives when cities were connected via unowned
intermediate cities on the map.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 14:15:08 -07:00
Mike Munson
c2cd23df7a Compute free jump status from network topology instead of engine flag
Viewer now checks whether a player has 2+ disconnected networks directly
from their city list, so the indicator works correctly for in-progress
games and any state where usedFreeJump wasn't set by the engine.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 14:15:08 -07:00
Mike Munson
55d074a6e6 Add Japan Free Jump indicator showing per-player status
Track usedFreeJump on each player when they start a second disconnected
network in Japan. Render a house-per-player indicator in the top area
of the SVG; the house fades when the player has used their free jump.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 14:15:08 -07:00
Mike Munson
04bc3a9cd8 Fix transregional slot limits and add Japan starting city label
- Fix transregional cities to respect slotCosts/stepSlots (BW [15,20]
  cities now correctly allow only 1 player in step 2)
- Add bold "10" label at bottom-left of Japan starting cities to
  indicate the second 10-Elektro slot available in steps 1 and 2

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 14:15:07 -07:00
Mike Munson
f05187c62b Fix transregional cities to respect slotCosts and stepSlots
The transregional code path was using hardcoded slot limits (othersCount
== G.step) and hardcoded prices (15/20), ignoring slotCosts and stepSlots
entirely. BW's five transregional [15,20] cities were allowing 2 players
in step 2 instead of 1. Now uses stepSlots/slotCosts when defined, falling
back to the original behaviour for standard transregional cities.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 14:15:07 -07:00
github-actions
09d0775598 🔖 powergrid-viewer 1.9.4 2026-05-19 08:31:26 +00:00
goldjohn6
cc3b426ca8
Korea: enlarge map for better visibility (#83)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 10:30:40 +02:00
github-actions
bd984b6e28 🔖 powergrid-viewer 1.9.3 2026-05-18 20:11:53 +00:00
github-actions
a864c6fc35 🔖 powergrid-engine 1.13.3 2026-05-18 20:09:56 +00:00
goldjohn6
ca3a751b43
Fix Northern Europe uranium restriction and Europe deck reduction (#82)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 22:01:35 +02:00
github-actions
bd7a541aed 🔖 powergrid-viewer 1.9.2 2026-05-17 10:05:42 +00:00
github-actions
a8000dea44 🔖 powergrid-engine 1.13.2 2026-05-17 10:04:01 +00:00
goldjohn6
4c0f2b3506
Soak test and misc fixes (#81)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 12:02:47 +02:00
github-actions
da299b4afb 🔖 powergrid-viewer 1.9.1 2026-05-16 23:02:53 +00:00
github-actions
e531d47115 🔖 powergrid-engine 1.13.1 2026-05-16 23:01:25 +00:00
mmunson99
bbf8a50731
Japan recharged and Baden plant removal fix (#80)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 01:00:51 +02:00
goldjohn6
8a8a93d7af
Fix Northern Europe plant 26 and UK & Ireland 2P step2 trigger (#79)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 20:42:27 +02:00
github-actions
608f963666 🔖 powergrid-viewer 1.9.0 2026-05-15 17:43:34 +00:00
github-actions
3f543ec83f 🔖 powergrid-engine 1.13.0 2026-05-15 17:37:38 +00:00
mmunson99
37f14a722e
Add Japan map and Baden-Württemberg special rules (#78)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 19:36:49 +02:00
goldjohn6
240ea149d8
Add smoke tests for Korea and Northern Europe map setup (#76)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-14 20:50:40 +02:00
github-actions
f309961aa7 🔖 powergrid-engine 1.12.1 2026-05-14 18:48:45 +00:00
c5c35e79e4 Clearer error message on unfound map 2026-05-14 20:47:53 +02:00
github-actions
c22a81d533 🔖 powergrid-viewer 1.8.0 2026-05-14 16:20:35 +00:00
github-actions
88eca7d4a8 🔖 powergrid-engine 1.12.0 2026-05-14 16:18:43 +00:00
goldjohn6
96072e3219
Add Europe, North America, South Africa, and UK & Ireland maps (#75)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-14 18:15:47 +02:00
github-actions
b571e9eeef 🔖 powergrid-viewer 1.7.0 2026-05-11 11:14:25 +00:00
github-actions
6835643244 🔖 powergrid-engine 1.11.0 2026-05-11 11:12:25 +00:00
goldjohn6
8006269459
Add Northern Europe and Korea maps (#74)
* Add Northern Europe map

- Enable northerneurope.ts with resupply table (from official rulebook),
  starting resources (coal/oil at 3E, garbage at 5E, uranium at 7E),
  Portrait layout, and nuclear restriction rules
- Add regionalPowerPlants field to GameMap interface and engine swap logic
  so each chosen region's 2 replacement power plant cards are applied
  after region selection at game setup
- Register Northern Europe and Baden-Wurttemberg in MapName type
- Fix viewer serve/build scripts for Node 17+ OpenSSL compatibility

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add Korea engine support with dual-market mechanic

Korea has two separate resource markets (North + South). On a buying
turn, the player picks one side and buys all their resources from that
side; next turn they may pick the other side. Used cubes return to a
shared supply pool; during bureaucracy, North restocks first, then South
from whatever remains.

- Schema: GameState/GameMap fields for north markets, prices, resupply
- Korea map data: full resupply tables, custom per-side price arrays,
  layout, mapSpecificRules text
- Engine: setup, side-locked buying via chosenSide, pass clearing,
  side-aware undo, bureaucracy restocking from shared supply
- North has no uranium track (nuclear ban encoded structurally)

Viewer not yet updated; Korea is engine-complete but won't render
correctly until the viewer is taught about the parallel north markets.

All 11 existing engine tests still pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add Korea viewer dual-market UI and fix engine resupply

The Korea engine commit (1260da2) added the dual-market rules but the
viewer rendered nothing for the North side and a couple of engine edge
cases broke once the markets were exercised end-to-end.

- Resources.vue: render North market above the existing South market
  when the gameState carries Korea-shape data. Cube positions are
  computed from each side's prices array so variable slot counts are
  preserved (South coal [1,1,1,1,2,2,2,2], North coal [2,2,2,2,1,1,1,1],
  oil/garbage 1 or 2 per space, etc.). South uranium $1-$8 moves to a
  separate row so it no longer overlaps oil. Per-side blue 'buyable'
  highlight follows the available moves.
- korea.ts: taller viewBox and lowered supplyPosition to make room for
  the stacked markets above the bottom edge. adjustRatio set to 0.22
  so the source city coordinates fit the canvas.
- Game.vue + Piece type: buyableResources prop and the BuyResource move
  carry the side tag end-to-end; cube objects know their own side.
- engine.ts: undo of the last BuyResource now clears chosenSide so the
  player can switch sides if they revert their only buy. The previous
  behavior left them locked indefinitely.
- engine.ts: bureaucracy resupply now also caps by remaining market
  capacity (prices.length - market). Korea's smaller markets - 12-slot
  North coal, 8-slot North oil/garbage - otherwise overflowed past
  their slot count after one round of resupply, breaking the price
  lookup at coalPrices[length - market] (negative index, undefined
  price, buy silently filtered out).

All 11 existing engine tests still pass.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* Fix Korea rules dialog and correct supply pool description

PR #74 review feedback from Mike:

- Rules dialog now shows both North and South resupply per step.
  Adds GameState.resourceResupplyNorth (populated only for Korea)
  and renders inline as "[..] (S), [..] (N)" in Game.vue.
- mapSpecificRules text gets line breaks and a factual correction:
  the supply pool is shared, not independent per market.
- Game.vue rules <span> switches to white-space: pre-wrap so long
  per-map descriptions wrap instead of overflowing horizontally.
- self-contained.ts dev sandbox set to Korea/recharged with
  randomizeMap=false so reviewers don't hit the random-map quirk
  that renames cities to "Red 1", "Yellow 2", etc.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 13:11:42 +02:00
Eliott C.
c7ab44e91d
Remove Gitpod badge from README
Removed Gitpod badge from README.
2026-04-27 12:34:47 +02:00
github-actions
c82da25555 🔖 powergrid-viewer 1.6.0 2026-04-27 09:32:24 +00:00
f075d0aefb Enable legacy OpenSSL provider for viewer build
vue-cli-service pulls in webpack 4, which calls createHash('md4').
OpenSSL 3 (bundled with Node >= 17) removed MD4, so the build now
fails with ERR_OSSL_EVP_UNSUPPORTED on the Node 24 runner. Setting
NODE_OPTIONS=--openssl-legacy-provider re-enables the legacy provider
just for the publish step, which is the documented workaround until
the viewer is migrated off webpack 4.

Made-with: Cursor
2026-04-27 11:31:32 +02:00
github-actions
0376b99536 🔖 powergrid-engine 1.10.0 2026-04-27 09:25:29 +00:00
github-actions
45dd262086 🔖 powergrid-engine 1.9.9 2026-04-27 09:24:24 +00:00
c0e5a67adf Publish under unscoped names and fix repository metadata
- Stop rewriting package names to @boardgamers/* before publish: trusted
  publishing on npmjs.com is configured for the original unscoped
  powergrid-engine / powergrid-viewer packages, so the rewrite caused
  E404 because the OIDC exchange has no trust relationship for the
  scoped names.
- Update each package.json's repository, homepage and bugs fields to
  point at boardgamers/powergrid (with a directory subpath) instead of
  the now-defunct LucasAMello/powergrid-engine fork.
- Switch the publish step to pnpm@latest via npx so we get both OIDC
  trusted-publishing support (pnpm >= 10.16) and the workspace:
  protocol rewrite that npm publish does not perform, without bumping
  the repo-wide packageManager.

Made-with: Cursor
2026-04-27 11:23:14 +02:00
mmunson99
ec23d9c63f
Add Baden-Württemberg map with all 5 rule variants (#73)
Co-authored-by: coyotte508 <coyotte508@protonmail.com>
2026-04-27 11:12:22 +02:00
github-actions
283e5b8eaa 🔖 powergrid-viewer 1.5.5 2025-08-09 21:33:20 +00:00
aae94d105f add package.json to .gitignore 2025-08-09 21:32:06 +00:00
github-actions
b2acca231b 🔖 powergrid-engine 1.9.8 2025-08-09 21:28:47 +00:00
771b8fd071 backcompat 2025-08-09 21:27:50 +00:00
github-actions
202650b96f 🔖 powergrid-viewer 1.5.4 2025-08-09 21:19:59 +00:00
github-actions
c78a37ab8a 🔖 powergrid-engine 1.9.7 2025-08-09 21:15:55 +00:00
317bc7dde7 update viewer publish 2025-08-09 21:14:46 +00:00
c82c1b978f update engine-publish 2025-08-09 21:12:39 +00:00
Eliott C.
abdcd7354a
Merge pull request #71 from mtpauly/resource-pass-plant-check 2025-08-09 23:02:39 +02:00
d33f122727 also revert back to older node 2025-08-09 21:01:14 +00:00
edfd73c381 Merge remote-tracking branch 'origin/master' into pr/mtpauly/71 2025-08-09 20:57:10 +00:00
20f679f283 prettier 2025-08-09 20:56:35 +00:00
3dcf4556ad revert to older package manager 2025-08-09 20:54:47 +00:00
1c3c92219b add devcontainer 2025-08-09 20:52:51 +00:00
69b6d04492 Revert "add devcontainer and specify pnpm version"
This reverts commit 5cf4a446d0.
2025-08-09 20:52:36 +00:00
2c4c54f569 fix CI? 2025-08-09 20:42:38 +00:00
3915026164 add ignore files for prettier 2025-08-09 20:26:48 +00:00
8a1340e09c Merge remote-tracking branch 'origin/master' into pr/mtpauly/71 2025-08-09 20:25:22 +00:00
e490b9d604 refactor a bit 2025-08-09 20:18:45 +00:00
71dd8b7a40 update publish scripts 2025-08-09 20:11:15 +00:00
Eliott C.
f7a33d51c8
Merge pull request #72 from mtpauly/benelux-resupply-correction 2025-08-09 22:09:20 +02:00
2a791bf0a1 comments 2025-08-09 20:07:14 +00:00
5cf4a446d0 add devcontainer and specify pnpm version 2025-08-09 20:00:50 +00:00
mtpauly
f851144c4f Correct Benelux resupply matrix entries
Adjust several resupply entries in the Benelux map to reflect
intended flows and eliminate inaccuracies. The previous values led to
incorrect resource availability during certain phases, which could
produce unintended balance effects. This aligns the matrix with the
expected design for resupplying cities in the region.
2025-08-03 17:56:26 -07:00
mtpauly
c1c13a88df Confirm on pass if insufficient resources
Players can no longer accidentally skip buying resources while lacking
enough to power all plants. When attempting to pass during the Resources
phase without sufficient resources, the UI now prompts for confirmation.

This helps prevent accidental misplays and makes the consequence of
passing explicit. The sufficiency check accounts for hybrid plants that
can use either coal or oil, ensuring the prompt reflects real options.
2025-08-03 17:44:45 -07:00
github-actions
dcfbf31636 Viewer v1.5.3
Some checks are pending
All / prettier (push) Waiting to run
2024-07-15 12:55:01 +00:00
github-actions
9bb060e3ae Engine v1.9.6
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2024-07-15 12:52:18 +00:00
Eliott C
9b1245d4e5
Merge pull request #66 from tjohnson314/master
Fix Central Europe map
2024-07-15 14:51:30 +02:00
Timothy Johnson
4c57cd7b65
Merge branch 'boardgamers:master' into master 2024-07-13 22:07:21 -07:00
Tim Johnson
eae10b8cd4 Merge branch 'master' of https://github.com/tjohnson314/powergrid 2024-07-11 00:30:42 -07:00
Tim Johnson
b0c29ab71b Fix starting resources in Central Europe 2024-07-11 00:30:27 -07:00
Tim Johnson
bf7ec00932 Fix rules for bidding on uranium plants in Central Europe 2024-07-11 00:30:04 -07:00
github-actions
4392a50782 Viewer v1.5.2 2024-05-23 09:59:51 +00:00
github-actions
d804caa3bd Engine v1.9.5
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2024-05-23 09:57:29 +00:00
Eliott C
fd9f2f9df2
Merge pull request #65 from tjohnson314/master
Fix deck setup for India map
2024-05-23 11:56:31 +02:00
Timothy Johnson
adfab5dbe3
Merge branch 'boardgamers:master' into master 2024-05-23 00:59:51 -07:00
Tim Johnson
f509e8a915 Merge branch 'master' of https://github.com/tjohnson314/powergrid 2024-05-23 00:57:03 -07:00
Tim Johnson
533fa31c44 Fix deck setup for India map 2024-05-23 00:56:45 -07:00
github-actions
18ab61365b Engine v1.9.4
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2024-02-18 21:13:38 +00:00
Eliott C
ec983d93df
Merge pull request #63 from tjohnson314/master
Fix deck setup for France map
2024-02-18 22:12:54 +01:00
Timothy Johnson
e684bb6d7a
Merge branch 'boardgamers:master' into master 2024-02-17 23:41:40 -08:00
Tim Johnson
963faccdf4 Merge branch 'master' of https://github.com/tjohnson314/powergrid 2024-02-17 23:38:50 -08:00
Tim Johnson
f170d84e02 Fix deck setup for France map 2024-02-17 23:38:33 -08:00
github-actions
7a9258f3e3 Viewer v1.5.1 2024-02-05 14:04:11 +00:00
github-actions
5f24951524 Engine v1.9.3
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2024-02-05 13:53:17 +00:00
Eliott C
5f4b46c2b4
Merge pull request #62 from tjohnson314/master
Add missing connection to Russia map
2024-02-03 16:52:26 +01:00
Timothy Johnson
682a9cbbab
Merge branch 'boardgamers:master' into master 2024-01-18 21:32:34 -08:00
Tim Johnson
2b41d30804 Add missing connection to Russia map 2024-01-18 21:31:04 -08:00
github-actions
8a4d42d086 Engine v1.9.2
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2023-12-13 02:10:21 +00:00
Eliott C
8b87e722ca
Merge pull request #58 from tjohnson314/master
Enable Central Europe map
2023-07-11 12:02:46 +02:00
Tim Johnson
48739d2934 Fix order of imports 2023-07-10 21:53:58 -07:00
Tim Johnson
6abb4333fe Add garbage discount for players in Wien 2023-07-04 23:48:22 -07:00
Tim Johnson
90879d3cd1 Add restrictions for uranium plants 2023-07-03 02:04:12 -07:00
Tim Johnson
87626ced15 Begin adding Central Europe map 2023-07-02 23:28:02 -07:00
github-actions
d9583c19ed Engine v1.9.1
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2023-06-14 15:46:13 +00:00
Lucas Mello
d3e161e748
Merge pull request #57 from tjohnson314/master
Fix bugs in Russia map
2023-06-14 12:43:49 -03:00
Timothy Johnson
6bf5f38815
Merge branch 'boardgamers:master' into master 2023-06-14 00:25:53 -07:00
Tim Johnson
8e57cdf6fe Fix map edges, and fix bug with pass while no plants in market 2023-06-14 00:25:16 -07:00
github-actions
a8fdf85983 Viewer v1.5.0 2023-06-04 19:13:13 +00:00
Lucas Mello
7a9f30660e
Update package.json 2023-06-04 16:10:55 -03:00
github-actions
576b705a4e Engine v1.9.0
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2023-06-04 19:00:26 +00:00
Lucas Mello
7ae89f7494
Merge pull request #56 from tjohnson314/master
Enable Russia map
2023-06-04 15:57:37 -03:00
Tim Johnson
f10a8aca7a Fix lint and prettier issues 2023-05-31 21:04:32 -07:00
Tim Johnson
acf62e50ec Merge branch 'master' of https://github.com/tjohnson314/powergrid 2023-05-31 20:57:36 -07:00
Tim Johnson
597d7cbbe8 Fix highlight for actual market 2023-05-31 20:57:19 -07:00
Timothy Johnson
210701a84d
Merge branch 'boardgamers:master' into master 2023-05-30 23:18:41 -07:00
Tim Johnson
60a4bc724d Remove smallest plant after first pass 2023-05-30 23:17:59 -07:00
Tim Johnson
d9a67ce192 Fix discount token 2023-05-25 01:17:01 -07:00
Tim Johnson
93a73004e6 Adjust city location for legibility 2023-05-24 15:05:45 -07:00
Tim Johnson
877fcf1f41 Implement deck setup for Russia 2023-05-24 01:33:09 -07:00
Tim Johnson
b315298f2d First set of changes for Russia map 2023-05-23 00:11:06 -07:00
github-actions
dd023c9de8 Viewer v1.3.6 2023-05-22 14:14:34 +00:00
512 changed files with 152857 additions and 10046 deletions

View file

@ -0,0 +1,24 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/typescript-node
{
"name": "Node.js & TypeScript",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/typescript-node:1-22-bookworm",
// Features to add to the dev container. More info: https://containers.dev/features.
"features": {
"ghcr.io/joshuanianji/devcontainer-features/mount-pnpm-store:1": {}
}
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install",
// Configure tool-specific properties.
// "customizations": {},
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

View file

@ -4,11 +4,17 @@ on:
workflow_dispatch:
inputs:
newversion:
description: 'Semantic Version Bump Type (major minor patch)'
description: 'Semantic Version Bump Type'
type: choice
required: true
default: patch
options:
- patch
- minor
- major
env:
node_version: 14
node_version: 24
defaults:
run:
@ -17,24 +23,29 @@ defaults:
jobs:
version_and_release:
runs-on: ubuntu-latest
permissions:
contents: write
id-token: write
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v6
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: sed -i 's:powergrid-engine:@boardgamers/powergrid-engine:' package.json
- run: pnpm publish --access public --no-git-checks .
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: |
PACKAGE_VERSION=$(node -p "require('./package.json').version")
BUMPED_VERSION=$(node -p "require('semver').inc('$PACKAGE_VERSION', '${{ github.event.inputs.newversion }}')")
# Update package.json with the new version
node -e "const fs = require('fs'); const package = JSON.parse(fs.readFileSync('./package.json')); package.version = '$BUMPED_VERSION'; fs.writeFileSync('./package.json', JSON.stringify(package, null, '\t') + '\n');"
git add .
git commit -m "🔖 powergrid-engine $BUMPED_VERSION"
# pnpm 10.16+ supports OIDC trusted publishing; use it directly to avoid bumping the
# repo-wide packageManager (currently pnpm 7) which would force a lockfile rewrite.
- run: npx -y pnpm@latest publish --access public --no-git-checks
- run: git push --follow-tags

View file

@ -9,6 +9,9 @@ on:
- '.github/workflows/engine-test.yml'
- 'engine/**'
permissions:
contents: read
defaults:
run:
working-directory: engine
@ -17,13 +20,11 @@ jobs:
lint_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: '12'
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
node-version: '14'
- run: corepack enable
- run: pnpm install
- run: pnpm build
- run: pnpm lint

View file

@ -1,14 +1,17 @@
name: All
on: [pull_request, push]
permissions:
contents: read
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@v6
- uses: actions/setup-node@v6
with:
version: 5.17.1
node-version: '22'
- run: corepack enable
- run: pnpm install
- run: pnpm run prettier-check

View file

@ -4,11 +4,17 @@ on:
workflow_dispatch:
inputs:
newversion:
description: 'Semantic Version Bump Type (major minor patch)'
description: 'Semantic Version Bump Type'
type: choice
required: true
default: patch
options:
- patch
- minor
- major
env:
node_version: 14
node_version: 24
defaults:
run:
@ -17,24 +23,34 @@ defaults:
jobs:
version_and_release:
runs-on: ubuntu-latest
permissions:
contents: write
id-token: write
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v6
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: sed -i 's:"powergrid-viewer":"@boardgamers/powergrid-viewer":' package.json
- run: pnpm publish --access public --no-git-checks .
- run: |
PACKAGE_VERSION=$(node -p "require('./package.json').version")
BUMPED_VERSION=$(node -p "require('semver').inc('$PACKAGE_VERSION', '${{ github.event.inputs.newversion }}')")
# Update package.json with the new version
node -e "const fs = require('fs'); const package = JSON.parse(fs.readFileSync('./package.json')); package.version = '$BUMPED_VERSION'; fs.writeFileSync('./package.json', JSON.stringify(package, null, '\t') + '\n');"
git add .
git commit -m "🔖 powergrid-viewer $BUMPED_VERSION"
# pnpm 10.16+ supports OIDC trusted publishing and rewrites the workspace:../engine
# dependency to a real version range; use it directly to avoid bumping the repo-wide
# packageManager (currently pnpm 7) which would force a lockfile rewrite.
# 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

@ -11,6 +11,9 @@ on:
- '.github/workflows/viewer-test.yml'
- 'viewer/**'
permissions:
contents: read
defaults:
run:
working-directory: viewer
@ -18,15 +21,24 @@ defaults:
jobs:
test_and_build:
runs-on: ubuntu-latest
env:
NODE_OPTIONS: --openssl-legacy-provider
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
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
# - run: pnpm test
- run: pnpm build
- run: pnpm --dir ../engine build
- run: pnpm package
- run: pnpm test:unit
- run: pnpm test:tutorial
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm test:browser
- run: pnpm test:tutorial:browser
- run: node scripts/premove-smoke.mjs

16
.gitignore vendored
View file

@ -1 +1,17 @@
node_modules
# Dev-only board photos used by the coord-picker (see GameMap.devBackdrop).
viewer/public/*.jpg
viewer/public/*.jpeg
viewer/public/*.png
.pnpm-store
ai/private-data/
ai/runs/
ai/.venv/
source-bundle/
ai/__pycache__/
ai/strong/__pycache__/
serving-bundle/

18
.prettierignore Normal file
View file

@ -0,0 +1,18 @@
pnpm-lock.yaml
viewer/pnpm-lock.yaml
engine/pnpm-lock.yaml
viewer/package.json
engine/package.json
.pnpm-store/
**/dist/
# Generated reports and geographic data preserve the generators' formatting.
ai/strong/handoff/*.json
viewer/scripts/geography/*.json
viewer/src/geography/assets/*.json
viewer/src/geography/names.json
viewer/src/geography/loaders.ts
# Achievement artwork manifest (written by scripts/generate-achievement-art.py) and release receipts, kept as recorded.
art/achievements/manifest.json
docs/releases/*.json

15
AGENTS.md Normal file
View file

@ -0,0 +1,15 @@
# Agent instructions
## 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 @@
# Power Grid
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/boardgamers/powergrid)
Mono repo containing the viewer & the engine for Power Grid
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/powergrid)
Reach out to us if you want to contribute.
## Install
@ -27,3 +27,5 @@ npm run serve
```
It will use the engine in its sibling folder
Viewer releases: see [uploading the complete viewer build](docs/viewer-publishing.md).

89
ai/README.md Normal file
View file

@ -0,0 +1,89 @@
# Powergrid AI — first executable baseline
> Research paused. Start with the [4 October 2026 handoff](RESUME.md) for current status, pinned artifacts and resumption instructions.
This is an experimental training/serving pipeline, **not a replacement for the current production bot**. The trained self-play model beats the new simple heuristic but loses heavily to the engine's existing bot. No BGS bot routing has been changed.
## Scope and information
Germany, three players, normal region setup, original and Recharged rules, open and sealed (`fastBid`) auctions. Money is visible for every player. Other maps, player counts and randomized maps need another feature schema and training distribution. Optional region/color drafts are not represented adequately and must not be used with this model.
The existing compiled JavaScript engine is the authoritative simulator. No game rules were modified. The engine revision is `365fc519903fa2b4e8c593eed6cc5f5f77b5332a`. Schema v2 contains 541 state numbers and 74 numbers per candidate action. Its 44-city vocabulary covers both original and Recharged Germany, including Stralsund/Mainz and Torgelow/Wiesbaden. Schema v1 omitted the two replacement cities and is superseded; do not mix v1 weights with current features. The policy scores a variable list of legal candidates. Large bid lists are approximated by the lowest eight bids, multiples of ten, and the maximum; this is not exhaustive bidding.
Feature extraction excludes seed, deck order, logs, queued plans, and sealed bid amounts, including already submitted opposing bids. Sealed auctions retain the engine's actual resolution rules, rather than being treated as faster ascending auctions. Player order, plant markets, resource markets, cities, all players' money and holdings remain visible. The server passes trusted engine state; the model itself sees only the allowlisted features.
## Corrected schema v2 results
The final HF job completed in 155 seconds. It uses the 44-city vocabulary, 600 synthetic games, 32 supported human games, 12 imitation epochs and 16 self-play updates (482 completed episodes). Four JS workers serve 64 environments; optimizer batch is 1,024. Source: dataset commit `65ecfa063c272bd72a805d45f4ba55dc84a28f42`, archive `source-v4.tgz`. Job: https://huggingface.co/jobs/coyotte508/6abd0cba404719ba3761324e.
Each comparison has 480 games and zero truncations:
| Candidate | Opponents | Win share |
| ------------ | ------------------- | --------: |
| Imitation v2 | New heuristic | 13.75% |
| Self-play v2 | New heuristic | 90.00% |
| Imitation v2 | Existing engine bot | 0.00% |
| Self-play v2 | Existing engine bot | 0.00% |
This is a failed playing-strength gate, despite a working training pipeline. Do not deploy it as the production bot. The larger optimizer batch improved component throughput but reduced gradient updates per epoch; these runs also change schema and rollout configuration, so they are not a controlled batch-size quality comparison.
On the 8840U, the corrected self-play model reproduces all 480 laptop game outcomes. Pure inference p95 is 0.130 ms. Full worker p50/p95 is 0.773/1.202 ms across 48 representative positions; startup plus first request is 152 ms. All returned actions are legal. Both exports agree with PyTorch on 128 checked decisions each, with maximum absolute error below 0.000007.
The throughput microbenchmark measured 2,766 decisions/s with one worker/24 environments, 6,289 with four workers/256 environments, and 6,177 with eight. Optimizer sample throughput rose from 18,874 to 28,590/s when increasing batch 256 to 1,024. This does not translate directly into full training speed or playing strength.
## Initial evidence (schema v1; corrected-model results accompany the package)
- Read-only BGS audit: 4,007 records, 3,978 marked ended. Export restricted to non-unlisted, ended Germany games with three players.
- 66 candidate historical games; 33 replay exactly against the current engine, including 7 sealed games. Reject 14 dropped/quit/bot games, 15 records that do not reach engine termination, and 4 incompatible replays. The initial run used 11,675 decision examples. Corrected-schema training excludes one color-draft game outside its supported setup: 32 games and 11,366 historical decision examples remain. These records are private and excluded from Git and serving bundles.
- Initial HF job: 600 synthetic games plus verified human examples, 12 imitation epochs, 16 PPO updates, all three seats share the model. Split imitation validation by whole game. HF job completed in 147 seconds excluding queue. CPU training is not run on the 8840U.
- Evaluation: 40 unseen seeds × 3 rotated seats × 4 rule combinations = 480 games per comparison. Model gets one seat, the selected opponent fills the other two. Zero truncated evaluation games.
| Candidate | Opponents | Win share |
| --------------- | ------------------- | --------: |
| Imitation model | New heuristic | 59.27% |
| Self-play model | New heuristic | 81.77% |
| Self-play model | Existing engine bot | 2.08% |
These are observed win shares, splitting ties. Seats sharing a seed are correlated. The simple heuristic is a weak opponent; its score is not evidence of human-level play. Use the existing bot as a gate and a training teacher in the next experiment. Freeze separate final-test seeds before selecting many checkpoints.
8840U: all 480 model-vs-heuristic games completed with identical outcomes to the laptop. Pure ONNX inference p50 0.082 ms / p95 0.165 ms. Persistent JSONL worker on 48 representative positions: p50 0.725 ms / p95 1.144 ms; first request including worker startup 182 ms. All returned actions passed the engine. These are one-run measurements, not concurrency/load guarantees.
The value head is an **uncalibrated self-play win estimate**, not a forecast of a player's final score or objective position strength. Imitation held-out value MSE is approximately 0.244. Do not expose a player-analysis graph from it yet: add round-stratified calibration, stronger reference opponents, and a separate final-score target if that is the desired analysis.
## Run and reproduce
Install the engine dependencies and build `engine/tsconfig.json` using the repository's package manager. Use Python 3.11+, Node 24, and `pip install -r ai/requirements-serve.txt` for serving. Verified runtimes: Python 3.11 / NumPy 2.4.6 on the laptop; Python 3.12 / NumPy 2.5.3 on the 8840U; ONNX Runtime 1.30.0 on both. Cloud training additionally needs PyTorch, `onnx`, and `huggingface_hub`; launch scripts use the PyTorch 2.6.0 CUDA 12.4 image.
```sh
node --test ai/test.cjs
hf download coyotte508/powergrid-ai-germany-v1 --include 'runs/baseline-v2/*' --local-dir ai/runs/download
python ai/evaluate.py ai/runs/download/runs/baseline-v2/selfplay.onnx --seeds 40 --output evaluation.json
python ai/evaluate.py ai/runs/download/runs/baseline-v2/selfplay.onnx --seeds 40 --opponent legacy --output evaluation-legacy.json
python ai/serving-smoke.py ai/runs/download/runs/baseline-v2/selfplay.onnx
```
Private HF repositories require the owner's token in the CLI credential store. `launch-v2.sh` trains the corrected schema using `source-v4.tgz`; `launch.sh` reproduces the initial frozen `source-v1.tgz` job; `launch-smoke.sh` checks the updated concurrent trainer with `source-v2.tgz`. `launch-profile.sh` measures batching/worker throughput. Source archives contain only the compiled engine, its production dependencies, AI scripts and the deidentified verified training records. Use the recorded dataset commit plus archive hash for exact provenance; uploaded archives are not automatically rebuilt when local files change.
Trainer controls: `GAMES`, `BC_EPOCHS`, `RL_UPDATES`, `ENVS`, `WORKERS`, `BATCH_SIZE`, `ROLLOUT_SAMPLES`, `OUT`, `RUN_NAME`, `HF_MODEL_REPO`. Start with four workers and 256 environments, then tune the optimizer batch from measurements. Increasing batch changes optimization dynamics; compare strength as well as throughput. The small model does not need to fill GPU VRAM. Python JSON conversion and feature packing still take appreciable time; a packed binary/shared-memory interface is the next throughput improvement if needed.
## Platform worker contract
Keep one worker alive per CPU execution slot:
```sh
python ai/infer.py selfplay.onnx
```
Input is one JSON object per line: `{ "requestId": "unique-job-id", "revision": 123, "player": 0, "state": <authoritative raw engine state> }`.
Output echoes the request ID/revision and returns `move`, `winProbabilities`, `valueStatus`, `playerOrder`, `model`, `modelSha256`, and `elapsedMs`, or an `error`. Probabilities are ordered `[acting seat, next seat clockwise, third seat]`.
Each request chooses one **atomic** engine action. Before committing it, the platform must reload/check the game revision and acting player, validate the action with its pinned engine, and commit through its normal move path with a server timestamp. Revision is an echoed correlation value here, not a concurrency lock. Retry stale jobs from fresh state; deduplicate by request ID; use the existing bot on timeout/error or unsupported options. Multiple atomic actions can be needed to finish a player's turn. The process provides no HTTP endpoint or authentication; invoke it through the platform's existing job machinery.
## Next strength experiment
1. Generate demonstrations from the existing engine bot and improve the heuristic's build/auction economics. Preserve information boundaries for all teachers.
2. Train against a mixture of existing bots, frozen older policies and self-play; use larger rollout batches and enough completed games rather than simply more GPU memory.
3. Evaluate across rule combinations and held-out seeds with paired uncertainty estimates; require improvement over the existing bot before routing production moves.
4. Expand to other maps/player counts using graph/city features and variable player encodings. Retrain; do not silently apply the Germany model.
5. Train/calibrate analysis targets separately. Public-money assumptions must remain explicit in any analysis UI.

255
ai/RESUME.md Normal file
View file

@ -0,0 +1,255 @@
# Power Grid AI — saved research handoff, 4 October 2026
**Start here when resuming. Research is paused at the user's request. No model
has passed the complete strength gate; nothing is routed into production bot
moves. Reserved final-test seeds remain unused.** This document supersedes the
outdated “running / pending / active” statements in the earlier READMEs and
`strong/multiplayer-progress.json`. Those files remain useful historical notes.
This handoff was reconstructed from the checked-in experiment ledger, local
artifacts and read-only Hugging Face queries. The last five diagnostic jobs are
now COMPLETED. `hf jobs ps --format json` returned `[]` on 4 October. No training
or evaluation jobs were launched for this handoff.
## Objective and information contract
Build a **really strong** Power Grid bot, not just one that beats the default
engine bot. Train on HF Jobs; serve platform requests on the AMD 8840U. Browser
ONNX inference is a possible later use, not a completed integration. Later
analysis of players' decisions/win probabilities requires separately validated
and calibrated values; the current value head is not ready for that claim.
The user explicitly allows all players' money to be visible to the bot. Include
opponents' cities, plants, fuel, turn order and players still to act; resource
replenishment by step, available stock and prices; region/island presence and
remaining building slots. Building more cities can improve income but worsen
turn order, so optimize terminal winning, not an unconditional city reward.
Never expose actual hidden deck order, RNG seed, submitted sealed bids or queued
plans. Search samples public-consistent worlds rather than reading these secrets.
Validated training scope is **Germany, automatic setup, 2–6 players, original
and Recharged rules, open and sealed auctions**. Early policies were Germany/3p
only. Generic topology/territory export and UK/Ireland feature tests exist, but
there is no demonstrated trained strength on other maps. Do not advertise
multi-map support based on feature encoding alone.
## Where everything lives
| Material | Location |
| ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Canonical source | [boardgamers/powergrid](https://github.com/boardgamers/powergrid), `ai/` and `ai/strong/` |
| Complete experiment ledger | [strong/experiments.json](strong/experiments.json): source/model revisions, job IDs, reports, counterexamples and decisions |
| Strong-policy background | [strong/README.md](strong/README.md), historical and partly stale |
| Baseline background | [README.md](README.md) |
| Private checkpoints, ONNX, reports, serving archives | [coyotte508/powergrid-ai-germany-v1](https://huggingface.co/coyotte508/powergrid-ai-germany-v1) (name predates multiplayer work) |
| Private immutable source bundles and data | [coyotte508/powergrid-ai-training-v1](https://huggingface.co/datasets/coyotte508/powergrid-ai-training-v1) |
| Multiplayer final gate | [strong/final-protocol-multiplayer.json](strong/final-protocol-multiplayer.json) |
| Earlier 3p gate | [strong/final-protocol.json](strong/final-protocol.json) |
| Latest admission comparison protocol | [strong/league-admission-protocol-v1.json](strong/league-admission-protocol-v1.json) |
| Collected diagnostic summary | [strong/handoff/teacher-reliability-v2-summary.json](strong/handoff/teacher-reliability-v2-summary.json) |
| Sanitized resume manifest | [strong/handoff/status-2026-10-04.json](strong/handoff/status-2026-10-04.json) |
Local canonical checkout: `/home/eliheros/code/powergrid`. Source before this
handoff was `face347f258a057c2ed3fb4e4606fce2003ab4c1`; AI research was integrated
by `1e73e53`. Old research checkout:
`/home/eliheros/Documents/Codex/2026-09-26/je-x20-2/work/powergrid-ai`, HEAD
`4bc256a8b126c0da977b9a728df9356e201ed815`. Its ignored `ai/runs/` contains large
local artifacts; do not assume those are present in a fresh clone. The previously
untracked `summarize-search-budgets.py` has been rescued into canonical source.
The research-only 8840U installation is `~/powergrid-ai-strong` on SSH alias
`minipc` (fallback `minipc-wg`). SSH configuration was updated previously. No
production routing was installed. Recheck host/runtime state when resuming.
The authenticated HF CLI is `/home/eliheros/.local/bin/hf`; its Python is
`/home/eliheros/.hf-cli/venv/bin/python`. Use cached authentication; never put
tokens or raw historical game data in Git.
## What was implemented and learned
1. **Baseline and historical-data audit.** Of 4,007 BGS records, 3,978 were ended;
66 candidate Germany/3p games yielded 33 exact replays (7 sealed), then 32
usable games / 11,366 decisions after excluding a colour-draft game. Failed,
interrupted and incompatible replays were excluded explicitly. A 600-game
synthetic + human baseline ran BC and PPO. It beat a weak heuristic but scored
0% against the default bot: not useful evidence of strength.
2. **Corrected opponent and observations.** A heuristic read nonexistent
`BuyResource.data.price`, producing NaN and suppressing fuel buying; stock-based
resource pricing was also wrong. The corrected heuristic scored 85.1% against
the default bot over 960 games. Default-bot wins are only a sanity check.
3. **Schema 3 strong policies.** 738 state / 96 action features; economic prior
plus learned residual action scores, complete-episode PPO, frozen opponents,
public-information search, CPU arenas and ONNX serving. Preserve frozen
revision `3.0`; `3.1-uranium39` fixes persistent replenishment after plant 39
has been purchased (even if later discarded). Unknown feature revisions fail.
4. **3p training/search/distillation.** A/B leagues completed 300 updates;
high-exploration C/D were stopped after regression. Search-teacher datasets
progressed from 512 games / 25,268 strategic positions to corrected v3's
2,048 complete games / 247,104 decisions. More distillation did not reliably
improve independent play. Corrected A260 refinement update 40 and A299 were
useful references, but sealed-auction weaknesses remained.
5. **3p specialist.** Corrected A40 for three rule combinations and corrected-input
B160 + 48-sample search for Recharged/sealed: 76.7% versus economic, 94.6%
versus legacy, 46.7% versus frozen A260, each 480 development matches. SHA:
`b4cae14eb6e1aff72b16e5056983b2a57ad42984f4a27cf99dd70bb63e86be32`.
This is a research candidate, not a qualified universal bot. See ledger
`specialist_candidate`, `specialists_remaining_results` and the other screens.
6. **Schema 4 multiplayer.** Revision `4.0-multiplayer`: 1,149 state / 98 action
features, six ordered player slots (74 features each), inactive value slots
masked to zero. `multiplayer_ordered` has 983,682 parameters and supersedes the
earlier pooled prototype. Tested encoding and legal responses at every count;
2,553 fixtures cover 2–6p. Initial teacher: 1,200 games / 142,804 positions /
4,746,464 search rollouts with no truncations. Subsequent distillation, PPO,
asynchronous environment workers, stronger-opponent replay and league
admission comparisons are all recorded in the ledger.
7. **Later PPO.** H200 refinement and geographic-opponent asynchronous training
each completed 80 updates / 19,200 games. These improved some development
matchups, especially 5–6p, but did not qualify. A stronger teacher replay
experiment did not translate prediction agreement into better independent
play. Do not simply extend the same recipe or assume harder labels help.
## Latest completed strength screens
All numbers below are percentage win credit, including fractional ties, on
**reused development screening deals**, not untouched final tests. Each row has
3,680 completed matches: economic at 2/3/4/5/6 players (320/480/640/800/960 games)
plus frozen A260 at 3p (480). Full rule-level breakdowns and deal-cluster intervals
are in each corresponding ledger entry. Aggregate rates cannot override a weak
rule cell. Search is off for these candidates.
| Candidate | Econ 2p | 3p | 4p | 5p | 6p | Frozen A260 3p |
| ----------------------------------- | ------: | ----: | ----: | ----: | ----: | -------------: |
| H200 update 79 | 63.44 | 60.83 | 59.69 | 77.69 | 73.28 | 33.54 |
| Geographic league update 79 | 52.34 | 59.90 | 54.53 | 71.44 | 65.99 | 33.33 |
| Admission “best” update 19 | 52.81 | 56.67 | 57.66 | 79.19 | 74.58 | 39.58 |
| Admission periodic-anchor update 19 | 60.31 | 57.40 | 61.72 | 74.94 | 70.16 | 36.04 |
None passes the 66.25% economic/2p and 40% A260/3p floors together. Geographic
update 79 also fails the strict export tolerance on one logit (although all
2,553 selected actions agree). Its training had four capped search rollouts;
the screening games/rollouts above were untruncated. Other three exports pass
their recorded parity checks. “Internal best” was not a reliable universal
external-strength selector; admission comparison had one training seed.
Pinned checkpoints in the private model repo:
| Candidate | HF revision | File | SHA256 |
| ----------------------- | ------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ |
| H200 u79 | `0aeacd5b8e36ece36ba06a77ddfd7b86110d4f3a` | `runs/multiplayer-refine-hard-v1/latest.onnx` | `2f1dd42625ea86404155e63124e55d95d07016027a0ceda4e08164357b554927` |
| Geographic u79 | `035345f5f05bbbb55af5e0f4884d07f9087b1e32` | `runs/multiplayer-refine-geoleague-async-v1/latest.onnx` | `35deffdacefdc3d3638417b1590432b84a86f3fb302958e273f5eeea9ad7ce34` |
| Admission best u19 | `efdb82f2712b8c6648100d7ad99b6941102f7001` | `runs/multiplayer-league-admission-v1-best/latest.onnx` | `691a91ae58d5946a396fe595ffba2f866b5bfba6533ec504da9e6a134c07750e` |
| Periodic-anchor u19 | `efdb82f2712b8c6648100d7ad99b6941102f7001` | `runs/multiplayer-league-admission-v1-periodic-anchor/latest.onnx` | `08ad0042e548e9b871e9f4178626d405637fb55f3f42b0d580b2bd6979ac7f67` |
| Frozen 3p A260 opponent | `b38515c29e57826de05b55b645c29591e4a886bf` | `runs/strong-league-v2-a/best.onnx` | `9b46db558669a0c3085412fe2544359eda55ed9f092dffb67bead6af3c409ecd` |
Earlier H200 update 29 (revision
`fbdf2bf24c968bff99ab2d7d9ff9a7d97047db2b`, same hard-refinement model path,
SHA `d3d2ee88a0940f079a4b38879c8154dbab55951abc7b295a7db17bdf22e52c5f`)
remains a useful retained comparison; do not replace it just because later
updates exist. Its raw policy transferred gains over the distillation warm start
against independent `search_geo`, but 2–4p rates missed floors, with sealed-rule
weaknesses at 5–6p. Single-deal auction counterfactuals did not support the simple
explanation “pass or buy a cheaper plant”; no tested round-4 nomination won the
second investigated losing deal. Those are local diagnoses, not causal proof
about the whole policy.
## Diagnostics completed after the pause
Jobs `teacher-reliability-v2-{2..6}p`, CPU-performance, submitted 1 October:
| Players | Completed job |
| ------- | ------------------------------------------------------------------------------------------- |
| 2 | [6abe1df0fbc85ba682360bd8](https://huggingface.co/jobs/coyotte508/6abe1df0fbc85ba682360bd8) |
| 3 | [6abe1df1404719ba3761721e](https://huggingface.co/jobs/coyotte508/6abe1df1404719ba3761721e) |
| 4 | [6abe1df2fbc85ba682360bda](https://huggingface.co/jobs/coyotte508/6abe1df2fbc85ba682360bda) |
| 5 | [6abe1df2fbc85ba682360bdc](https://huggingface.co/jobs/coyotte508/6abe1df2fbc85ba682360bdc) |
| 6 | [6abe1df3fbc85ba682360be0](https://huggingface.co/jobs/coyotte508/6abe1df3fbc85ba682360be0) |
Immutable source: dataset revision `d07e072058ee877112d609280980fc806ee8ce28`,
`strong-source-v36.tgz`, SHA256
`6c4170317a74a5148c2a576ad93d1170441e0d8e791a7e6c23197c51dad69109`.
Fixtures: 60 reused development positions, 2–6p × four rules × nomination/bid/build.
Fixture SHA `855b34ad7f07665dfcb012a673147f0780820a9e7560fda268a9a39478c60ff4`.
Downloaded model-repo revision `daef30ae69d6a96f21e46abd8a30909689682364`,
`runs/teacher-reliability-v1/` and `runs/teacher-reliability-v2/`. The summary
script verified every shard hash, all 360 searches / **721,152 rollouts**, zero
truncations, 2,400-step horizon, exact nested 48-sample prefixes and shared public
scenarios across continuation policies. It compares independent batches A/B and
budgets 48/96/192/384 under mixed/economic/heuristic continuations.
At 384 mixed samples, selected action agreed on 47/60 positions (v1: 39/60 at
48). Same unique winner rose from 19/60 to 29/60; disjoint winning sets fell from
16/60 to 10/60, but the intermediate budgets were not monotonic. Fourteen positions
had opposite economic/heuristic preferences in confirmation batch B for actions
selected in batch A. **Descriptive only:** this small reused fixture set establishes
neither playing strength nor which continuation policy is realistic. Larger
budgets alone do not resolve the teacher-policy mismatch. No gradients were run.
Reproduce this local audit without submitting jobs (from repo root):
```sh
hf download coyotte508/powergrid-ai-germany-v1 \
--revision daef30ae69d6a96f21e46abd8a30909689682364 \
--include 'runs/teacher-reliability-v1/*' 'runs/teacher-reliability-v2/*' \
--local-dir ai/runs/resume-snapshot
python3 ai/strong/summarize-search-budgets.py \
ai/runs/resume-snapshot/runs/teacher-reliability-v2 \
ai/runs/resume-snapshot/runs/teacher-reliability-v1/results.jsonl \
--output ai/runs/resume-snapshot/summary.json
```
## Runtime, implementation and resumption order
The JavaScript engine is still authoritative. No Rust rewrite was completed.
Profiling found repeated economics/territory calculations to be a bigger cost;
hoisting them out of action loops sped feature generation 2.2× with identical
outputs over 1,786 positions. Batching and asynchronous environment workers were
added. A tested cache regressed runtime and was removed. Low GPU utilization by
itself is not a reason to allocate more GPUs to CPU-bound simulation.
Actual 8840U measurements: schema-3 raw full-worker p95 around 3.5–3.8 ms;
multiplayer prototype p95 4.69 ms over 2,553 legal requests. Optional search is
much slower: roughly 0.7 s at 16 samples on a small fixture subset, 2–3 s at 48.
The specialist's 33 searched decisions had p95 2.36 s, max 2.57 s, no capped
rollouts. These measurements belong to their exact archived candidates/configs;
they are not latency guarantees for all later policies or browsers.
When the user explicitly resumes:
1. Read this file and relevant ledger entries; inspect HF jobs before launching
anything, to avoid duplicates. Fetch exact HF revisions and verify hashes.
Use immutable source bundles to reproduce old experiments; current engine
code includes later UI/game fixes and is not automatically equivalent.
2. Start from the saved teacher-reliability summary. Design an explicit comparison
of continuation quality/opponent coverage, especially sealed auctions, and
evaluate uncertain targets before another large hard-label distillation run.
More samples helped repeatability but did not make all labels reliable.
3. Retain H200 u29/u49/u79, specialist and frozen opponents as comparisons. Use
paired development deals, every player count and rule cell, diverse opponents,
and report all actual-game/search truncations. Search horizon must explicitly
be 2,400 for the newer multiplayer runtime; older 1,200-step results remain
separate. `six_player_search_horizon_investigation` documents the rare cap.
4. Re-run meaningful information-boundary, encoder and export checks when code
changes. Key entry points: `test.cjs`, `test-v4.cjs`, `test-search-samples.cjs`,
`test-search-horizon.cjs`, Python tests, `check-export.py`,
`benchmark-serving.py`, `package-serving.py`, `verify-package.py`. Check each
script's CLI and candidate feature contract before use. Standalone archives
expose `serve.py`, which verifies the frozen model hash and configuration.
5. Freeze a candidate only after development evidence warrants it. The multiplayer
gate requires each count/rule interval lower bound above 1/N, complete paired
deals, no illegal moves, explicit rollout counters, strict ONNX parity, all
2,553 legal serving requests and actual 8840U measurements. Minimum economic
rates for 2–6p are 66.25/55/49.375/46/43.75%; default bot is 90% at every count;
other opponent thresholds are in the protocol. Do not lower gates after results.
6. Only then use reserved prefix `strong-multiplayer-final-reserved-v1` under a
frozen multiplayer evaluator. The existing `launch-final.py` / `verify-final.py`
were built for the earlier 3p protocol: inspect/adapt their count support before
invoking, rather than assuming the new protocol JSON is sufficient. Failed
qualification stays failed; a new candidate requires new final seeds.
7. After qualification, integrate bot requests, then separately investigate
browser ONNX and calibrated per-round analysis. Expand maps with per-map
training/evaluation; UK/Ireland geography is particularly important.
Historical BGS data remains useful for legal-action replay, realistic positions,
imitation warm starts and diagnostics. It is small, selected and not evidence
that its players are expert. Keep whole games separated across splits and never
substitute training fit for independent playing-strength tests.

55
ai/arena.cjs Normal file
View file

@ -0,0 +1,55 @@
const c = require('./core.cjs'),
readline = require('node:readline');
let g, seat, opponent, rng, steps;
function advance() {
while (!c.E.ended(g) && g.currentPlayers[0] !== seat && steps < 1600) {
const p = g.currentPlayers[0];
if (opponent === 'legacy') {
const old = Math.random;
Math.random = rng;
try {
g = c.E.moveAI(g, p);
} finally {
Math.random = old;
}
} else g = c.E.move(g, c.heuristic(g, p, rng).action, p);
steps++;
}
if (c.E.ended(g) || steps >= 1600)
return {
done: true,
truncated: !c.E.ended(g),
win: c.E.ended(g) ? c.outcome(g)[seat] : 0,
round: g.round,
steps,
final: g.players.map((p) => ({ powered: p.citiesPowered, money: p.money, cities: p.cities.length })),
};
const a = c.candidates(g, seat);
return {
done: false,
state: c.observe(g, seat),
actions: a.map((x) => c.actionFeatures(g, seat, x)),
heuristic: c.heuristic(g, seat, rng).index,
};
}
(async () => {
for await (const line of readline.createInterface({ input: process.stdin })) {
try {
const q = JSON.parse(line);
if (q.op === 'reset') {
g = c.start(q.seed, q.variant, q.sealed);
seat = q.seat;
opponent = q.opponent || 'heuristic';
rng = c.seedrandom(q.seed + '-opponents');
steps = 0;
} else if (q.op === 'step') {
g = c.E.move(g, c.candidates(g, seat)[q.action], seat);
steps++;
}
console.log(JSON.stringify(advance()));
} catch (e) {
console.error(e.stack);
process.exit(1);
}
}
})();

59
ai/audit-remote.cjs Normal file
View file

@ -0,0 +1,59 @@
const fs = require('node:fs');
const { parseEnv } = require('node:util');
const { createRequire } = require('node:module');
const requireApi = createRequire('/home/bgs/boardgamers-mono/apps/api/package.json');
const { MongoClient } = requireApi('mongodb');
(async () => {
const env = parseEnv(fs.readFileSync('/home/bgs/boardgamers-mono/apps/api/.env', 'utf8'));
const client = await MongoClient.connect(env.dbUrl, { serverSelectionTimeoutMS: 10000 });
try {
const db = client.db(env.dbName || 'bgs');
const c = db.collection('games');
const counts = await c
.aggregate(
[
{ $match: { 'game.name': 'powergrid' } },
{
$group: {
_id: {
version: '$game.version',
status: '$status',
map: '$game.options.map',
variant: '$game.options.variant',
players: '$options.setup.nbPlayers',
},
n: { $sum: 1 },
},
},
],
{ maxTimeMS: 20000 }
)
.toArray();
const sample = await c.findOne(
{ 'game.name': 'powergrid', status: 'ended' },
{ projection: { data: 1, game: 1, options: 1, players: 1, status: 1 } }
);
console.log(
JSON.stringify(
{
counts,
sample: sample && {
dataType: typeof sample.data,
dataKeys: typeof sample.data === 'object' ? Object.keys(sample.data || {}) : undefined,
dataLength: typeof sample.data === 'string' ? sample.data.length : undefined,
game: sample.game,
playerFields: Object.keys(sample.players[0] || {}),
hasSeed: !!sample.options?.setup?.seed,
},
},
null,
2
)
);
} finally {
await client.close();
}
})().catch((e) => {
console.error(e.name, e.code);
process.exit(1);
});

54
ai/audit-replays.cjs Normal file
View file

@ -0,0 +1,54 @@
const fs = require('node:fs'),
assert = require('node:assert/strict');
const c = require('./core.cjs');
const games = fs.readFileSync('ai/private-data/human-games.jsonl', 'utf8').trim().split('\n').map(JSON.parse);
const results = [];
let admitted = [];
const clean = (p) => ({
money: p.money,
citiesPowered: p.citiesPowered,
cities: p.cities.map((c) => c.name).sort(),
powerPlants: p.powerPlants.map((p) => p.number).sort((a, b) => a - b),
});
for (const h of games) {
let count = 0;
try {
if (h.players.some((p) => p.dropped || p.quit || p.bot)) throw Error('dropped/quit/bot');
if (h.phase !== c.E.Phase.GameEnd) throw Error('not engine terminal');
let g = c.E.setup(3, h.options, h.seed);
for (const m of h.moves) {
g = c.E.move(g, m.move, m.player);
count++;
}
assert.deepEqual(g.players.map(clean), h.final);
assert.ok(c.E.ended(g));
admitted.push(h);
results.push({
id: h.id,
version: h.version,
variant: h.options.variant,
sealed: !!h.options.fastBid,
moves: count,
accepted: true,
});
} catch (e) {
results.push({ id: h.id, version: h.version, moves: count, accepted: false, reason: e.message.split('\n')[0] });
}
}
fs.writeFileSync('ai/private-data/verified-games.jsonl', admitted.map((x) => JSON.stringify(x)).join('\n'));
const report = {
total: games.length,
accepted: admitted.length,
acceptedSealed: admitted.filter((x) => x.options.fastBid).length,
results,
};
fs.writeFileSync('ai/replay-audit.json', JSON.stringify(report, null, 2));
console.log({
total: games.length,
accepted: admitted.length,
reasons: results.reduce((o, r) => {
let k = r.accepted ? 'accepted' : r.reason;
o[k] = (o[k] || 0) + 1;
return o;
}, {}),
});

35
ai/benchmark.cjs Normal file
View file

@ -0,0 +1,35 @@
const c = require('./core.cjs'),
fs = require('node:fs'),
os = require('node:os'),
{ performance } = require('node:perf_hooks');
let runs = [];
for (const variant of ['original', 'recharged'])
for (const sealed of [false, true]) {
let steps = 0,
ended = 0;
const t = performance.now();
for (let i = 0; i < 100; i++) {
let g = c.start('benchmark-' + i, variant, sealed),
rng = c.seedrandom('policy-' + i),
n = 0;
while (!c.E.ended(g) && n++ < 1600) {
const p = g.currentPlayers[0];
g = c.E.move(g, c.heuristic(g, p, rng).action, p);
steps++;
}
ended += +c.E.ended(g);
}
const sec = (performance.now() - t) / 1000;
runs.push({
variant,
sealed,
games: 100,
ended,
steps,
seconds: sec,
gamesPerSecond: 100 / sec,
stepsPerSecond: steps / sec,
});
}
const result = { cpu: os.cpus()[0].model, node: process.version, runs };
console.log(JSON.stringify(result, null, 2));

54
ai/bridge.cjs Normal file
View file

@ -0,0 +1,54 @@
const c = require('./core.cjs'),
readline = require('node:readline');
let envs = [],
sequence = 0;
const seed = process.env.SEED || 'rollout-v1';
const rng = c.seedrandom(seed);
function reset() {
const id = sequence++;
return { g: c.start(seed + '-' + id, id % 2 ? 'recharged' : 'original', id % 4 < 2), id, steps: 0 };
}
function obs(e) {
const seat = e.g.currentPlayers[0],
a = c.candidates(e.g, seat);
return {
state: c.observe(e.g, seat),
actions: a.map((x) => c.actionFeatures(e.g, seat, x)),
seat,
episode: e.id,
heuristic: c.heuristic(e.g, seat, rng).index,
};
}
(async () => {
for await (const line of readline.createInterface({ input: process.stdin })) {
try {
const q = JSON.parse(line);
let ended = [];
if (q.op === 'reset') {
envs = Array.from({ length: q.n }, reset);
} else if (q.op === 'step') {
q.actions.forEach((action, i) => {
const e = envs[i],
seat = e.g.currentPlayers[0];
e.g = c.E.move(e.g, c.candidates(e.g, seat)[action], seat);
e.steps++;
if (c.E.ended(e.g) || e.steps >= 1600) {
ended.push({
env: i,
episode: e.id,
truncated: !c.E.ended(e.g),
value: c.E.ended(e.g) ? c.outcome(e.g) : null,
steps: e.steps,
round: e.g.round,
});
envs[i] = reset();
}
});
} else throw Error('unknown operation');
console.log(JSON.stringify({ observations: envs.map(obs), ended }));
} catch (e) {
console.error(e.stack);
process.exit(1);
}
}
})();

239
ai/core-v2.cjs Normal file
View file

@ -0,0 +1,239 @@
const E = require('../engine/dist/index.js');
const { map: germany, mapRecharged: germanyRecharged } = require('../engine/dist/src/maps/germany.js');
const seedrandom = require(require.resolve('seedrandom', { paths: [__dirname + '/../engine'] }));
const TYPES = [
'ChoosePowerPlant',
'Bid',
'DiscardPowerPlant',
'DiscardResources',
'BuyResource',
'Build',
'UsePowerPlant',
'ChooseRegion',
'ChooseColor',
'Pass',
];
const RES = ['coal', 'oil', 'garbage', 'uranium'];
const CITIES = [...new Set([...germany.cities, ...germanyRecharged.cities].map((c) => c.name))].sort();
const PHASES = Object.values(E.Phase);
const onehot = (v, vs) => vs.map((x) => +(x === v));
const plant = (p) =>
p ? [p.number / 50, p.cost / 4, p.citiesPowered / 8, ...onehot(p.type, [0, 1, 2, 3, 4, 5])] : Array(9).fill(0);
function assertScope(g) {
if (
g.map.name !== 'Germany' ||
g.players.length !== 3 ||
g.options.randomizeMap ||
g.map.cities.some((city) => !CITIES.includes(city.name)) ||
g.options.chooseRegions ||
g.options.chooseColors
)
throw Error('Baseline supports three-player Germany with automatic setup only');
}
function observe(g, seat) {
assertScope(g);
const order = [seat, (seat + 1) % 3, (seat + 2) % 3];
const s = [
...onehot(g.phase, PHASES),
g.round / 20,
g.step / 3,
+(g.options.variant === 'recharged'),
+g.options.fastBid,
g.cardsLeft / 50,
+g.nextCardWeak,
(g.options.fastBid ? 0 : g.currentBid || 0) / 100,
(g.minimunBid || 0) / 100,
...onehot(g.auctioningPlayer, order),
g.citiesToEndGame / 25,
g.citiesToStep2 / 20,
];
for (const r of RES)
s.push(
(g[r + 'Market'] || 0) / 24,
(g[r + 'Supply'] || 0) / 24,
...(g[r + 'Prices'] || []).slice(0, 24).map((x) => x / 20),
...Array(Math.max(0, 24 - (g[r + 'Prices'] || []).length)).fill(0)
);
for (const i of order) {
const p = g.players[i];
s.push(
p.money / 500,
p.cities.length / 22,
p.housesLeft / 22,
p.citiesPowered / 22,
g.playerOrder.indexOf(i) / 2,
+p.skipAuction,
+p.passed,
(g.options.fastBid ? 0 : p.bid || 0) / 100
);
for (const r of RES) s.push((p[r + 'Left'] || 0) / 24, (p[r + 'Capacity'] || 0) / 24);
s.push(p.hybridCapacity / 24);
for (let j = 0; j < 4; j++) s.push(...plant(p.powerPlants[j]));
}
for (let i = 0; i < 4; i++) s.push(...plant(g.actualMarket[i]), ...plant(g.futureMarket[i]));
s.push(...plant(g.chosenPowerPlant));
for (const city of CITIES)
s.push(
+g.map.cities.some((c) => c.name === city),
...order.map((i) => +g.players[i].cities.some((c) => c.name === city))
);
if (!s.every(Number.isFinite)) throw Error('Non-finite observation');
return s;
}
function allLegal(g, seat) {
return Object.entries(g.players[seat].availableMoves || {}).flatMap(([name, items]) =>
(items || []).map((data) => ({ name, data }))
);
}
function candidates(g, seat) {
const all = allLegal(g, seat),
bids = all.filter((a) => a.name === 'Bid');
if (bids.length <= 48) return all;
const min = bids[0].data,
max = bids.at(-1).data;
return all.filter((a) => a.name !== 'Bid' || a.data < min + 8 || a.data % 10 === 0 || a.data === max);
}
function actionFeatures(g, seat, a) {
const d = a.data,
p = g.players[seat];
const pp =
a.name === 'ChoosePowerPlant'
? g.actualMarket.find((x) => x.number === d)
: a.name === 'DiscardPowerPlant'
? p.powerPlants.find((x) => x.number === d)
: a.name === 'UsePowerPlant'
? p.powerPlants.find((x) => x.number === d.powerPlant)
: g.chosenPowerPlant;
const cost = a.name === 'Bid' ? d : d?.price || 0;
return [
...onehot(a.name, TYPES),
cost / 500,
cost / Math.max(p.money, 1),
...onehot(d?.resource || (typeof d === 'string' ? d : ''), RES),
...plant(pp),
...onehot(d?.name, CITIES),
(d?.citiesPowered || 0) / 20,
...RES.map((r) => (d?.resourcesSpent || []).filter((x) => x === r).length / 4),
];
}
function fuelDemand(g, p) {
const target = Math.min(Math.max(p.cities.length, Math.min(3, capacity(p))), capacity(p));
let powered = 0;
const need = Object.fromEntries(RES.map((r) => [r, 0]));
const ps = [...p.powerPlants].sort((a, b) => fuelCost(g, a) / a.citiesPowered - fuelCost(g, b) / b.citiesPowered);
for (const pp of ps) {
if (powered >= target) break;
powered += pp.citiesPowered;
let resource = RES[pp.type];
if (pp.type === 4) resource = (g.coalPrices[0] || 8) <= (g.oilPrices[0] || 8) ? 'coal' : 'oil';
if (resource) need[resource] += pp.cost;
}
return need;
}
function fuelCost(g, pp) {
return (
pp.cost *
(pp.type === 4 ? Math.min(g.coalPrices[0] || 8, g.oilPrices[0] || 8) : g[RES[pp.type] + 'Prices']?.[0] || 0)
);
}
const capacity = (p) => p.powerPlants.reduce((n, x) => n + x.citiesPowered, 0);
function plantWorth(g, p, pp) {
let old = 0;
if (p.powerPlants.length >= 3) old = Math.min(...p.powerPlants.map((x) => x.citiesPowered));
const gain = Math.max(0, pp.citiesPowered - old);
const reserve = Math.max(12, Math.min(40, p.cities.length * 2 + 10));
const useful = gain > 0 || fuelCost(g, pp) < 3;
return useful ? Math.min(p.money - reserve, pp.number + gain * 5 - fuelCost(g, pp)) : 0;
}
function heuristicScore(g, seat, a) {
const p = g.players[seat],
d = a.data,
cap = capacity(p);
switch (a.name) {
case 'ChoosePowerPlant': {
const pp = g.actualMarket.find((x) => x.number === d);
const worth = plantWorth(g, p, pp);
return worth >= d ? 20 + pp.citiesPowered * 5 - fuelCost(g, pp) - d * 0.2 : -100 - d;
}
case 'Bid': {
const worth = Math.max(g.round === 1 ? g.minimunBid : 0, plantWorth(g, p, g.chosenPowerPlant));
if (d > worth) return -100 - d;
return g.options.fastBid ? 20 - Math.abs(worth - d) : 30 - d * 0.1;
}
case 'DiscardPowerPlant': {
const pp = p.powerPlants.find((x) => x.number === d);
return 10 - pp.citiesPowered * 5 + fuelCost(g, pp);
}
case 'DiscardResources':
return 10 + (p[d + 'Left'] || 0);
case 'BuyResource': {
const need = fuelDemand(g, p);
return p[d.resource + 'Left'] < need[d.resource] &&
p.money - d.price >= Math.max(0, p.cities.length ? 0 : 12)
? 20 - d.price
: -100;
}
case 'Build': {
const desired =
p.money > 150 || g.round > 18
? g.citiesToEndGame
: Math.min(g.citiesToEndGame, cap + (p.money > 100 ? 1 : 0));
return p.cities.length < desired ? 30 - d.price * 0.5 : -100;
}
case 'UsePowerPlant':
return (
40 +
(d.citiesPowered || 0) * 5 -
(d.resourcesSpent || []).reduce((n, r) => n + (g[r + 'Prices']?.[0] || 8), 0)
);
case 'Pass':
return 0;
default:
return 1;
}
}
function heuristic(g, seat, rng = () => 0.5) {
const a = candidates(g, seat);
let best = 0,
v = -Infinity;
a.forEach((x, i) => {
const score = heuristicScore(g, seat, x) + rng() * 0.01;
if (score > v) {
v = score;
best = i;
}
});
return { index: best, action: a[best] };
}
function outcome(g) {
const sorted = E.playersSortedByScore(g),
top = sorted[0],
w = g.players.map(
(p) =>
+(
p.citiesPowered === top.citiesPowered &&
p.money === top.money &&
p.cities.length === top.cities.length
)
);
return w.map((x) => x / w.reduce((a, b) => a + b, 0));
}
function start(seed, variant = 'original', fastBid = false) {
return E.setup(3, { map: 'Germany', variant, fastBid, showMoney: true }, seed);
}
module.exports = {
E,
CITIES,
TYPES,
RES,
observe,
allLegal,
candidates,
actionFeatures,
heuristic,
heuristicScore,
outcome,
start,
seedrandom,
};

250
ai/core.cjs Normal file
View file

@ -0,0 +1,250 @@
const E = require('../engine/dist/index.js');
const { map: germany, mapRecharged: germanyRecharged } = require('../engine/dist/src/maps/germany.js');
const seedrandom = require(require.resolve('seedrandom', { paths: [__dirname + '/../engine'] }));
const TYPES = [
'ChoosePowerPlant',
'Bid',
'DiscardPowerPlant',
'DiscardResources',
'BuyResource',
'Build',
'UsePowerPlant',
'ChooseRegion',
'ChooseColor',
'Pass',
];
const RES = ['coal', 'oil', 'garbage', 'uranium'];
const CITIES = [...new Set([...germany.cities, ...germanyRecharged.cities].map((c) => c.name))].sort();
const PHASES = Object.values(E.Phase);
const onehot = (v, vs) => vs.map((x) => +(x === v));
const plant = (p) =>
p ? [p.number / 50, p.cost / 4, p.citiesPowered / 8, ...onehot(p.type, [0, 1, 2, 3, 4, 5])] : Array(9).fill(0);
function assertScope(g) {
if (
g.map.name !== 'Germany' ||
g.players.length !== 3 ||
g.options.randomizeMap ||
g.map.cities.some((city) => !CITIES.includes(city.name)) ||
g.options.chooseRegions ||
g.options.chooseColors
)
throw Error('Baseline supports three-player Germany with automatic setup only');
}
function observe(g, seat) {
assertScope(g);
const order = [seat, (seat + 1) % 3, (seat + 2) % 3];
const s = [
...onehot(g.phase, PHASES),
g.round / 20,
g.step / 3,
+(g.options.variant === 'recharged'),
+g.options.fastBid,
g.cardsLeft / 50,
+g.nextCardWeak,
(g.options.fastBid ? 0 : g.currentBid || 0) / 100,
(g.minimunBid || 0) / 100,
...onehot(g.auctioningPlayer, order),
g.citiesToEndGame / 25,
g.citiesToStep2 / 20,
];
for (const r of RES)
s.push(
(g[r + 'Market'] || 0) / 24,
(g[r + 'Supply'] || 0) / 24,
...(g[r + 'Prices'] || []).slice(0, 24).map((x) => x / 20),
...Array(Math.max(0, 24 - (g[r + 'Prices'] || []).length)).fill(0)
);
for (const i of order) {
const p = g.players[i];
s.push(
p.money / 500,
p.cities.length / 22,
p.housesLeft / 22,
p.citiesPowered / 22,
g.playerOrder.indexOf(i) / 2,
+p.skipAuction,
+p.passed,
(g.options.fastBid ? 0 : p.bid || 0) / 100
);
for (const r of RES) s.push((p[r + 'Left'] || 0) / 24, (p[r + 'Capacity'] || 0) / 24);
s.push(p.hybridCapacity / 24);
for (let j = 0; j < 4; j++) s.push(...plant(p.powerPlants[j]));
}
for (let i = 0; i < 4; i++) s.push(...plant(g.actualMarket[i]), ...plant(g.futureMarket[i]));
s.push(...plant(g.chosenPowerPlant));
for (const city of CITIES)
s.push(
+g.map.cities.some((c) => c.name === city),
...order.map((i) => +g.players[i].cities.some((c) => c.name === city))
);
if (!s.every(Number.isFinite)) throw Error('Non-finite observation');
return s;
}
function allLegal(g, seat) {
return Object.entries(g.players[seat].availableMoves || {}).flatMap(([name, items]) =>
(items || []).map((data) => ({ name, data }))
);
}
function candidates(g, seat) {
const all = allLegal(g, seat),
bids = all.filter((a) => a.name === 'Bid');
if (bids.length <= 48) return all;
const min = bids[0].data,
max = bids.at(-1).data;
return all.filter((a) => a.name !== 'Bid' || a.data < min + 8 || a.data % 10 === 0 || a.data === max);
}
function actionFeatures(g, seat, a) {
const d = a.data,
p = g.players[seat];
const pp =
a.name === 'ChoosePowerPlant'
? g.actualMarket.find((x) => x.number === d)
: a.name === 'DiscardPowerPlant'
? p.powerPlants.find((x) => x.number === d)
: a.name === 'UsePowerPlant'
? p.powerPlants.find((x) => x.number === d.powerPlant)
: g.chosenPowerPlant;
const cost = a.name === 'Bid' ? d : a.name === 'BuyResource' ? resourcePrice(g, d.resource) : d?.price || 0;
return [
...onehot(a.name, TYPES),
cost / 500,
cost / Math.max(p.money, 1),
...onehot(d?.resource || (typeof d === 'string' ? d : ''), RES),
...plant(pp),
...onehot(d?.name, CITIES),
(d?.citiesPowered || 0) / 20,
...RES.map((r) => (d?.resourcesSpent || []).filter((x) => x === r).length / 4),
];
}
function resourcePrice(g, resource, offset = 0) {
const prices = g[resource + 'Prices'];
const count = g[resource + 'Market'];
return prices && count > offset ? prices[prices.length - count + offset] : 20;
}
function fuelDemand(g, p) {
const target = Math.min(Math.max(p.cities.length, Math.min(3, capacity(p))), capacity(p));
let powered = 0;
const need = Object.fromEntries(RES.map((r) => [r, 0]));
const ps = [...p.powerPlants].sort((a, b) => fuelCost(g, a) / a.citiesPowered - fuelCost(g, b) / b.citiesPowered);
for (const pp of ps) {
if (powered >= target) break;
powered += pp.citiesPowered;
let resource = RES[pp.type];
if (pp.type === 4) resource = resourcePrice(g, 'coal') <= resourcePrice(g, 'oil') ? 'coal' : 'oil';
if (resource) need[resource] += pp.cost;
}
return need;
}
function fuelCost(g, pp) {
return (
pp.cost *
(pp.type === 4
? Math.min(resourcePrice(g, 'coal'), resourcePrice(g, 'oil'))
: RES[pp.type]
? resourcePrice(g, RES[pp.type])
: 0)
);
}
const capacity = (p) => p.powerPlants.reduce((n, x) => n + x.citiesPowered, 0);
function plantWorth(g, p, pp) {
let old = 0;
if (p.powerPlants.length >= 3) old = Math.min(...p.powerPlants.map((x) => x.citiesPowered));
const gain = Math.max(0, pp.citiesPowered - old);
const reserve = Math.max(12, Math.min(40, p.cities.length * 2 + 10));
const useful = gain > 0 || fuelCost(g, pp) < 3;
return useful ? Math.min(p.money - reserve, pp.number + gain * 5 - fuelCost(g, pp)) : 0;
}
function heuristicScore(g, seat, a) {
const p = g.players[seat],
d = a.data,
cap = capacity(p);
switch (a.name) {
case 'ChoosePowerPlant': {
const pp = g.actualMarket.find((x) => x.number === d);
const worth = plantWorth(g, p, pp);
return worth >= d ? 20 + pp.citiesPowered * 5 - fuelCost(g, pp) - d * 0.2 : -100 - d;
}
case 'Bid': {
const worth = Math.max(g.round === 1 ? g.minimunBid : 0, plantWorth(g, p, g.chosenPowerPlant));
if (d > worth) return -100 - d;
return g.options.fastBid ? 20 - Math.abs(worth - d) : 30 - d * 0.1;
}
case 'DiscardPowerPlant': {
const pp = p.powerPlants.find((x) => x.number === d);
return 10 - pp.citiesPowered * 5 + fuelCost(g, pp);
}
case 'DiscardResources':
return 10 + (p[d + 'Left'] || 0);
case 'BuyResource': {
const need = fuelDemand(g, p),
price = resourcePrice(g, d.resource);
return p[d.resource + 'Left'] < need[d.resource] && p.money - price >= Math.max(0, p.cities.length ? 0 : 12)
? 20 - price
: -100;
}
case 'Build': {
const desired =
p.money > 150 || g.round > 18
? g.citiesToEndGame
: Math.min(g.citiesToEndGame, cap + (p.money > 100 ? 1 : 0));
return p.cities.length < desired ? 30 - d.price * 0.5 : -100;
}
case 'UsePowerPlant':
return (
40 + (d.citiesPowered || 0) * 5 - (d.resourcesSpent || []).reduce((n, r) => n + resourcePrice(g, r), 0)
);
case 'Pass':
return 0;
default:
return 1;
}
}
function heuristic(g, seat, rng = () => 0.5) {
const a = candidates(g, seat);
let best = 0,
v = -Infinity;
a.forEach((x, i) => {
const score = heuristicScore(g, seat, x) + rng() * 0.01;
if (score > v) {
v = score;
best = i;
}
});
return { index: best, action: a[best] };
}
function outcome(g) {
const sorted = E.playersSortedByScore(g),
top = sorted[0],
w = g.players.map(
(p) =>
+(
p.citiesPowered === top.citiesPowered &&
p.money === top.money &&
p.cities.length === top.cities.length
)
);
return w.map((x) => x / w.reduce((a, b) => a + b, 0));
}
function start(seed, variant = 'original', fastBid = false) {
return E.setup(3, { map: 'Germany', variant, fastBid, showMoney: true }, seed);
}
module.exports = {
E,
CITIES,
TYPES,
RES,
observe,
allLegal,
candidates,
actionFeatures,
heuristic,
heuristicScore,
outcome,
start,
seedrandom,
resourcePrice,
fuelDemand,
fuelCost,
capacity,
};

4322
ai/data-audit.json Normal file

File diff suppressed because it is too large Load diff

73
ai/evaluate.py Normal file
View file

@ -0,0 +1,73 @@
import argparse, json, time, platform
from pathlib import Path
import numpy as np
from infer import Model, Node
p = argparse.ArgumentParser()
p.add_argument("model")
p.add_argument("--seeds", type=int, default=10)
p.add_argument("--opponent", default="heuristic", choices=["heuristic", "legacy"])
p.add_argument("--output", default="evaluation.json")
args = p.parse_args()
net = None if args.model == "heuristic" else Model(args.model)
node = Node("arena.cjs")
results = []
latency = []
start = time.perf_counter()
try:
for variant in ["original", "recharged"]:
for sealed in [False, True]:
for seed in range(args.seeds):
for seat in range(3):
config = {
"op": "reset",
"seed": "heldout-arena-v1-" + str(seed),
"variant": variant,
"sealed": sealed,
"seat": seat,
"opponent": args.opponent,
}
o = node.call(config)
while not o["done"]:
t = time.perf_counter()
action = (
net.predict(o["state"], o["actions"])[0]
if net
else o["heuristic"]
)
latency.append((time.perf_counter() - t) * 1000)
o = node.call({"op": "step", "action": action})
results.append({**config, **o})
group = [
r for r in results if r["variant"] == variant and r["sealed"] == sealed
]
print(
json.dumps(
{
"variant": variant,
"sealed": sealed,
"games": len(group),
"win_rate": np.mean([r["win"] for r in group]),
"truncated": sum(r["truncated"] for r in group),
}
),
flush=True,
)
finally:
node.close()
report = {
"model": args.model,
"opponent": args.opponent,
"platform": platform.platform(),
"games": len(results),
"win_rate": np.mean([r["win"] for r in results]),
"truncated": sum(r["truncated"] for r in results),
"seconds": time.perf_counter() - start,
"inference_ms": {
k: float(np.percentile(latency, v))
for k, v in [("p50", 50), ("p95", 95), ("p99", 99)]
},
"results": results,
}
Path(args.output).write_text(json.dumps(report, indent=2))
print(json.dumps({k: v for k, v in report.items() if k != "results"}))

63
ai/export-remote.cjs Normal file
View file

@ -0,0 +1,63 @@
const fs = require('node:fs'),
{ parseEnv } = require('node:util'),
{ createRequire } = require('node:module'),
{ createHash } = require('node:crypto');
const { MongoClient } = createRequire('/home/bgs/boardgamers-mono/apps/api/package.json')('mongodb');
(async () => {
const env = parseEnv(fs.readFileSync('/home/bgs/boardgamers-mono/apps/api/.env', 'utf8'));
const c = await MongoClient.connect(env.dbUrl);
try {
for await (const g of c
.db(env.dbName || 'bgs')
.collection('games')
.find(
{
'game.name': 'powergrid',
status: 'ended',
'game.options.map': 'Germany',
'options.setup.nbPlayers': 3,
'options.meta.unlisted': { $ne: true },
},
{ projection: { _id: 1, game: 1, options: 1, data: 1, players: 1 } }
)
.maxTimeMS(20000)) {
const d = g.data;
if (!d || typeof d !== 'object') continue;
const cleanPlayer = (p) => ({
money: p.money,
citiesPowered: p.citiesPowered,
cities: p.cities?.map((c) => c.name).sort(),
powerPlants: p.powerPlants?.map((p) => p.number).sort((a, b) => a - b),
});
console.log(
JSON.stringify({
id: createHash('sha256')
.update('powergrid-ai-v1:' + g._id)
.digest('hex')
.slice(0, 20),
version: g.game.version,
options: d.options || g.game.options,
seed: d.seed || g.options.setup.seed,
players: g.players.map((p) => ({
bot: !!p.isBot,
dropped: !!p.dropped,
quit: !!p.quit,
rating: p.elo?.initial,
ranking: p.ranking,
})),
moves: (d.log || [])
.filter((x) => x.type === 'move')
.map((x) => ({ player: x.player, move: x.move })),
final: d.players.map(cleanPlayer),
phase: d.phase,
round: d.round,
})
);
}
} finally {
await c.close();
}
})().catch((e) => {
console.error(e.name, e.code);
process.exit(1);
});

25
ai/features.cjs Normal file
View file

@ -0,0 +1,25 @@
const c = require('./core-v2.cjs'),
readline = require('node:readline');
(async () => {
for await (const line of readline.createInterface({ input: process.stdin })) {
try {
const q = JSON.parse(line),
g = q.state,
p = q.player;
if (!Number.isInteger(p) || !g.currentPlayers.includes(p))
throw Error('Player cannot act in this position');
const moves = c.candidates(g, p);
if (!moves.length) throw Error('No legal actions');
console.log(
JSON.stringify({
state: c.observe(g, p),
actions: moves.map((a) => c.actionFeatures(g, p, a)),
moves,
playerOrder: [p, (p + 1) % 3, (p + 2) % 3],
})
);
} catch (e) {
console.log(JSON.stringify({ error: e.message }));
}
}
})();

72
ai/generate.cjs Normal file
View file

@ -0,0 +1,72 @@
const fs = require('node:fs'),
c = require('./core.cjs');
const count = Number(process.env.GAMES || 600),
rng = c.seedrandom('dataset-v1'),
out = fs.openSync(process.argv[2] || 'dataset.jsonl', 'w');
let samples = 0,
completed = 0,
truncated = 0;
function writeEpisode(rows, g, id) {
const result = c.outcome(g);
for (const row of rows) {
row.value = [row.seat, (row.seat + 1) % 3, (row.seat + 2) % 3].map((i) => result[i]);
row.game = id;
fs.writeSync(out, JSON.stringify(row) + '\n');
samples++;
}
}
for (let i = 0; i < count; i++) {
let g = c.start('train-v1-' + i, i % 2 ? 'recharged' : 'original', i % 4 < 2),
rows = [],
n = 0;
while (!c.E.ended(g) && n++ < 1600) {
const seat = g.currentPlayers[0],
a = c.candidates(g, seat),
h = c.heuristic(g, seat, rng);
if (a.length > 1 && rng() < 0.4)
rows.push({
state: c.observe(g, seat),
actions: a.map((x) => c.actionFeatures(g, seat, x)),
target: h.index,
seat,
weight: 1,
});
let index = rng() < 0.015 ? Math.floor(rng() * a.length) : h.index;
g = c.E.move(g, a[index], seat);
}
if (c.E.ended(g)) {
writeEpisode(rows, g, 'synthetic-' + i);
completed++;
} else truncated++;
if (i % 100 === 99) console.error(JSON.stringify({ games: i + 1, samples, completed, truncated }));
}
const path = 'ai/private-data/verified-games.jsonl';
if (fs.existsSync(path))
for (const line of fs.readFileSync(path, 'utf8').split('\n').filter(Boolean)) {
const h = JSON.parse(line);
if (h.options.chooseColors || h.options.chooseRegions || h.options.randomizeMap) {
console.error(JSON.stringify({ skippedHumanGame: h.id, reason: 'unsupported setup' }));
continue;
}
let g = c.E.setup(3, h.options, h.seed),
rows = [];
for (const m of h.moves) {
const seat = m.player,
a = c.candidates(g, seat),
target = a.findIndex(
(x) => JSON.stringify(x.data) === JSON.stringify(m.move.data) && x.name === m.move.name
);
if (target >= 0 && a.length > 1)
rows.push({
state: c.observe(g, seat),
actions: a.map((x) => c.actionFeatures(g, seat, x)),
target,
seat,
weight: 1.5,
});
g = c.E.move(g, m.move, seat);
}
writeEpisode(rows, g, 'human-' + h.id);
}
fs.closeSync(out);
console.error(JSON.stringify({ completed, truncated, samples }));

95
ai/infer.py Normal file
View file

@ -0,0 +1,95 @@
import json, sys, subprocess, argparse, time, hashlib
from pathlib import Path
import numpy as np
import onnxruntime as ort
ROOT = Path(__file__).resolve().parents[1]
class Model:
def __init__(self, path, threads=1):
self.sha256 = hashlib.sha256(Path(path).read_bytes()).hexdigest()
options = ort.SessionOptions()
options.intra_op_num_threads = threads
options.inter_op_num_threads = 1
self.session = ort.InferenceSession(
str(path), sess_options=options, providers=["CPUExecutionProvider"]
)
def predict(self, state, actions):
a = np.asarray(actions, dtype=np.float32)[None]
s = np.asarray(state, dtype=np.float32)[None]
mask = np.ones(a.shape[:2], dtype=bool)
scores, values = self.session.run(
None, {"state": s, "actions": a, "mask": mask}
)
return int(scores[0].argmax()), values[0].tolist()
class Node:
def __init__(self, script):
self.proc = subprocess.Popen(
["node", str(ROOT / "ai" / script)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
bufsize=1,
)
def call(self, q):
self.proc.stdin.write(json.dumps(q) + "\n")
self.proc.stdin.flush()
line = self.proc.stdout.readline()
if not line:
raise RuntimeError("Engine worker exited")
return json.loads(line)
def close(self):
self.proc.terminate()
self.proc.wait(timeout=5)
self.proc.stdin.close()
self.proc.stdout.close()
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("model")
args = p.parse_args()
model = Model(args.model)
node = Node("features.cjs")
try:
for line in sys.stdin:
q = {}
try:
decoded = json.loads(line)
if not isinstance(decoded, dict):
raise ValueError("Request must be a JSON object")
q = decoded
begin = time.perf_counter()
o = node.call(q)
if "error" in o:
raise ValueError(o["error"])
index, value = model.predict(o["state"], o["actions"])
print(
json.dumps(
{
"requestId": q.get("requestId"),
"revision": q.get("revision"),
"move": o["moves"][index],
"winProbabilities": value,
"valueStatus": "uncalibrated-selfplay-estimate",
"playerOrder": o["playerOrder"],
"model": Path(args.model).name,
"modelSha256": model.sha256,
"elapsedMs": (time.perf_counter() - begin) * 1000,
}
),
flush=True,
)
except Exception as e:
print(
json.dumps({"requestId": q.get("requestId"), "error": str(e)}),
flush=True,
)
finally:
node.close()

19
ai/launch-profile.sh Executable file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor l4x1 --timeout 2h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=profile-v1 --env GAMES=600 --env BC_EPOCHS=12 \
--env RL_UPDATES=16 --env ENVS=24 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=profile-v1 \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx onnxruntime
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"profile-source.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs
python -u ai/performance.py
'

19
ai/launch-smoke.sh Executable file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor l4x1 --timeout 2h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=optimized-smoke --env GAMES=32 --env BC_EPOCHS=1 \
--env RL_UPDATES=1 --env ENVS=64 --env WORKERS=4 --env BATCH_SIZE=1024 --env ROLLOUT_SAMPLES=2000 \
--label project=powergrid-ai --label stage=optimized-smoke \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"source-v2.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs
python -u ai/train.py
'

19
ai/launch-v2.sh Executable file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor l4x1 --timeout 2h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=baseline-v2 --env GAMES=600 --env BC_EPOCHS=12 \
--env RL_UPDATES=16 --env ENVS=64 --env WORKERS=4 --env BATCH_SIZE=1024 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=baseline-v2 \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"source-v4.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs
python -u ai/train.py
'

19
ai/launch.sh Executable file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor l4x1 --timeout 2h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=baseline-v1 --env GAMES=600 --env BC_EPOCHS=12 \
--env RL_UPDATES=16 --env ENVS=24 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=baseline-v1 \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"source-v1.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs
python -u ai/train.py
'

88
ai/package-results.py Normal file
View file

@ -0,0 +1,88 @@
"""Create the user-facing report from completed, measured runs."""
import argparse, json, hashlib, html, shutil, tarfile
from pathlib import Path
p = argparse.ArgumentParser()
p.add_argument("output")
args = p.parse_args()
out = Path(args.output)
out.mkdir(parents=True, exist_ok=True)
root = Path(__file__).resolve().parents[1]
runs = root / "ai/runs"
model = runs / "download/runs/baseline-v2"
summary = json.loads((runs / "v2-summary.json").read_text())
profile = json.loads((runs / "download/runs/baseline-v1/profile.json").read_text())
smoke = json.loads((runs / "8840u-serving-v2.json").read_text().split("\n", 1)[1])
cpu = json.loads((runs / "8840u-evaluation-v2.json").read_text())
parity = json.loads((runs / "parity-v2.json").read_text())
bench = json.loads((runs / "8840u-simulation-v2.json").read_text())
for name in [
"v2-summary.json",
"8840u-evaluation-v2.json",
"8840u-serving-v2.json",
"8840u-simulation-v2.json",
"parity-v2.json",
]:
shutil.copy2(runs / name, out / name)
shutil.copy2(root / "ai/README.md", out / "README.md")
shutil.copy2(model / "metrics.json", out / "training-metrics.json")
shutil.copy2(model / "schema.json", out / "schema.json")
bundle = runs / "serving-bundle"
for name in [
"core.cjs",
"arena.cjs",
"features.cjs",
"infer.py",
"evaluate.py",
"benchmark.cjs",
"test.cjs",
"serving-smoke.py",
"requirements-serve.txt",
"README.md",
]:
shutil.copy2(root / "ai" / name, bundle / "ai" / name)
shutil.copy2(model / "selfplay.onnx", bundle / "selfplay.onnx")
shutil.copy2(model / "schema.json", bundle / "schema.json")
with tarfile.open(out / "powergrid-ai-serving-v2.tgz", "w:gz") as tf:
for item in sorted(bundle.rglob("*")):
if item.is_file() and "__pycache__" not in item.parts:
tf.add(item, arcname=str(item.relative_to(bundle)))
manifest = {
"engine_revision": "365fc519903fa2b4e8c593eed6cc5f5f77b5332a",
"source_dataset_commit": "65ecfa063c272bd72a805d45f4ba55dc84a28f42",
"source_archive": "source-v4.tgz",
"source_sha256": hashlib.sha256((runs / "source-v4.tgz").read_bytes()).hexdigest(),
"job": "https://huggingface.co/jobs/coyotte508/6abd0cba404719ba3761324e",
"schema": 2,
"model_sha256": hashlib.sha256((model / "selfplay.onnx").read_bytes()).hexdigest(),
"deployment": "Research worker only; production bot unchanged",
"files": {
f.name: hashlib.sha256(f.read_bytes()).hexdigest()
for f in out.iterdir()
if f.is_file() and f.name not in ["report.html", "manifest.json"]
},
}
(out / "manifest.json").write_text(json.dumps(manifest, indent=2))
rows = "".join(
f"<tr><td>{html.escape(Path(r['model']).stem)}</td><td>{html.escape(r['opponent'])}</td><td>{r['win_rate']:.1%}</td><td>{(format(r['seed_cluster_bootstrap_95pct'][0], '.1%') + '–' + format(r['seed_cluster_bootstrap_95pct'][1], '.1%')) if r['seed_cluster_bootstrap_95pct'] else 'Not estimated (identical outcomes)'}</td><td>{r['truncated']}</td></tr>"
for r in summary
)
rollouts = profile["rollouts"]
speed = rollouts[2]["decisions_per_second"] / rollouts[0]["decisions_per_second"]
train_speed = (
profile["training"][1]["samples_per_second"]
/ profile["training"][0]["samples_per_second"]
)
report = f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Powergrid AI baseline</title><style>body{{font:17px/1.6 system-ui,sans-serif;max-width:1050px;margin:40px auto;padding:0 24px;color:#19302a;background:#f5f7f2}}h1,h2{{line-height:1.2}}.cards{{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px}}.card,section{{background:white;padding:22px;border:1px solid #d4e1d8;border-radius:12px;margin:16px 0}}.metric{{font-size:30px;font-weight:700}}table{{width:100%;border-collapse:collapse;font-size:15px}}th,td{{padding:10px;text-align:left;border-bottom:1px solid #d4e1d8}}.scroll{{overflow:auto}}a{{color:#176145}}code{{overflow-wrap:anywhere}}.note{{background:#fff4da;padding:18px;border-radius:8px}}</style><h1>Powergrid AI: executable baseline</h1><p>30 September 2026 · Germany · 3 players · original / Recharged · open / sealed auctions</p><p class="note"><b>CPU deployment is feasible. Playing strength is not ready for production.</b> The existing engine bot remains the baseline to beat. These value estimates are not calibrated for player analysis.</p><div class="cards"><div class="card"><div class="metric">{speed:.1f}×</div>Rollout throughput improvement in the HF microbenchmark</div><div class="card"><div class="metric">{train_speed:.1f}×</div>Optimizer sample throughput with batch 1,024 versus 256</div><div class="card"><div class="metric">{smoke["warm_end_to_end_ms"]["p95"]:.2f} ms</div>8840U persistent worker p95, including state encoding and IPC</div></div>
<section><h2>Measured playing strength</h2><p>Each row is 480 games: 40 unseen seeds × 3 seat rotations × 4 rule combinations. One model faces two bots of the listed type. Ties split win credit. The intervals resample whole seed groups, retaining correlations between seats and rule variants.</p><div class="scroll"><table><tr><th>Model</th><th>Opponents</th><th>Win share</th><th>95% seed-bootstrap interval</th><th>Truncated</th></tr>{rows}</table></div><p>This remains a small baseline experiment. Beating the new heuristic does not establish human-level play; performance against the existing bot is the relevant deployment gate.</p></section>
<section><h2>What was built and checked</h2><ul><li>Reproducible JavaScript simulator, heuristic, masked candidate-scoring policy, whole-game imitation split, multi-player self-play, ONNX export and CPU worker.</li><li>All 4,007 game records counted. 66 candidate Germany replays inspected; 33 match the current engine exactly. Corrected training uses 32 supported historical games, with one color-draft game excluded.</li><li>Schema v2 covers both Germany city lists (44 cities), including the Recharged replacements Mainz and Stralsund. Bids remain sealed in model observations; other players’ money is intentionally visible.</li><li>{smoke["requests"]} end-to-end worker requests returned legal actions; {cpu["games"]} CPU arena games completed on the 8840U. Pure model inference p95: {cpu["inference_ms"]["p95"]:.3f} ms. Cold first request: {smoke["first_request_including_startup_ms"]:.0f} ms.</li><li>PyTorch / ONNX maximum absolute error: {max(x["max_abs_error"] for x in parity.values()):.2g}; all checked action choices agree.</li><li><code>minipc-wg</code> now reaches the verified 8840U at WireGuard address <code>10.90.0.3</code>.</li></ul></section>
<section><h2>Why resource utilization was low</h2><p>The initial configuration used one Node worker, 24 environments and optimizer batches of 256. This compact model alternates simulation and optimization, so GPU work arrives in bursts. Four workers and 256 environments reached {rollouts[2]["decisions_per_second"]:,.0f} decisions/s versus {rollouts[0]["decisions_per_second"]:,.0f}; eight workers offered no gain. Python feature packing and JSON communication still take substantial time.</p><p>These are component microbenchmarks, not an end-to-end speedup guarantee. Larger optimizer batches also reduce gradient updates per epoch. The replacement training run uses four workers, 64 environments and batch 1,024; 256 environments are more suitable when collecting substantially larger completed-episode batches.</p></section>
<section><h2>Recommendation</h2><p>Keep the JS engine authoritative and train on HF Jobs. Run persistent ONNX workers on the 8840U; this model needs neither its GPU nor NPU. Before production, train against the existing bot and a mixture of frozen opponents, use more completed games, and gate releases on held-out arena results. Expand maps/player counts with a new variable-size representation and retraining.</p><p>For round-by-round analysis, train and calibrate that target separately. The current three-way value output estimates outcomes under its training opponents; it is not an objective score evaluation.</p></section>
<section><h2>Artifacts</h2><p><a href="powergrid-ai-serving-v2.tgz">Serving bundle</a> · <a href="README.md">Setup and worker contract</a> · <a href="v2-summary.json">Evaluation details</a> · <a href="throughput-profile.json">Throughput profile</a> · <a href="manifest.json">Hashes and provenance</a> · <a href="{manifest["job"]}">HF training job</a></p><p>One JSONL request chooses one atomic move. The platform must check the game revision, validate the move and commit it through its normal server path. No production routing was changed.</p></section></html>'''
(out / "report.html").write_text(report)
print(
json.dumps(
{"report": str(out / "report.html"), "model_sha256": manifest["model_sha256"]}
)
)

125
ai/performance.py Normal file
View file

@ -0,0 +1,125 @@
"""Run on HF Jobs: profile real engine rollouts, GPU batches and ONNX parity."""
import concurrent.futures, json, os, subprocess, time
from pathlib import Path
import numpy as np
import torch
import onnxruntime as ort
from huggingface_hub import hf_hub_download, HfApi
import train
repo = "coyotte508/powergrid-ai-germany-v1"
ck = torch.load(
hf_hub_download(repo, "runs/baseline-v1/imitation.pt"),
map_location="cpu",
weights_only=True,
)
train.AD = ck["action_dim"]
net = train.Policy(ck["state_dim"], train.AD).cuda().eval()
net.load_state_dict(ck["state_dict"])
class Worker:
def __init__(self, i):
self.p = subprocess.Popen(
["node", "ai/bridge.cjs"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
env={**os.environ, "SEED": f"profile-{i}"},
)
def call(self, q):
self.p.stdin.write(json.dumps(q) + "\n")
self.p.stdin.flush()
return json.loads(self.p.stdout.readline())
results = []
sample = None
for workers, envs in [(1, 24), (1, 256), (4, 256), (8, 256)]:
pool = concurrent.futures.ThreadPoolExecutor(workers)
ws = [Worker(i) for i in range(workers)]
n = envs // workers
current = list(pool.map(lambda w: w.call({"op": "reset", "n": n}), ws))
timing = {"packing_gpu": 0.0, "engine_ipc": 0.0}
started = time.perf_counter()
decisions = 0
for step in range(120):
rows = [r for x in current for r in x["observations"]]
t = time.perf_counter()
with torch.no_grad():
logits, _ = net(*train.tensors(rows))
choices = (
torch.distributions.Categorical(logits=logits).sample().cpu().tolist()
)
timing["packing_gpu"] += time.perf_counter() - t
t = time.perf_counter()
current = list(
pool.map(
lambda pair: pair[1].call(
{"op": "step", "actions": choices[pair[0] * n : (pair[0] + 1) * n]}
),
enumerate(ws),
)
)
timing["engine_ipc"] += time.perf_counter() - t
decisions += len(rows)
seconds = time.perf_counter() - started
entry = {
"workers": workers,
"envs": envs,
"decisions_per_second": decisions / seconds,
"seconds": seconds,
**timing,
}
results.append(entry)
print(json.dumps(entry), flush=True)
sample = rows
for w in ws:
w.p.terminate()
w.p.wait()
pool.shutdown()
# Compare GPU optimization throughput including normal data packing.
optimizer = torch.optim.Adam(net.parameters(), lr=3e-4)
training = []
for size in [256, 1024]:
rows = (sample * ((size + len(sample) - 1) // len(sample)))[:size]
torch.cuda.synchronize()
t = time.perf_counter()
for _ in range(30):
logits, v = net(*train.tensors(rows))
loss = -logits.log_softmax(-1)[:, 0].mean() + v.square().mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()
torch.cuda.synchronize()
seconds = time.perf_counter() - t
training.append({"batch": size, "samples_per_second": 30 * size / seconds})
# Validate original checkpoint export with real observations and varying masks.
net.load_state_dict(ck["state_dict"])
net.eval()
session = ort.InferenceSession(
hf_hub_download(repo, "runs/baseline-v1/imitation.onnx"),
providers=["CPUExecutionProvider"],
)
errors = []
for n in [1, 7, 24]:
x = train.tensors(sample[:n])
feed = dict(zip(["state", "actions", "mask"], [a.cpu().numpy() for a in x]))
actual = session.run(None, feed)
with torch.no_grad():
expected = [a.cpu().numpy() for a in net(*x)]
errors.append(max(float(np.max(np.abs(a - b))) for a, b in zip(actual, expected)))
assert max(errors) < 1e-4, errors
out = Path("profile.json")
out.write_text(
json.dumps(
{"rollouts": results, "training": training, "onnx_max_abs_error": max(errors)},
indent=2,
)
)
print(out.read_text(), flush=True)
HfApi().upload_file(
repo_id=repo, path_or_fileobj=str(out), path_in_repo="runs/baseline-v1/profile.json"
)

71
ai/pool.py Normal file
View file

@ -0,0 +1,71 @@
"""Concurrent isolated JS engines with one batched GPU policy call per step."""
import json
import os
import subprocess
from concurrent.futures import ThreadPoolExecutor
class EnginePool:
def __init__(self, workers=1, seed="rollout-v1", script="ai/bridge.cjs"):
self.executor = ThreadPoolExecutor(workers)
self.processes = [
subprocess.Popen(
["node", script],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
bufsize=1,
env={**os.environ, "SEED": f"{seed}-worker-{i}"},
)
for i in range(workers)
]
self.sizes = []
@staticmethod
def _call(pair):
process, request = pair
process.stdin.write(json.dumps(request) + "\n")
process.stdin.flush()
line = process.stdout.readline()
if not line:
raise RuntimeError("Engine worker exited")
return json.loads(line)
def call(self, request):
workers = len(self.processes)
if request["op"] == "reset":
n = request["n"]
if n < workers:
raise ValueError("Need at least one environment per worker")
self.sizes = [n // workers + (i < n % workers) for i in range(workers)]
requests = []
offset = request.get("offset", 0)
for n in self.sizes:
requests.append({**request, "n": n, "offset": offset})
offset += n
else:
requests = []
offset = 0
for n in self.sizes:
requests.append(
{"op": "step", "actions": request["actions"][offset : offset + n]}
)
offset += n
if offset != len(request["actions"]):
raise ValueError("Incorrect action count")
results = self.executor.map(self._call, zip(self.processes, requests))
observations, ended, offset = [], [], 0
for result, n in zip(results, self.sizes):
observations.extend(result["observations"])
ended.extend({**e, "env": e["env"] + offset} for e in result["ended"])
offset += n
return {"observations": observations, "ended": ended}
def close(self):
for process in self.processes:
process.terminate()
process.wait(timeout=5)
process.stdin.close()
process.stdout.close()
self.executor.shutdown()

502
ai/replay-audit.json Normal file
View file

@ -0,0 +1,502 @@
{
"total": 66,
"accepted": 33,
"acceptedSealed": 7,
"results": [
{
"id": "ab995e827dbb1e02ade0",
"version": 11,
"variant": "original",
"sealed": false,
"moves": 318,
"accepted": true
},
{
"id": "928d7ae9824c4e016bf6",
"version": 8,
"variant": "recharged",
"sealed": true,
"moves": 418,
"accepted": true
},
{
"id": "143b518757e189efc7e3",
"version": 8,
"variant": "recharged",
"sealed": false,
"moves": 351,
"accepted": true
},
{
"id": "6fcca63a2d0f6c9b306b",
"version": 5,
"variant": "recharged",
"sealed": false,
"moves": 388,
"accepted": true
},
{
"id": "607961f608892c628873",
"version": 3,
"variant": "recharged",
"sealed": true,
"moves": 380,
"accepted": true
},
{
"id": "2af648ee2c81b05daa9c",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "19ea5e783adbad9865d4",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "549451ce830ac138852f",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 391,
"accepted": true
},
{
"id": "54e393e828a04be005b8",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "d9a4234d28fdb5a8547b",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "eb708533d3ebd35d724a",
"version": 3,
"variant": "recharged",
"sealed": false,
"moves": 405,
"accepted": true
},
{
"id": "d4c097c3d06fe3975517",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "210a7d1dfd4b54d11c2c",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "c9537b635df301d5d05b",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "6f7f5a1973f1476ef44d",
"version": 3,
"variant": "original",
"sealed": true,
"moves": 369,
"accepted": true
},
{
"id": "44817ee07143fb7704c4",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 434,
"accepted": true
},
{
"id": "65ddf54509b49a8aa36f",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "0f9f19bd7730819956b3",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 440,
"accepted": true
},
{
"id": "a8250d7cd92ca6e0e8b3",
"version": 3,
"variant": "recharged",
"sealed": false,
"moves": 441,
"accepted": true
},
{
"id": "3b5968bedb92d0f8bd79",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "092879ca1fe46053827e",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "6bf265fe48dae34c6101",
"version": 3,
"variant": "recharged",
"sealed": true,
"moves": 372,
"accepted": true
},
{
"id": "09d086a97424a4a9b912",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "0488c48741af557764af",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "c448d8a0c7a6c9557f5f",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "142899655d055b4bc61e",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "e00b68c936f0ccdcd0e7",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "9dba6d7432a8f41e6083",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "4622adbf48bc58ce9ce2",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "4ca01233be2fd72067a0",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "2faf87e068025d212b9c",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "6cfdadead45769953298",
"version": 3,
"moves": 21,
"accepted": false,
"reason": "Wrong argument for the command Build"
},
{
"id": "8a881b6eaf108c303025",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "8df1a59ac269271dbc46",
"version": 3,
"moves": 22,
"accepted": false,
"reason": "Wrong argument for the command Build"
},
{
"id": "a74cabc1bba0781fd23f",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "1f9f4a3777e43af15c54",
"version": 3,
"moves": 19,
"accepted": false,
"reason": "Wrong argument for the command Build"
},
{
"id": "d018dbf18dbe82273a6b",
"version": 3,
"variant": "original",
"sealed": true,
"moves": 454,
"accepted": true
},
{
"id": "72c34fdee48fe10fdc7f",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "83416c44fa84004a5f45",
"version": 3,
"variant": "recharged",
"sealed": false,
"moves": 370,
"accepted": true
},
{
"id": "b76ed70e5aa1ae33b963",
"version": 3,
"variant": "recharged",
"sealed": false,
"moves": 405,
"accepted": true
},
{
"id": "54d6f0e36f565a708c9b",
"version": 3,
"variant": "recharged",
"sealed": false,
"moves": 390,
"accepted": true
},
{
"id": "718f4881af994c1faf9a",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 383,
"accepted": true
},
{
"id": "433cf6558b24a0bbdbf9",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 444,
"accepted": true
},
{
"id": "eb0cec0a066e8b33bad2",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 405,
"accepted": true
},
{
"id": "c2894a48c0a27444e114",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 436,
"accepted": true
},
{
"id": "31610763def175adf40b",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 538,
"accepted": true
},
{
"id": "1312804c48c9f82aa016",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 482,
"accepted": true
},
{
"id": "adf42d5b3442634e4caf",
"version": 3,
"variant": "recharged",
"sealed": true,
"moves": 381,
"accepted": true
},
{
"id": "5068dbfee4b33c649609",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 373,
"accepted": true
},
{
"id": "933fb07b88c95c2bbe96",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "b43887f769649ff3c89d",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "6c1d332a20633eea9f94",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "dcd4475ef997f56beb6f",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 427,
"accepted": true
},
{
"id": "e3d7fed6a1e2b332bf0a",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 430,
"accepted": true
},
{
"id": "32df38734319c7b5dfde",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 392,
"accepted": true
},
{
"id": "b019571e788c2fc32cd4",
"version": 3,
"variant": "recharged",
"sealed": true,
"moves": 381,
"accepted": true
},
{
"id": "2b63676563cda6368b48",
"version": 3,
"moves": 144,
"accepted": false,
"reason": "You are not allowed to run the command DiscardPowerPlant"
},
{
"id": "dc4da51d596babae1a94",
"version": 2,
"variant": "recharged",
"sealed": false,
"moves": 429,
"accepted": true
},
{
"id": "7034b82777f64af7059a",
"version": 3,
"variant": "original",
"sealed": false,
"moves": 320,
"accepted": true
},
{
"id": "b42f7181fe6174bfcf9b",
"version": 2,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "8232d800063a67651177",
"version": 2,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "0304865b35466d23992c",
"version": 3,
"moves": 0,
"accepted": false,
"reason": "not engine terminal"
},
{
"id": "b1befc19a57d12d4a1a0",
"version": 2,
"variant": "recharged",
"sealed": false,
"moves": 418,
"accepted": true
},
{
"id": "6bdc5e3f925879f358b3",
"version": 2,
"moves": 0,
"accepted": false,
"reason": "dropped/quit/bot"
},
{
"id": "21040a462644ef9ce599",
"version": 2,
"variant": "original",
"sealed": false,
"moves": 397,
"accepted": true
},
{
"id": "48965364741e57901f71",
"version": 2,
"variant": "original",
"sealed": false,
"moves": 354,
"accepted": true
}
]
}

View file

@ -0,0 +1,3 @@
numpy==2.4.6; python_version < "3.12"
numpy==2.5.3; python_version >= "3.12"
onnxruntime==1.30.0

48
ai/serving-smoke.py Normal file
View file

@ -0,0 +1,48 @@
"""Exercise the full persistent JSONL worker; validate returned engine actions."""
import json, subprocess, sys, time
from pathlib import Path
import numpy as np
root = Path(__file__).resolve().parents[1]
generate = """const c=require('./ai/core.cjs');for(const variant of ['original','recharged'])for(const sealed of [false,true]){let g=c.start('serving-smoke',variant,sealed),rng=c.seedrandom('smoke'),seen=new Set();for(let n=0;n<1600&&!c.E.ended(g);n++){const p=g.currentPlayers[0],key=g.phase+':'+Math.min(g.round,3);if(!seen.has(key)){seen.add(key);console.log(JSON.stringify({state:g,player:p,revision:n,requestId:variant+'-'+sealed+'-'+n}));}g=c.E.move(g,c.heuristic(g,p,rng).action,p);}}"""
requests = [
json.loads(l)
for l in subprocess.check_output(
["node", "-e", generate], cwd=root, text=True
).splitlines()
]
p = subprocess.Popen(
[sys.executable, str(root / "ai/infer.py"), sys.argv[1]],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
latency = []
checks = []
for q in requests:
t = time.perf_counter()
p.stdin.write(json.dumps(q) + "\n")
p.stdin.flush()
r = json.loads(p.stdout.readline())
latency.append((time.perf_counter() - t) * 1000)
assert "error" not in r, r
assert r["requestId"] == q["requestId"] and r["revision"] == q["revision"]
assert abs(sum(r["winProbabilities"]) - 1) < 1e-5
checks.append({"state": q["state"], "player": q["player"], "move": r["move"]})
p.stdin.close()
p.wait(timeout=10)
validate = """const c=require('./ai/core.cjs'),fs=require('fs');for(const q of JSON.parse(fs.readFileSync(0,'utf8'))){if(!c.allLegal(q.state,q.player).some(x=>JSON.stringify(x)===JSON.stringify(q.move)))throw Error('Illegal move');c.E.move(q.state,q.move,q.player);}console.log('all legal');"""
subprocess.run(
["node", "-e", validate], input=json.dumps(checks), cwd=root, text=True, check=True
)
report = {
"requests": len(requests),
"first_request_including_startup_ms": latency[0],
"warm_end_to_end_ms": {
k: float(np.percentile(latency[1:], v))
for k, v in [("p50", 50), ("p95", 95), ("p99", 99)]
},
"all_moves_legal": True,
}
print(json.dumps(report, indent=2))

103
ai/strong/README.md Normal file
View file

@ -0,0 +1,103 @@
# Strong-policy research (active)
> Research paused. Start with the [4 October 2026 handoff](../RESUME.md) for current status, pinned artifacts and resumption instructions.
The target is substantially stronger play, not merely beating the engine's default bot. No strength claim is made from the first prototype. Training runs on HF Jobs; CPU inference and correctness checks run locally and on the 8840U.
## Critical diagnosis
The first heuristic incorrectly read `BuyResource.data.price`, which the engine does not provide. The resulting NaN comparison suppressed fuel buying. It also used the beginning of a price schedule instead of the slot indexed by remaining market stock. Both are fixed and covered by a test against the engine's actual cash deduction. The corrected heuristic wins 85.1% against the default bot over 960 games. Thus the default bot is only a sanity check.
`../core-v2.cjs` preserves the old feature semantics solely for compatibility with old exported research artifacts. New strong models use the corrected core and this directory's features. Do not evaluate new models with old feature encoders.
## Model information and strategy
Schema 3 has 738 state features and 96 features per candidate action. All opponents' money is visible by user instruction. Hidden deck order, random seed, sealed bid amounts and queued plans are excluded.
Feature revision `3.1-uranium39` corrects the effective uranium refill after plant 39 has been bought in Recharged Germany (also handled by the helper for Italy). The engine's persistent flag matters even after that plant is discarded. A test compares the feature's predicted refill with a real engine round transition. Older checkpoints use frozen revision `3.0`; the arena and worker select the matching encoder from ONNX metadata. The old encoder's output was verified byte-for-byte against the archived runtime over 427 positions. Unknown revisions and mismatched data fail explicitly. Revision 3.0 datasets and source bundles are retained for reproducibility, not silently reinterpreted.
The observation explicitly includes all players' cities, plants, fuel, money, current order and remaining actors; per-resource replenishment for every step; current prices and capped refill; and generation capacity with current fuel. Territory features describe each player's presence in map-defined regions/islands and their remaining legal building slots. Building actions include the projected next order with highest-plant tie breaking. Terminal winning is the optimization objective; there is no reward for indiscriminately adding cities.
`public-graph.cjs` exports map topology, owner vectors, slot rules, edges, islands and crossing costs for subsequent multi-map model work. UK/Ireland territory behavior is tested, but the current trained policy remains Germany/three players. Exporting generic map features does not establish playing strength on another map.
## Opponents and training
The economic opponent enumerates feasible plant/fuel combinations and considers purchase cost, income, generation capacity, resource replenishment and stockpiling. A rush variant and the corrected heuristic supply different styles. The residual policy starts with economic action scores and learns neural corrections, rather than initially relearning how to buy fuel from scratch.
PPO collects complete episodes against a mixture of fixed bots, self-play and frozen earlier neural policies. The four learners vary seed, learning rate, entropy and prior regularization. Each is configured for 300 updates × 128 completed games. Development evaluation uses 96 games per opponent every 20 updates. It selects checkpoints; it is not the final test.
A separate rollout-search opponent uses the engine's public-information scenario sampler and evaluates counterfactual actions across sampled unknown decks and sealed bids. Its choices are tested for invariance to the actual hidden deck and bids. The initial search benchmark is held separately from training.
The search reference scored 64.8% against the economic bot and 76.3% against the corrected heuristic, 240 games each with no truncations. Bootstrap 95% intervals, clustered by the 20 independent deals, were [57.9%, 71.7%] and [70.8%, 81.3%]. The B learner's update-20 checkpoint scored 42.2% against the economic bot on 480 fresh paired games (40 deals; interval [38.1%, 46.3%]). These are development/screening results, not a final strength claim; the comparison also uses different deals.
Four HF CPU jobs generated a separate search-teacher dataset: 512 games, 25,268 strategic positions, 6,769 disagreements with the economic teacher, zero truncated games. `distill.py` trains on HF GPUs, splitting whole games for validation and selecting checkpoints using actual arena performance. Its seeds do not overlap the reference benchmark, screening, or reserved final test.
The first distillation run deteriorated after epoch 5. Its epoch-30 model scored 8.6% against the economic bot on 480 screening games. Restricting its learned corrections to auction/build decisions raised that to 22.3% on exactly the same deals, still worse than the economic prior. This isolates harmful changes in unsupervised phases as one contributor, not a complete explanation. The next dataset covers every phase and uses 12 search samples instead of four. Hard labels and distributions over counterfactual action values are separate experiments; no improvement is assumed in advance.
The high-exploration league runs C and D were stopped after sustained regression around updates 60–80, retaining their best checkpoints. A and B completed all 300 updates. The neural B20 checkpoint scored 23.8% against two search opponents over 240 paired screening games (20 deals; 95% interval [17.1%, 30.4%]). Thus it has not passed the strength gate.
B160 subsequently scored 46.0% against the economic bot and 40.4% against two B20 neural opponents, each over 480 paired screening games (40 independent deals) with no truncations. B20 with 16-sample search scored 47.9% against two four-sample search opponents on 96 screening games (eight deals; interval [36.5%, 59.4%]), but its original/open subset was only 25%; broader evaluation is needed. These runs use their archived revision-3.0 runtime. B160 scored 47.9% with 16 samples and 61.5% with 48 samples against the four-sample reference, each over 96 games/eight deals. The 48-sample interval is [53.6%, 71.4%]; all four rule subsets exceeded 54%. This remains a small development test against a limited reference.
The corrected revision-3.1 dataset (`search-teacher-v3`) contains 247,104 decisions from 2,048 complete games, with 33,130 search/economic disagreements and no truncations. It includes all phases and uses 12 search samples per strategic decision. Hard-label and uncertainty-preserving distillation completed separately on HF Jobs. Their best checkpoints scored 37.9% and 42.5%, respectively, against the corrected economic opponent over 480 paired screening games each. The corrected soft-label checkpoint is the starting point for two new PPO refinements, with an anchor to its initial policy; one includes search opponents and restricts learned corrections to strategic phases. The new dataset replaces the intermediate revision-3.0 all-phase dataset for corrected-model training.
## Evidence required before declaring strength
- Robust gains over the economic, corrected-heuristic, rush, and frozen neural opponents—not just the default bot.
- Independent matches against the search reference, with confidence intervals and each rule combination reported separately.
- Fresh final-test seeds, balanced seats, original/Recharged and open/sealed auctions, no silent dropping of failed or truncated games.
- Tactical and information-boundary tests, ONNX parity, and measured full-worker latency on the 8840U.
- Human/expert matches would still be needed to substantiate an expert-level claim. Other maps need training and validation, even though their topology can be encoded.
## Runtime
The initial whole-engine JavaScript simulation benchmark was already fast. Repeated economic and regional feature calculations were a larger bottleneck. Hoisting them out of candidate-action loops made the feature benchmark 2.2× faster while preserving the exact output hash across 1,786 positions. A Rust rewrite remains an option if later profiling warrants it.
`infer.py` serves schema 3 over persistent JSONL; it preserves the same revision-validation obligation as the baseline worker. `evaluate.py` runs independent CPU matches. The current policies are research artifacts, not routed into production bot moves.
The arena supports `--opponent search` and `--opponent-model frozen.onnx`. Every deal is repeated across three candidate seats and four rule combinations. Results retain the deal identifier; confidence intervals resample deals, not correlated seat repeats. A same-checkpoint-in-all-seats test yields exactly 1/3 for every rule combination, including with uneven worker batches.
`serving-fixtures.cjs` and `benchmark-serving.py` check full JSONL round trips, legal responses, request/revision preservation and latency across all phases. The update-20 B model's ONNX logits matched PyTorch within 4.1e-6 on 39 search positions, with all argmax actions identical. CPU serving is still a research installation and its value outputs are uncalibrated.
On the 8840U, all 427 fixture requests returned legal moves: warm round-trip median 1.78 ms, p95 3.80 ms, cold start 167 ms. Optional 16-sample public-belief search, guided by the model's proposed move, had a p95 of 704 ms on 43 sampled requests, all legal. The guided variant is under independent arena evaluation; runtime feasibility alone is not evidence of strength. The isolated research installation is `~/powergrid-ai-strong` and has no production routing.
## Current deeper evaluation
Optional geographic proposals broaden build shortlists using connection costs and nearby available expansion sites, while preserving the classic reference for reproducibility. The independent `search_geo` opponent uses 16 sampled worlds and six proposals. Three configurations (B160/48 samples, corrected soft/48, corrected soft/16) each have four HF CPU shards of 48 games against it, sharing deals across configurations. These are development tests; reserved final seeds remain unused. Source v11 is pinned in `experiments.json`.
The corrected soft model passed PyTorch/ONNX parity across all 427 fixture positions: all actions identical, maximum logit error 3.82e-5 and value error 2.15e-6. On the 8840U, all requests were legal, with 1.87 ms median and 3.45 ms p95 full-worker response. With 48-sample geographic search, a smaller 43-position sample had a 2.02-second p95 and all legal moves. These timings support feasibility, not playing strength.
A bounded cache of static plant/fuel combinations was tested and removed: feature/search output hashes stayed identical, but measured runtime increased. No cache is included in source v11.
The later A260 checkpoint scored 67.5% against two economic opponents on the same 480 paired screening games (40 deals; 95% interval [62.3%, 72.5%]), compared with B160’s 46.0%. Its four rule subsets scored 57.5%, 65.8%, 71.7%, and 75.0%. The corrected refinement checkpoint at update 30 scored 54.7%. Both exports matched checkpoint actions on all 427 fixtures. A260 is now tested against frozen B160 and the deeper geographic search reference, both raw and with 48-sample guided search. These remain development tests; final seeds are reserved.
An explicit, limited 3.0 → 3.1 uranium-feature transfer experiment starts from pinned A260 weights. Ordinary checkpoint loading still rejects mismatched input revisions. The experiment evaluates its transferred starting policy before any gradient update, anchors refinement to that policy, records the original feature revision, and trains only on an HF GPU job. It does not relabel the old ONNX model or claim unchanged behavior. The complete 427-position corrected-soft/search-48 benchmark on the 8840U returned only legal moves with a 2.50-second p95. Raw A260 serving also passed all 427 positions at 3.74 ms p95.
The corrected soft policy with 16-sample geographic search scored 34.9% against two independent 16-sample geographic search opponents across 192 games/16 paired deals (95% interval [28.9%, 40.4%]), with no truncations. This is consistent with parity and does not pass the strength gate. A260 scored 42.5% against two frozen B160 policies over 480 games/40 deals ([37.5%, 47.9%]); original/open was only 30.0%, so the aggregate gain does not establish superiority in every ruleset.
A260 without inference-time search scored 34.1% against two 16-sample geographic search opponents over 192 games/16 deals ([29.7%, 38.5%]), consistent with parity. The completed A run selected update 299; it scored 62.2% against economic opponents and 44.2% against B160 on 480 paired games each. All A299/B160 rule subsets exceeded 39%, while A260/B160 original-open scored 30%; the tradeoff requires the separate search comparison rather than selecting only the highest economic score. The corrected full-refinement update-60 checkpoint reached 60.8% against economic opponents.
No further training experiments will be started until the current fixed cohort is compared: completed original A/B, corrected full refinement, search-opponent refinement, and corrected A260 refinement. Final-test seeds remain unused. A second bounded-cache experiment avoided freezing and copied returned arrays instead; six alternating benchmark runs retained identical search output hashes but showed no runtime gain, so that implementation was also discarded.
On the deeper reference, 48-sample geographic B160 scored 46.9% over 192 games/16 deals ([40.6%, 52.6%]); all four rule subsets were 45.8–47.9%. Corrected soft/48 scored 44.3% ([37.5%, 51.0%]), with all subsets above 33.3%. Both completed without truncations. The corrected A260 refinement at update 40 scored 72.3% against economic opponents ([67.7%, 76.7%]) and 40.6% against A260 ([37.1%, 44.2%]), 480 games each; its search-reference tests are pending.
`package-serving.py` builds a frozen CPU runtime archive with a model hash, feature revision, scope, source revision, per-file hashes, bundled engine dependencies, and JSONL startup instructions. An archive containing the corrected refinement checkpoint was extracted outside the worktree and passed nine legal-request checks each with zero and 48 search samples; every file hash matched. This is a packaging check, not a strength approval.
The final evaluation protocol is fixed in `final-protocol.json` before candidate selection or use of final seeds. It requires fresh balanced matches against six opponent styles, confidence intervals and minimum win shares, with per-rule gains rather than an aggregate-only pass. Source v13 adds search rollout diagnostics; a 12-game regression preserved every terminal state, action count and outcome while recording 22,927 rollouts with zero truncations. Historical reports without these counters explicitly mark them unreported.
A299 without search scored 51.0% against the geographic search reference over 192 games/16 deals ([44.8%, 57.8%]); corrected A260-refinement update 40 scored 47.9% ([41.1%, 54.2%]). Both had only 33.3% in Recharged sealed auctions, so neither result alone establishes superiority in every rule combination. The same A40 checkpoint remains best after its full 80-update training run. All A10G training jobs are complete; the H200 search-opponent experiment was subsequently stopped after regression, retaining its best checkpoint.
The corrected A40 policy passed all 427 CPU serving requests and checkpoint/export action comparisons. Its 48-sample serving mode had 2.38-second overall p95, 2.65-second p95 among the 161 actual search decisions, and a 3.04-second maximum over the fixture set.
## Frozen specialist configuration under evaluation
Applying 48-sample search to every rule combination reduced corrected A40’s aggregate search-reference result from 47.9% to 43.2%. It helped Recharged sealed (33.3% → 39.6%) but hurt the other three subsets. B160/search-48 was stronger and more balanced in that mode (45.8%). A CPU-only composition therefore combines corrected A40 for three rule combinations with B160 weights for Recharged sealed, and spends the 48-sample search budget only in that last combination. Both branches consume corrected feature revision 3.1. The B160 input correction is explicit in component provenance; it is a new, unapproved candidate whose playing strength must be measured, not an assertion that the old policy is unchanged. No gradient training occurs during composition.
The single ONNX export has SHA `b4cae14eb6e1aff72b16e5056983b2a57ad42984f4a27cf99dd70bb63e86be32`. `check-export.py` independently selected the expected component from the original engine options and verified all 427 positions (337 default, 90 Recharged sealed), along with ONNX/checkpoint action parity. Its isolated 8840U archive passed all 1,201 file hashes and all 427 legal requests. There were 33 actual search decisions: 2.36-second search-only p95, 2.57-second maximum; zero of 7,872 rollouts were truncated. Full-worker median was 2.42 ms, with search scoped to Recharged sealed. Development matches against the full opponent suite are running on immutable source v14; final seeds remain unused.
The completed full-distillation refinement’s update-119 checkpoint scored 65.9% against economic opponents and 35.7% against A260 over 480 games each; the latter interval [30.3%, 41.3%] did not establish a reliable gain. It is not replacing the stronger corrected A40 checkpoint.
The combined candidate’s first full development result is 76.7% against two economic opponents over 480 games/40 deals ([72.7%, 80.6%]). The unchanged three A40 branches reproduce their earlier win rates; the corrected B160/search branch scored 96.7% in Recharged sealed. All games completed, and none of 1,204,368 candidate search rollouts hit the step limit. Other opponent results are still required.
`launch-final.py` prepares 3,840 fresh games in 80 CPU shards and defaults to a dry run. It verifies the selected model hash, freezes the candidate/protocol/launcher fingerprint, and records each dispatched job for resumption without silently changing the test. `verify-final.py` recomputes paired-deal intervals from raw matches and audits model/configuration hashes, exact game counts, every seat/rule pairing, held-out seed prefixes, terminal credit, rollout reporting, parity, the 8840U benchmark, and the extracted archive. A negative check correctly rejected development seeds and a mismatched/unfrozen candidate.
The standalone archive provides `serve.py`, which reads the frozen manifest and checks the model hash before starting the worker. It was tested from an unrelated working directory with legal responses and the intended rule-specific search budget. Final CPU arenas use source v15 (policy unchanged; adds completed-game progress logs) and pinned dependencies.

55
ai/strong/arena-job.py Normal file
View file

@ -0,0 +1,55 @@
"""Pinned-checkpoint CPU evaluation on HF Jobs."""
import os
from pathlib import Path
import subprocess
import sys
from huggingface_hub import HfApi, hf_hub_download
repo = os.environ["HF_MODEL_REPO"]
model = hf_hub_download(
repo, os.environ["MODEL_PATH"], revision=os.environ["MODEL_REVISION"]
)
command = [
sys.executable,
"ai/strong/evaluate.py",
model,
"--players",
os.getenv("PLAYER_COUNT", "3"),
"--deal-offset",
os.getenv("DEAL_OFFSET", "0"),
"--opponent",
os.environ.get("OPPONENT", "search_geo"),
"--games",
os.environ.get("GAMES", "48"),
"--workers",
os.environ.get("WORKERS", "24"),
"--seed",
os.environ["EVAL_SEED"],
"--search-scope",
os.environ.get("SEARCH_SCOPE", "all"),
"--search-samples",
os.environ.get("SEARCH_SAMPLES", "0"),
"--output",
"evaluation.json",
]
if os.getenv("ASYNC_ARENA") == "1":
command.append("--async-rollout")
if os.getenv("DISABLE_SEARCH_PROPOSAL") == "1":
command.append("--disable-search-proposal")
if os.getenv("GEOGRAPHY") == "1":
command.append("--geographic-search")
if os.getenv("OPPONENT_MODEL_PATH"):
opponent = hf_hub_download(
repo,
os.environ["OPPONENT_MODEL_PATH"],
revision=os.environ["OPPONENT_MODEL_REVISION"],
)
command.extend(["--opponent-model", opponent])
subprocess.run(command, check=True)
assert Path("evaluation.json").exists()
HfApi().upload_file(
repo_id=repo,
path_or_fileobj="evaluation.json",
path_in_repo=f"runs/{os.environ['RUN_NAME']}/evaluation.json",
)

View file

@ -0,0 +1,74 @@
"""Uncertainty over independent deals, keeping seat/rule repeats together."""
import numpy as np
def win_summary(rows, key="gameSeed"):
groups = {}
for row in rows:
groups.setdefault(row[key], []).append(float(row["win"]))
totals = np.asarray([sum(v) for v in groups.values()])
counts = np.asarray([len(v) for v in groups.values()])
result = {
"games": len(rows),
"independent_seeds": len(groups),
"win_rate": float(totals.sum() / counts.sum()),
"truncated": sum(row["truncated"] for row in rows),
}
if len(groups) >= 2:
rng = np.random.default_rng(8501)
picks = rng.integers(len(groups), size=(10000, len(groups)))
draws = totals[picks].sum(axis=1) / counts[picks].sum(axis=1)
result["seed_bootstrap_95_interval"] = np.quantile(
draws, [0.025, 0.975]
).tolist()
else:
result["seed_bootstrap_95_interval"] = None
return result
def search_summary(rows):
if not all("searchStats" in row for row in rows):
return {"search_rollouts_reported": False}
totals = {}
for row in rows:
for role, stats in row["searchStats"].items():
target = totals.setdefault(
role, {"decisions": 0, "evaluations": 0, "truncated": 0}
)
for key in target:
target[key] += stats[key]
return {"search_rollouts_reported": True, "search_stats": totals}
def validate_pairs(rows, players):
"""Reject missing seats/rules and malformed outcomes, including in old reports."""
if players not in range(2, 7) or not rows:
raise ValueError("Expected nonempty 2–6 player arena")
expected = {
(seat, variant, sealed)
for seat in range(players)
for variant in ["original", "recharged"]
for sealed in [False, True]
}
deals = {}
for row in rows:
if row.get("playerCount", players) != players:
raise ValueError("Mixed player counts")
key = (row["seat"], row["variant"], row["sealed"])
seen = deals.setdefault(row["gameSeed"], set())
if key in seen or key not in expected:
raise ValueError("Duplicate or invalid paired match")
seen.add(key)
if len(row["value"]) != players or len(row["roles"]) != players:
raise ValueError("Wrong terminal vector or role count")
if row["roles"].count("learner") != 1 or row["roles"][row["seat"]] != "learner":
raise ValueError("Wrong candidate seat")
if any(not np.isfinite(v) or v < 0 or v > 1 for v in row["value"]):
raise ValueError("Invalid terminal credits")
if not row["truncated"] and not np.isclose(sum(row["value"]), 1):
raise ValueError("Terminal credits must sum to one")
if row["win"] != row["value"][row["seat"]]:
raise ValueError("Candidate win differs from terminal credit")
if any(seen != expected for seen in deals.values()):
raise ValueError("Incomplete paired deal")

71
ai/strong/async_pool.py Normal file
View file

@ -0,0 +1,71 @@
"""One engine per game; advance ready games without a global step barrier."""
from concurrent.futures import FIRST_COMPLETED, wait
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from pool import EnginePool
class AsyncEnginePool(EnginePool):
def __init__(self, workers, seed="rollout-v1", script="ai/strong/bridge.cjs"):
super().__init__(workers, seed, script)
self.pending = {}
self.ready = set()
self.started = False
def _submit(self, index, request):
future = self.executor.submit(self._call, (self.processes[index], request))
self.pending[future] = index
def _collect(self):
observations = [None] * len(self.processes)
ended = []
while self.pending:
done, _ = wait(self.pending, return_when=FIRST_COMPLETED)
# Also consume replies that finished during the wakeup.
done.update(f for f in self.pending if f.done())
for future in sorted(done, key=lambda f: self.pending[f]):
index = self.pending.pop(future)
result = future.result()
if len(result["observations"]) != 1:
raise ValueError("Async engines must own exactly one game")
row = result["observations"][0]
observations[index] = row
if row is not None:
self.ready.add(index)
for e in result["ended"]:
if e["env"] != 0:
raise ValueError("Unexpected worker-local environment index")
ended.append({**e, "env": index})
if self.ready:
break
# Completed games alone must not end the caller's loop while other
# engines still have requests in flight.
return {"observations": observations, "ended": ended}
def call(self, request):
count = len(self.processes)
if request["op"] == "reset":
if self.pending or self.ready:
raise ValueError("Cannot reset while a batch is active")
if request["n"] != count:
raise ValueError("Async training needs one worker per environment")
self.started = True
offset = request.get("offset", 0)
for index in range(count):
self._submit(index, {**request, "n": 1, "offset": offset + index})
elif request["op"] == "step":
actions = request["actions"]
if not self.started or len(actions) != count:
raise ValueError("Incorrect action count or missing reset")
supplied = {i for i, action in enumerate(actions) if action is not None}
if supplied != self.ready:
raise ValueError("Actions must match the ready environments exactly")
for index in sorted(self.ready):
self._submit(index, {"op": "step", "actions": [actions[index]]})
self.ready.clear()
else:
raise ValueError("Unknown operation")
return self._collect()

View file

@ -0,0 +1,29 @@
// Paired public scenarios across continuation policies and nested search budgets.
const fs = require('node:fs');
const search = require('./search.cjs');
const rows = fs.readFileSync(process.argv[2], 'utf8').trim().split('\n');
const row = JSON.parse(rows[Number(process.argv[3])]);
const continuation = process.argv[4],
batch = process.argv[5];
if (!['a', 'b'].includes(batch)) throw Error('Invalid batch');
const { state, player } = row.request;
const result = search.choose(state, player, {
samples: 384,
candidates: 6,
geography: true,
maxSteps: 2400,
seed: `teacher-reliability-v1-${row.fixtureIndex}-${batch}`,
continuation,
includeSamples: true,
});
console.log(
JSON.stringify({
fixtureIndex: row.fixtureIndex,
cell: row.cell,
round: state.round,
continuation,
batch,
samples: 384,
result,
})
);

View file

@ -0,0 +1,55 @@
"""HF diagnostic shard: repeat searches with shared scenarios across policies."""
import concurrent.futures
import hashlib
import itertools
import json
import os
from pathlib import Path
import subprocess
from huggingface_hub import HfApi
players = int(os.environ['PLAYER_COUNT'])
assert 2 <= players <= 6
fixtures = Path('ai/strong/fixtures/teacher-reliability-v1.jsonl')
rows = [json.loads(line) for line in fixtures.read_text().splitlines()]
indices = [i for i, r in enumerate(rows) if r['cell'][0] == players]
assert len(indices) == 12
tasks = list(itertools.product(indices, ['mixed', 'economic', 'heuristic'], ['a', 'b']))
def audit(task):
index, policy, batch = task
process = subprocess.run(['node', 'ai/strong/audit-search-budget.cjs', str(fixtures),
str(index), policy, batch], capture_output=True, text=True, check=True)
row = json.loads(process.stdout)
assert row['cell'][0] == players and row['continuation'] == policy and row['batch'] == batch
result = row['result']
assert len(result['sampleOutcomes']) * 384 == result['evaluations']
assert sum(v.count(None) for v in result['sampleOutcomes'].values()) == result['truncated']
for k, v in result['sampleOutcomes'].items():
assert len(v) == 384 and sum(x for x in v if x is not None) == result['values'][k]
return row
completed = []
with concurrent.futures.ThreadPoolExecutor(max_workers=24) as pool:
futures = [pool.submit(audit, task) for task in tasks]
for f in concurrent.futures.as_completed(futures):
completed.append(f.result())
print(json.dumps({'players': players, 'completed_searches': len(completed),
'requested_searches': len(tasks)}), flush=True)
completed.sort(key=lambda r: (r['fixtureIndex'], r['continuation'], r['batch']))
output = Path(f'results-{players}p.jsonl')
output.write_text(''.join(json.dumps(r) + '\n' for r in completed))
manifest = {'players': players, 'positions': 12, 'searches': len(completed), 'samples': 384,
'search_max_steps': 2400, 'fixture_sha256': hashlib.sha256(fixtures.read_bytes()).hexdigest(),
'output_sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
'evaluations': sum(r['result']['evaluations'] for r in completed),
'truncated': sum(r['result']['truncated'] for r in completed),
'scope': 'Reused development positions; nested budgets and shared public scenarios; no strength claim.'}
api = HfApi()
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=output,
path_in_repo=f'runs/teacher-reliability-v2/{output.name}')
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=json.dumps(manifest, indent=2).encode(),
path_in_repo=f'runs/teacher-reliability-v2/manifest-{players}p.json')
print(json.dumps(manifest), flush=True)

View file

@ -0,0 +1,28 @@
// Independent search batches on fixed development positions; no learning.
const fs = require('node:fs');
const search = require('./search.cjs');
const c = require('../core.cjs');
const rows = fs.readFileSync(process.argv[2], 'utf8').trim().split('\n');
const row = JSON.parse(rows[Number(process.argv[3])]);
const { state, player } = row.request;
const batches = ['a', 'b'].map((batch) => {
const result = search.choose(state, player, {
samples: 48,
candidates: 6,
geography: true,
maxSteps: 2400,
seed: `teacher-reliability-v1-${row.fixtureIndex}-${batch}`,
includeSamples: true,
});
return { batch, ...result };
});
console.log(
JSON.stringify({
fixtureIndex: row.fixtureIndex,
cell: row.cell,
round: state.round,
actions: c.candidates(state, player),
samplePolicies: Array.from({ length: 48 }, (_, i) => (i % 2 ? 'heuristic' : 'economic')),
batches,
})
);

View file

@ -0,0 +1,49 @@
"""HF-only diagnostic collection of independent teacher-search repetitions."""
import concurrent.futures
import hashlib
import json
import os
from pathlib import Path
import subprocess
from huggingface_hub import HfApi
fixtures = Path('ai/strong/fixtures/teacher-reliability-v1.jsonl')
rows = fixtures.read_text().splitlines()
assert len(rows) == 60
def audit(index):
result = subprocess.run(['node', 'ai/strong/audit-search-target.cjs', str(fixtures), str(index)],
text=True, capture_output=True, check=True)
row = json.loads(result.stdout)
for batch in row['batches']:
samples = batch['sampleOutcomes']
assert all(len(v) == 48 for v in samples.values())
assert sum(len(v) for v in samples.values()) == batch['evaluations']
assert sum(v.count(None) for v in samples.values()) == batch['truncated']
assert all(sum(x for x in v if x is not None) == batch['values'][k]
for k, v in samples.items())
return row
output = Path('teacher-reliability-v1.jsonl')
completed = []
with concurrent.futures.ThreadPoolExecutor(max_workers=24) as pool:
futures = [pool.submit(audit, i) for i in range(len(rows))]
for f in concurrent.futures.as_completed(futures):
completed.append(f.result())
print(json.dumps({'completed_positions': len(completed), 'requested_positions': len(rows)}), flush=True)
completed.sort(key=lambda r: r['fixtureIndex'])
output.write_text(''.join(json.dumps(r) + '\n' for r in completed))
manifest = {'positions': len(completed), 'samples_per_batch': 48, 'batches_per_position': 2,
'search_max_steps': 2400, 'fixture_sha256': hashlib.sha256(fixtures.read_bytes()).hexdigest(),
'output_sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
'truncated': sum(b['truncated'] for r in completed for b in r['batches']),
'evaluations': sum(b['evaluations'] for r in completed for b in r['batches']),
'scope': 'Reused development fixtures; diagnostic only, no strength or calibration claim.'}
api = HfApi()
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=output,
path_in_repo='runs/teacher-reliability-v1/results.jsonl')
api.upload_file(repo_id=os.environ['HF_MODEL_REPO'], path_or_fileobj=json.dumps(manifest, indent=2).encode(),
path_in_repo='runs/teacher-reliability-v1/manifest.json')
print(json.dumps(manifest), flush=True)

View file

@ -0,0 +1,111 @@
"""Read-only audit of immutable HF teacher shards before GPU training."""
import argparse
from collections import Counter
import gzip
import json
from pathlib import Path
from huggingface_hub import hf_hub_download
from teacher_contract import validate_game, validation_seeds
p = argparse.ArgumentParser()
p.add_argument("--revision", required=True)
p.add_argument("--version", default="multiplayer-teacher-v1")
p.add_argument("--output", required=True)
a = p.parse_args()
summary = {}
metadata = []
seen = set()
for shard, n in enumerate(range(2, 7)):
path = hf_hub_download(
"coyotte508/powergrid-ai-training-v1",
f"{a.version}/{a.version}-{shard}.jsonl.gz",
repo_type="dataset",
revision=a.revision,
)
stats = dict(
games=0,
positions=0,
truncated=0,
search_rollouts=0,
search_rollouts_truncated=0,
opponent_search_rollouts=0,
opponent_search_rollouts_truncated=0,
teacher_win_credit=0.0,
disagreements=0,
)
cells = Counter()
phases = Counter()
opponents = {}
with gzip.open(path, "rt") as source:
for line in source:
game = json.loads(line)
validate_game(game)
assert game["playerCount"] == n
assert game["seed"] not in seen
seen.add(game["seed"])
stats["games"] += 1
stats["truncated"] += game["truncated"]
stats["positions"] += len(game["rows"])
stats["search_rollouts"] += game["searchStats"]["evaluations"]
stats["search_rollouts_truncated"] += game["searchStats"]["truncated"]
opponent_search = game.get("opponentSearchStats", {})
stats["opponent_search_rollouts"] += opponent_search.get("evaluations", 0)
stats["opponent_search_rollouts_truncated"] += opponent_search.get(
"truncated", 0
)
if game["truncated"]:
continue
assert game["rows"]
seat = game["rows"][0]["seat"]
win = game["value"][seat]
stats["teacher_win_credit"] += win
opponent = game.get(
"opponent", ["economic", "heuristic", "rush"][game["id"] // (4 * n) % 3]
)
opp = opponents.setdefault(opponent, dict(games=0, win_credit=0.0))
opp["games"] += 1
opp["win_credit"] += win
cells[(seat, game["variant"], game["sealed"])] += 1
for row in game["rows"]:
phases[row["phase"]] += 1
stats["disagreements"] += not row["teacherAgrees"]
metadata.append(
{
**{
k: game[k] for k in ["seed", "playerCount", "variant", "sealed"]
},
"rows": [{"seat": seat}],
}
)
assert stats["games"] == 240 and len(cells) == n * 4
assert (
stats["truncated"]
== stats["search_rollouts_truncated"]
== stats["opponent_search_rollouts_truncated"]
== 0
)
summary[str(n)] = {
**stats,
"seat_rule_cells": len(cells),
"phases": dict(phases),
"opponents": opponents,
}
selected = validation_seeds(metadata)
for n, stats in summary.items():
stats["validation_games"] = sum(
g["playerCount"] == int(n) and g["seed"] in selected for g in metadata
)
stats["training_games"] = sum(
g["playerCount"] == int(n) and g["seed"] not in selected for g in metadata
)
report = dict(
revision=a.revision,
version=a.version,
counts=summary,
unique_games=len(seen),
validated=True,
scope="Teacher-generated development data; not held-out strength evidence",
)
Path(a.output).write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report))

View file

@ -0,0 +1,61 @@
"""Measure ambiguity in held-out search labels; estimates are not true win values."""
import argparse
from collections import defaultdict
import gzip
import json
from pathlib import Path
from teacher_contract import validation_seeds
p = argparse.ArgumentParser()
p.add_argument("dataset_directory", type=Path)
p.add_argument("--output", type=Path, required=True)
a = p.parse_args()
paths = sorted(a.dataset_directory.glob("*.jsonl.gz"))
assert len(paths) == 5
metadata = []
for path in paths:
with gzip.open(path, "rt") as source:
for line in source:
game = json.loads(line)
metadata.append(
{
**{
k: game[k] for k in ["seed", "playerCount", "variant", "sealed"]
},
"rows": [{"seat": r["seat"]} for r in game["rows"]],
}
)
held_out = validation_seeds(metadata)
groups = defaultdict(lambda: defaultdict(int))
for path in paths:
with gzip.open(path, "rt") as source:
for line in source:
game = json.loads(line)
if game["seed"] not in held_out:
continue
for row in game["rows"]:
for key in [
str(game["playerCount"]),
f"{game['playerCount']}/{row['phase']}",
]:
g = groups[key]
g["positions"] += 1
values = sorted([v for _, v in row["searchValues"]], reverse=True)
if len(values) < 2:
g["fewer_than_two_searched_candidates"] += 1
continue
g["search_comparisons"] += 1
margin = values[0] - values[1]
g["tied_top_estimates"] += margin < 1e-9
g["top_gap_at_most_one_of_16_rollouts"] += margin <= 1 / 16 + 1e-9
if not row["teacherAgrees"]:
g["teacher_disagreements"] += 1
g["disagreements_with_tied_top"] += margin < 1e-9
report = {
"scope": "Held-out teacher states; finite 16-rollout estimates, not calibrated confidence or true action quality.",
"validation_games": len(held_out),
"groups": dict(groups),
}
a.output.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({k: v for k, v in groups.items() if "/" not in k}))

View file

@ -0,0 +1,19 @@
const c = require('../core.cjs'),
f = require('./features.cjs'),
eco = require('./economics.cjs'),
{ createHash } = require('node:crypto');
const h = createHash('sha256');
let n = 0,
t = performance.now();
for (let i = 0; i < 4; i++) {
const g = c.start('features-bench-' + i, i % 2 ? 'original' : 'recharged', i < 2),
rng = c.seedrandom('bench');
while (!c.E.ended(g) && n < 5000) {
const p = g.currentPlayers[0],
x = f.encode(g, p);
h.update(JSON.stringify(x));
n++;
c.E.move(g, eco.choose(g, p, rng).action, p);
}
}
console.log(JSON.stringify({ states: n, seconds: (performance.now() - t) / 1000, hash: h.digest('hex') }));

View file

@ -0,0 +1,134 @@
"""Validate legal responses and time the complete persistent CPU worker."""
import argparse
import json
from pathlib import Path
import subprocess
import sys
import time
import platform
import numpy as np
from search_scope import SCOPES
p = argparse.ArgumentParser()
p.add_argument("model")
p.add_argument("--search-scope", choices=SCOPES, default="all")
p.add_argument("fixtures")
p.add_argument("--output", required=True)
p.add_argument("--search-samples", type=int, default=0)
p.add_argument("--stride", type=int, default=1)
p.add_argument("--geographic-search", action="store_true")
args = p.parse_args()
worker = subprocess.Popen(
[
sys.executable,
str(Path(__file__).with_name("infer.py")),
args.model,
"--search-scope",
args.search_scope,
"--search-samples",
str(args.search_samples),
]
+ (["--geographic-search"] if args.geographic_search else []),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
bufsize=1,
)
latencies, inner = [], []
search_latencies = []
search_evaluations = 0
search_truncations = 0
by_phase = {}
by_count = {}
sha = None
try:
with open(args.fixtures) as source:
for i, line in enumerate(source):
if i % args.stride:
continue
fixture = json.loads(line)
request = fixture["request"]
start = time.perf_counter()
worker.stdin.write(json.dumps(request) + "\n")
worker.stdin.flush()
result = json.loads(worker.stdout.readline())
latencies.append(1000 * (time.perf_counter() - start))
assert "error" not in result, result
assert result["move"] in fixture["legal"], result
assert result["requestId"] == request["requestId"]
assert result["revision"] == request["revision"]
assert result["schema"] in [3, 4]
n = len(request["state"]["players"])
assert len(result["winProbabilities"]) == n
assert result["playerOrder"] == [
(request["player"] + j) % n for j in range(n)
]
by_count.setdefault(str(n), []).append(latencies[-1])
assert result["playerOrder"][0] == request["player"]
assert abs(sum(result["winProbabilities"]) - 1) < 1e-5
assert sha is None or sha == result["modelSha256"]
sha = result["modelSha256"]
inner.append(result["elapsedMs"])
by_phase.setdefault(str(request["state"]["phase"]), []).append(
latencies[-1]
)
search_evaluations += (result.get("search") or {}).get("evaluations", 0)
search_truncations += (result.get("search") or {}).get("truncated", 0)
if (result.get("search") or {}).get("evaluations", 0):
search_latencies.append(latencies[-1])
finally:
worker.stdin.close()
worker.wait(timeout=10)
worker.stdout.close()
cpu_info = Path("/proc/cpuinfo")
processor_model = platform.processor()
if cpu_info.exists():
processor_model = next(
(
line.split(":", 1)[1].strip()
for line in cpu_info.read_text().splitlines()
if line.startswith("model name")
),
processor_model,
)
report = {
"hostname": platform.node(),
"processor_model": processor_model,
"python_version": platform.python_version(),
"positions": len(latencies),
"by_player_count": {
n: {"positions": len(xs), "p95_ms": float(np.percentile(xs, 95))}
for n, xs in by_count.items()
},
"model_sha256": sha,
"all_moves_legal": True,
"search_samples": args.search_samples,
"search_scope": args.search_scope,
"geographic_search": args.geographic_search,
"cold_start_ms": latencies[0],
"warm_roundtrip_p50_ms": float(np.percentile(latencies[1:], 50)),
"warm_roundtrip_p95_ms": float(np.percentile(latencies[1:], 95)),
"worker_p95_ms": float(np.percentile(inner[1:], 95)),
"max_roundtrip_ms": max(latencies),
"search_decisions": len(search_latencies),
"search_evaluations": search_evaluations,
"search_truncated_rollouts": search_truncations,
"search_roundtrip_p50_ms": float(np.percentile(search_latencies, 50))
if search_latencies
else None,
"search_roundtrip_p95_ms": float(np.percentile(search_latencies, 95))
if search_latencies
else None,
"by_phase": {
phase: {
"positions": len(times),
"p50_ms": float(np.percentile(times, 50)),
"p95_ms": float(np.percentile(times, 95)),
"max_ms": max(times),
}
for phase, times in by_phase.items()
},
}
Path(args.output).write_text(json.dumps(report, indent=2))
print(json.dumps(report))

219
ai/strong/bridge.cjs Normal file
View file

@ -0,0 +1,219 @@
const c = require('../core.cjs'),
eco = require('./economics.cjs'),
encoders = require('./encoders.cjs'),
readline = require('node:readline');
let envs = [],
sequence = 0;
const seed = process.env.SEED || 'strong-train';
function searchMove(e, seat, options) {
const result = require('./search.cjs').choose(e.g, seat, options);
const role = e.roles[seat];
const stats = (e.searchStats[role] ||= { decisions: 0, evaluations: 0, truncated: 0 });
stats.decisions++;
stats.evaluations += result.evaluations || 0;
stats.truncated += result.truncated || 0;
return result.action;
}
function applyBot(e, p) {
const role = e.roles[p];
if (role === 'legacy') {
const old = Math.random;
Math.random = e.rng;
try {
c.E.moveAI(e.g, p);
} finally {
Math.random = old;
}
} else if (role === 'search' || role === 'search_geo') {
const legal = c.candidates(e.g, p),
strategic = legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
c.E.move(
e.g,
strategic
? searchMove(e, p, {
samples: role === 'search_geo' ? 16 : 4,
candidates: role === 'search_geo' ? 6 : 5,
geography: role === 'search_geo',
seed: 'arena-search-' + e.g.round + '-' + p + '-' + Math.floor(e.rng() * 1e9),
})
: eco.choose(e.g, p, e.rng).action,
p
);
} else
c.E.move(
e.g,
role === 'heuristic' ? c.heuristic(e.g, p, e.rng).action : eco.choose(e.g, p, e.rng, role).action,
p
);
e.steps++;
}
function advance(e) {
while (
!c.E.ended(e.g) &&
e.steps < 1600 &&
!['learner', 'snapshot0', 'snapshot1', 'snapshot2'].includes(e.roles[e.g.currentPlayers[0]])
)
applyBot(e, e.g.currentPlayers[0]);
}
function observation(e) {
if (c.E.ended(e.g) || e.steps >= 1600) return null;
const seat = e.g.currentPlayers[0],
x = encoders.forRevision(e.featureRevisions[e.roles[seat]]).encode(e.g, seat);
delete x.moves;
return {
...x,
episode: e.id,
roles: e.roles,
round: e.g.round,
variant: e.g.options.variant,
sealed: !!e.g.options.fastBid,
playerCount: e.g.players.length,
};
}
function reset(mode = 'mixed', arenaSeed, arenaId, featureRevisions = {}, playerCount = 3, trainingIndex, learnerSeat) {
if (!Number.isInteger(playerCount) || playerCount < 2 || playerCount > 6) throw Error('Invalid player count');
if (
![
'mixed',
'mixed_search',
'mixed_search_geo',
'economic',
'heuristic',
'rush',
'legacy',
'selfplay',
'snapshot0',
'snapshot1',
'snapshot2',
'search',
'search_geo',
].includes(mode)
)
throw Error('Unknown opponent mode: ' + mode);
const id = arenaSeed === undefined ? trainingIndex ?? sequence++ : arenaId,
seat = learnerSeat ?? Math.floor(id / 4) % playerCount,
kind = Math.floor(c.seedrandom(seed + '-opponents-' + id)() * 8);
const opponent =
mode === 'mixed' || mode === 'mixed_search' || mode === 'mixed_search_geo'
? [
'economic',
'heuristic',
'rush',
mode === 'mixed_search_geo' ? 'search_geo' : mode === 'mixed_search' ? 'search' : 'legacy',
'selfplay',
'snapshot0',
'snapshot1',
'snapshot2',
][kind]
: mode;
const roles =
opponent === 'selfplay'
? Array(playerCount).fill('learner')
: Array.from({ length: playerCount }, (_, i) => (i === seat ? 'learner' : opponent));
const gameSeed = arenaSeed === undefined ? seed + '-' + id : arenaSeed + '-' + Math.floor(id / (4 * playerCount));
const e = {
id,
gameSeed,
g: c.E.setup(
playerCount,
{ map: 'Germany', variant: id % 2 ? 'recharged' : 'original', fastBid: id % 4 < 2, showMoney: true },
gameSeed
),
roles,
rng: c.seedrandom(arenaSeed === undefined ? seed + '-bot-' + id : gameSeed + '-bot'),
steps: 0,
policyMoves: {},
searchStats: {},
featureRevisions,
};
advance(e);
return e;
}
(async () => {
for await (const line of readline.createInterface({ input: process.stdin })) {
try {
const q = JSON.parse(line),
ended = [];
if (q.op === 'reset') {
const counts = q.playerCounts;
if (
counts &&
(q.arenaSeed !== undefined ||
!Array.isArray(counts) ||
!counts.length ||
new Set(counts).size !== counts.length ||
counts.some((n) => !Number.isInteger(n) || n < 2 || n > 6))
)
throw Error('Mixed player counts require a valid training-only schedule');
envs = Array.from({ length: q.n }, (_, i) => {
const index = (q.offset || 0) + i;
const count = counts ? counts[Math.floor(index / 4) % counts.length] : q.playerCount ?? 3;
const seat = counts ? Math.floor(index / (4 * counts.length)) % count : undefined;
return reset(
q.mode,
q.arenaSeed,
index,
q.featureRevisions,
count,
counts ? index : undefined,
seat
);
});
} else if (q.op === 'step')
for (let i = 0; i < envs.length; i++) {
const e = envs[i];
if (q.actions[i] === null) continue;
const seat = e.g.currentPlayers[0];
const legal = c.candidates(e.g, seat),
choice = q.actions[i];
const strategic =
legal.length > 1 && legal.some((a) => ['ChoosePowerPlant', 'Bid', 'Build'].includes(a.name));
const index = typeof choice === 'object' ? choice.proposal : choice;
const action =
typeof choice === 'object' && strategic
? searchMove(e, seat, {
samples: choice.searchSamples,
candidates: 6,
extraCandidates: choice.disableSearchProposal ? [] : [index],
geography: !!choice.geography,
seed: 'arena-guided-' + e.id + '-' + e.steps,
})
: legal[index];
c.E.move(e.g, action, seat);
if (e.roles[seat] === 'learner') e.policyMoves[action.name] = (e.policyMoves[action.name] || 0) + 1;
e.steps++;
advance(e);
if (c.E.ended(e.g) || e.steps >= 1600)
ended.push({
env: i,
episode: e.id,
gameSeed: e.gameSeed,
truncated: !c.E.ended(e.g),
value: c.E.ended(e.g) ? c.outcome(e.g) : Array(e.g.players.length).fill(0),
playerCount: e.g.players.length,
variant: e.g.options.variant,
sealed: !!e.g.options.fastBid,
steps: e.steps,
roles: e.roles,
policyMoves: e.policyMoves,
searchStats: e.searchStats,
final: {
round: e.g.round,
players: e.g.players.map((p) => ({
cities: p.cities.length,
powered: p.citiesPowered,
money: p.money,
capacity: c.capacity(p),
plants: p.powerPlants.map((pp) => pp.number),
})),
},
});
}
else throw Error('unknown op');
console.log(JSON.stringify({ observations: envs.map(observation), ended }));
} catch (err) {
console.error(err.stack);
process.exit(1);
}
}
})();

92
ai/strong/check-export.py Normal file
View file

@ -0,0 +1,92 @@
"""Check an exported policy against its checkpoint on real engine positions."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import numpy as np
import onnxruntime as ort
import torch
from feature_contract import METADATA_KEY
from model import policy_from_checkpoint, tensors
p = argparse.ArgumentParser()
p.add_argument("checkpoint")
p.add_argument("model")
p.add_argument("fixtures")
p.add_argument("--output", required=True)
a = p.parse_args()
torch.set_num_threads(1)
checkpoint = torch.load(a.checkpoint, map_location="cpu", weights_only=True)
net = policy_from_checkpoint(checkpoint).eval()
options = ort.SessionOptions()
options.intra_op_num_threads = 1
session = ort.InferenceSession(a.model, options, providers=["CPUExecutionProvider"])
revision = session.get_modelmeta().custom_metadata_map.get(METADATA_KEY, "3.0")
assert revision == checkpoint.get("feature_revision", "3.0")
worker = subprocess.Popen(
["node", str(Path(__file__).with_name("worker.cjs"))],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
errors = [0.0, 0.0]
count = 0
route_counts = {}
by_count = {}
inactive_values_zero = True
try:
for line in Path(a.fixtures).read_text().splitlines():
request = json.loads(line)["request"]
request["featureRevision"] = revision
worker.stdin.write(json.dumps(request) + "\n")
worker.stdin.flush()
row = json.loads(worker.stdout.readline())
assert "error" not in row, row
inputs = tensors([row], "cpu")
with torch.inference_mode():
expected = [x.numpy() for x in net(*inputs)]
if checkpoint.get("architecture") == "rule_specialists":
options = request["state"]["options"]
use_sealed = options.get("variant") == "recharged" and bool(
options.get("fastBid")
)
route = "recharged-sealed" if use_sealed else "default"
route_counts[route] = route_counts.get(route, 0) + 1
component = (
net.recharged_sealed_policy if use_sealed else net.default_policy
)
component_outputs = [x.numpy() for x in component(*inputs)]
for selected, correct in zip(expected, component_outputs):
np.testing.assert_array_equal(selected, correct)
actual = session.run(
None, dict(zip(["state", "actions", "mask"], [x.numpy() for x in inputs]))
)
for i in range(2):
errors[i] = max(errors[i], float(np.max(np.abs(expected[i] - actual[i]))))
np.testing.assert_allclose(actual[i], expected[i], rtol=1e-4, atol=1e-5)
n = len(request["state"]["players"])
by_count[str(n)] = by_count.get(str(n), 0) + 1
assert row["playerOrder"] == [(request["player"] + i) % n for i in range(n)]
assert np.all(actual[1][:, n:] == 0)
assert np.isfinite(actual[1]).all() and np.isclose(actual[1].sum(), 1)
assert np.argmax(actual[0]) == np.argmax(expected[0])
count += 1
finally:
worker.stdin.close()
worker.wait(timeout=10)
worker.stdout.close()
report = {
"positions": count,
"by_player_count": by_count,
"inactive_values_zero": inactive_values_zero,
"feature_revision": revision,
"model_sha256": hashlib.sha256(Path(a.model).read_bytes()).hexdigest(),
"max_logit_error": errors[0],
"max_value_error": errors[1],
"all_actions_match": True,
"specialist_route_counts": route_counts,
}
Path(a.output).write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report))

View file

@ -0,0 +1,60 @@
"""Combine disjoint paired arena shards without treating seat repeats as independent."""
import argparse
import json
from pathlib import Path
from arena_statistics import win_summary, search_summary, validate_pairs
p = argparse.ArgumentParser()
p.add_argument("reports", nargs="+")
p.add_argument("--output", required=True)
a = p.parse_args()
reports = [json.loads(Path(x).read_text()) for x in a.reports]
keys = [
"model_sha256",
"model_feature_revision",
"encoder_feature_revision",
"opponent",
"opponent_sha256",
"opponent_feature_revision",
"paired_seats",
"candidate_search_samples",
"candidate_geographic_search",
"search_max_steps",
]
for report in reports:
report.setdefault("candidate_search_scope", "all")
report.setdefault("search_max_steps", 1200)
report.setdefault("player_count", 3)
report.setdefault("candidate_search_model_proposal", True)
keys.extend(
["candidate_search_scope", "player_count", "candidate_search_model_proposal"]
)
config = {k: reports[0][k] for k in keys}
rows = []
seen = set()
for report in reports:
assert {k: report[k] for k in keys} == config, "Incompatible arena settings"
assert report["paired_seats"] and len(report["results"]) == report["games"]
for row in report["results"]:
key = (row["gameSeed"], row["variant"], row["sealed"], row["seat"])
assert key not in seen, f"Duplicate match: {key}"
seen.add(key)
rows.append(row)
validate_pairs(rows, config["player_count"])
result = {
**config,
"sources": a.reports,
**win_summary(rows),
**search_summary(rows),
"by_rules": [],
"results": rows,
}
for variant in ["original", "recharged"]:
for sealed in [False, True]:
group = [r for r in rows if r["variant"] == variant and r["sealed"] == sealed]
result["by_rules"].append(
{"variant": variant, "sealed": sealed, **win_summary(group)}
)
Path(a.output).write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps({k: v for k, v in result.items() if k != "results"}))

View file

@ -0,0 +1,99 @@
"""CPU-only composition of frozen specialists; no training or gradients."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import torch
from model import RuleSpecialists, policy_from_checkpoint
from feature_contract import FEATURE_REVISION
p = argparse.ArgumentParser()
p.add_argument("default_checkpoint")
p.add_argument("sealed_checkpoint")
p.add_argument("output")
p.add_argument("--default-revision", required=True)
p.add_argument("--sealed-revision", required=True)
p.add_argument("--allow-uranium39-transfer", action="store_true")
a = p.parse_args()
torch.set_num_threads(1)
components = []
checkpoints = []
for path, revision in [
(a.default_checkpoint, a.default_revision),
(a.sealed_checkpoint, a.sealed_revision),
]:
ck = torch.load(path, map_location="cpu", weights_only=True)
source_features = ck.get("feature_revision", "3.0")
if source_features != FEATURE_REVISION and not (
source_features == "3.0" and a.allow_uranium39_transfer
):
raise ValueError(
"Explicit authorization required for 3.0 to corrected-feature transfer"
)
assert ck.get("architecture", "policy") == "policy"
checkpoints.append(ck)
components.append(
{
"checkpoint_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(),
"repository_revision": revision,
"source_feature_revision": source_features,
"input_feature_revision": FEATURE_REVISION,
}
)
args = {
"default_strategic_only": checkpoints[0].get("strategic_only", False),
"sealed_strategic_only": checkpoints[1].get("strategic_only", False),
}
net = RuleSpecialists(**args).eval()
net.default_policy.load_state_dict(policy_from_checkpoint(checkpoints[0]).state_dict())
net.recharged_sealed_policy.load_state_dict(
policy_from_checkpoint(checkpoints[1]).state_dict()
)
out = Path(a.output)
out.mkdir(parents=True, exist_ok=False)
checkpoint = {
"architecture": "rule_specialists",
"model_args": args,
"schema": 3,
"state_dim": 738,
"action_dim": 96,
"feature_revision": FEATURE_REVISION,
"components": components,
"state_dict": net.state_dict(),
}
torch.save(checkpoint, out / "specialists.pt")
(out / "composition.json").write_text(
json.dumps(
{
"architecture": "rule_specialists",
"default": "corrected A260 refinement update 40",
"recharged_sealed": "B160 weights with explicit uranium-feature correction",
"training": "none; frozen-weight composition",
"components": components,
},
indent=2,
)
+ "\n"
)
subprocess.run(
[
sys.executable,
str(Path(__file__).with_name("export.py")),
str(out / "specialists.pt"),
str(out / "specialists.onnx"),
],
check=True,
)
print(
json.dumps(
{
"model": str(out / "specialists.onnx"),
"sha256": hashlib.sha256(
(out / "specialists.onnx").read_bytes()
).hexdigest(),
}
)
)

View file

@ -0,0 +1,23 @@
// Diagnostic preload only: return the original decision, and retry capped searches separately.
const fs = require('node:fs');
const search = require('./search.cjs');
const choose = search.choose;
search.choose = function (g, seat, options) {
const original = choose(g, seat, { ...options, maxSteps: 1200 });
if (original.truncated) {
const extended = choose(g, seat, { ...options, maxSteps: 2400 });
const record = { seat, options, original, extended, state: g };
fs.appendFileSync(process.env.SEARCH_DIAGNOSTIC_PATH, JSON.stringify(record) + '\n');
console.error(
JSON.stringify({
diagnostic: 'search_horizon',
seed: options.seed,
original_truncated: original.truncated,
extended_truncated: extended.truncated,
original_index: original.index,
extended_index: extended.index,
})
);
}
return original;
};

View file

@ -0,0 +1,118 @@
"""Replay the one capped arena match without changing its actual policy decisions."""
import json
import os
from pathlib import Path
import sys
import time
from huggingface_hub import HfApi, hf_hub_download
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from infer import Model
from pool import EnginePool
repo = "coyotte508/powergrid-ai-germany-v1"
model = Model(
hf_hub_download(
repo,
"runs/multiplayer-distillation-v2-hard/best.onnx",
revision="ab34dd266010ded1c9a6c818c721e5505dd1ddeb",
)
)
expected_file = hf_hub_download(
repo,
"runs/multiplayer-hard-e10-search48-search_geo-6p-probe-4/evaluation.json",
revision=os.environ["REPORT_REVISION"],
)
expected = next(
r
for r in json.loads(Path(expected_file).read_text())["results"]
if r["gameSeed"] == "multiplayer-search-strong-probe-v1-6p-5"
and r["variant"] == "recharged"
and not r["sealed"]
and r["seat"] == 1
)
out = Path("ai/runs/search-horizon-diagnostic-v1")
out.mkdir(parents=True, exist_ok=True)
os.environ["NODE_OPTIONS"] = "--require " + str(
Path("ai/strong/diagnose-search-horizon.cjs").resolve()
)
os.environ["SEARCH_DIAGNOSTIC_PATH"] = str((out / "capped-searches.jsonl").resolve())
pool = EnginePool(
1, seed="multiplayer-search-strong-probe-v1-6p", script="ai/strong/bridge.cjs"
)
start = last = time.monotonic()
try:
current = pool.call(
dict(
op="reset",
n=1,
playerCount=6,
offset=127,
mode="search_geo",
arenaSeed="multiplayer-search-strong-probe-v1-6p",
featureRevisions={"learner": "4.0-multiplayer"},
)
)["observations"]
ends = []
while current[0] is not None:
x = current[0]
action, _ = model.predict(x["state"], x["actions"])
reply = pool.call(
dict(
op="step",
actions=[dict(proposal=action, searchSamples=48, geography=True)],
)
)
current = reply["observations"]
ends.extend(reply["ended"])
if time.monotonic() - last >= 30:
print(
json.dumps(
dict(
stage="diagnostic_replay",
seconds=time.monotonic() - start,
round=x["round"],
)
),
flush=True,
)
last = time.monotonic()
finally:
pool.close()
assert len(ends) == 1
actual = ends[0]
keys = [
"episode",
"gameSeed",
"truncated",
"value",
"playerCount",
"variant",
"sealed",
"steps",
"roles",
"policyMoves",
"searchStats",
"final",
]
assert all(actual[k] == expected[k] for k in keys), (
"Diagnostic replay diverged from original match"
)
captured = [
json.loads(line)
for line in (out / "capped-searches.jsonl").read_text().splitlines()
]
assert sum(r["original"]["truncated"] for r in captured) == 1
report = dict(
exact_terminal_replay=True,
original=actual,
captures=[{k: v for k, v in r.items() if k != "state"} for r in captured],
seconds=time.monotonic() - start,
)
(out / "report.json").write_text(json.dumps(report, indent=2) + "\n")
HfApi().upload_folder(
repo_id=repo, folder_path=str(out), path_in_repo="runs/search-horizon-diagnostic-v1"
)
print(json.dumps({k: v for k, v in report.items() if k != "original"}), flush=True)

366
ai/strong/distill.py Normal file
View file

@ -0,0 +1,366 @@
"""HF GPU job: distill public-belief search, then measure actual playing strength."""
from collections import Counter
import copy
import gzip
import json
import os
from pathlib import Path
import random
import subprocess
import sys
import numpy as np
import torch
from huggingface_hub import HfApi, hf_hub_download
from model import Policy, tensors
from model_v4 import MultiplayerPolicy
from teacher_contract import validate_game, validation_seeds
from distillation_targets import policy_targets
from distill_data import source_count_weights, validate_initial_checkpoint
from feature_contract import FEATURE_REVISION, embed_revision
architecture = os.getenv("ARCHITECTURE", "policy")
multiplayer = architecture in ["multiplayer", "multiplayer_ordered"]
ordered_players = architecture == "multiplayer_ordered"
if multiplayer:
FEATURE_REVISION = "4.0-multiplayer"
if not os.getenv("DATA_REVISION"):
raise ValueError("Pin DATA_REVISION for the multiplayer teacher dataset")
state_dim, action_dim = (1149, 98) if multiplayer else (738, 96)
player_counts = [2, 3, 4, 5, 6] if multiplayer else [3]
assert torch.cuda.is_available(), "Training must run on a GPU HF Job"
torch.set_num_threads(2)
seed = int(os.getenv("TRAIN_SEED", "310"))
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
run = os.getenv("RUN_NAME", "search-distillation-v1")
out = Path("ai/runs") / run
out.mkdir(parents=True, exist_ok=True)
device = "cuda"
net = (
MultiplayerPolicy(ordered_players=ordered_players) if multiplayer else Policy()
).to(device)
initial_checkpoint = os.getenv("INIT_CHECKPOINT")
initial_revision = os.getenv("INIT_REVISION")
if bool(initial_checkpoint) != bool(initial_revision):
raise ValueError("Pin both INIT_CHECKPOINT and INIT_REVISION")
if initial_checkpoint:
if len(initial_revision) != 40 or any(
c not in "0123456789abcdef" for c in initial_revision
):
raise ValueError("INIT_REVISION must be an immutable commit")
checkpoint = torch.load(
hf_hub_download(
os.environ["HF_MODEL_REPO"], initial_checkpoint, revision=initial_revision
),
map_location="cpu",
weights_only=True,
)
validate_initial_checkpoint(
checkpoint, architecture, FEATURE_REVISION, state_dim, action_dim
)
net.load_state_dict(checkpoint["state_dict"])
train, validation = [], []
dataset_revisions = []
seen_games = set()
complete_games = []
version = os.getenv("DATA_VERSION", "search-teacher-v1")
target_mode = os.getenv("TARGET_MODE", "hard")
assert target_mode in ["hard", "soft"]
sources = [(version, os.getenv("DATA_REVISION"))]
replay_version, replay_revision = (
os.getenv("REPLAY_DATA_VERSION"),
os.getenv("REPLAY_DATA_REVISION"),
)
if bool(replay_version) != bool(replay_revision):
raise ValueError("Pin both replay dataset version and revision")
if replay_version:
if len(replay_revision) != 40 or any(
c not in "0123456789abcdef" for c in replay_revision
):
raise ValueError("Replay revision must be an immutable commit")
sources.append((replay_version, replay_revision))
for source_index, (source_version, source_revision) in enumerate(sources):
for shard in range(int(os.getenv("SHARDS", "4"))):
path = hf_hub_download(
os.environ["HF_DATA_REPO"],
f"{source_version}/{source_version}-{shard}.jsonl.gz",
repo_type="dataset",
revision=source_revision,
)
dataset_revisions.append(
{
"version": source_version,
"shard": shard,
"revision": Path(path).parents[1].name,
}
)
with gzip.open(path, "rt") as source:
for line in source:
game = json.loads(line)
if game.get("featureRevision", "3.0") != FEATURE_REVISION:
raise ValueError(
"Dataset uses a different feature revision; use its archived encoder or regenerate"
)
if multiplayer:
validate_game(game)
if game["seed"] in seen_games:
raise ValueError("Duplicate teacher game")
seen_games.add(game["seed"])
if game["truncated"]:
continue
game["dataset_source"] = source_index
for row in game["rows"]:
row["dataset_source"] = source_index
row["player_count"] = game.get("playerCount", 3)
row["variant"] = game.get("variant")
row["sealed"] = game.get("sealed")
row["state"] = np.asarray(row["state"], np.float32)
row["actions"] = np.asarray(row["actions"], np.float32)
complete_games.append(game)
held_out = (
set().union(
*(
validation_seeds([g for g in complete_games if g["dataset_source"] == i])
for i in range(len(sources))
)
)
if multiplayer
else {g["seed"] for g in complete_games if g["id"] % 5 == 0}
)
for game in complete_games:
(validation if game["seed"] in held_out else train).extend(game["rows"])
assert train and validation
count_sizes = Counter(r["player_count"] for r in train)
validation_sizes = Counter(r["player_count"] for r in validation)
if multiplayer and (
set(count_sizes) != set(player_counts)
or set(validation_sizes) != set(player_counts)
):
raise ValueError("Every player count must appear in training and validation")
balance_weights = source_count_weights(train, player_counts)
source_count_weights(validation, player_counts)
for row in train:
row["balance_weight"] = balance_weights[
(row["dataset_source"], row["player_count"])
]
print(
json.dumps(
{
"stage": "dataset_loaded",
"train_counts": dict(count_sizes),
"validation_counts": dict(validation_sizes),
"teacher_sources": dataset_revisions,
"train_source_counts": {
f"{source}/{n}": count
for (source, n), count in Counter(
(r["dataset_source"], r["player_count"]) for r in train
).items()
},
}
),
flush=True,
)
optimizer = torch.optim.AdamW(
net.parameters(), lr=float(os.getenv("LR", ".0003")), weight_decay=1e-4
)
metrics = []
best = -1
batchsize = int(os.getenv("BATCH_SIZE", "256"))
def export(name):
torch.save(
{
"schema": 4 if multiplayer else 3,
"architecture": architecture if multiplayer else "policy",
"feature_revision": FEATURE_REVISION,
"initial_checkpoint": initial_checkpoint,
"initial_revision": initial_revision,
"teacher_sources": dataset_revisions,
"state_dim": state_dim,
"action_dim": action_dim,
"state_dict": {k: v.detach().cpu() for k, v in net.state_dict().items()},
},
out / f"{name}.pt",
)
clone = copy.deepcopy(net).cpu().eval()
torch.onnx.export(
clone,
(
torch.zeros(1, state_dim),
torch.zeros(1, 8, action_dim),
torch.ones(1, 8, dtype=torch.bool),
),
str(out / f"{name}.onnx"),
input_names=["state", "actions", "mask"],
output_names=["logits", "value"],
dynamic_axes={
"state": {0: "batch"},
"actions": {0: "batch", 1: "candidates"},
"mask": {0: "batch", 1: "candidates"},
"logits": {0: "batch", 1: "candidates"},
"value": {0: "batch"},
},
opset_version=17,
dynamo=False,
)
embed_revision(out / f"{name}.onnx", FEATURE_REVISION)
def validate():
correct, disagreement_correct, disagreements, count = 0, 0, 0, 0
by_count = {
n: {"positions": 0, "correct": 0, "disagreements": 0, "disagreement_correct": 0}
for n in player_counts
}
with torch.no_grad():
for k in range(0, len(validation), batchsize):
rows = validation[k : k + batchsize]
predicted = net(*tensors(rows, device))[0].argmax(-1).cpu().tolist()
for row, chosen in zip(rows, predicted):
group = by_count[row["player_count"]]
group["positions"] += 1
group["correct"] += chosen == row["target"]
if not row["teacherAgrees"]:
group["disagreements"] += 1
group["disagreement_correct"] += chosen == row["target"]
correct += chosen == row["target"]
count += 1
if not row["teacherAgrees"]:
disagreements += 1
disagreement_correct += chosen == row["target"]
return {
"positions": count,
"by_player_count": by_count,
"accuracy": correct / count,
"search_disagreements": disagreements,
"disagreement_accuracy": disagreement_correct / max(1, disagreements),
}
for epoch in range(int(os.getenv("EPOCHS", "30")) + 1):
losses = []
if epoch:
net.train()
random.shuffle(train)
for k in range(0, len(train), batchsize):
rows = train[k : k + batchsize]
logits, value = net(*tensors(rows, device))
targets = torch.from_numpy(
policy_targets(rows, logits.shape[1], soft=target_mode == "soft")
).to(device)
weights = torch.tensor(
[
(
1.0
if r["teacherAgrees"]
else float(os.getenv("DISAGREEMENT_WEIGHT", "3"))
)
* (r["balance_weight"])
for r in rows
],
device=device,
)
ce = -(targets * logits.log_softmax(-1)).sum(-1)
returns = torch.tensor([r["value"] for r in rows], device=device)
value_error = ((value - returns) ** 2).sum(-1) / torch.tensor(
[r["player_count"] for r in rows], device=device
)
balance = torch.tensor(
[r["balance_weight"] for r in rows],
device=device,
)
loss = (ce * weights).sum() / weights.sum() + 0.2 * (
value_error * balance
).sum() / balance.sum()
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(net.parameters(), 1)
optimizer.step()
losses.append(float(loss.detach()))
net.eval()
metric = {
"epoch": epoch,
"loss": float(np.mean(losses)) if losses else None,
"validation": validate(),
}
if epoch % 5 == 0:
export("latest")
results = {}
for player_count in player_counts:
for opponent in ["economic", "heuristic", "rush"]:
result = subprocess.run(
[
sys.executable,
"ai/strong/evaluate.py",
str(out / "latest.onnx"),
"--opponent",
opponent,
"--players",
str(player_count),
"--games",
str(8 * player_count if multiplayer else 96),
"--workers",
"4",
"--seed",
f"multiplayer-distill-development-{player_count}-v1"
if multiplayer
else "search-distill-development-v1",
"--output",
str(out / f"{player_count}p-{opponent}.json"),
],
text=True,
capture_output=True,
check=True,
)
results[f"{player_count}p/{opponent}" if multiplayer else opponent] = (
json.loads(result.stdout.strip().splitlines()[-1])
)
metric["arena"] = results
score = np.mean(
[
(r["win_rate"] - 1 / r["player_count"]) / (1 - 1 / r["player_count"])
if multiplayer
else r["win_rate"]
for r in results.values()
]
)
if score > best:
best = score
export("best")
metrics.append(metric)
(out / "metrics.json").write_text(json.dumps(metrics, indent=2))
(out / "schema.json").write_text(
json.dumps(
{
"version": 4 if multiplayer else 3,
"feature_revision": FEATURE_REVISION,
"players": player_counts if multiplayer else 3,
"training_positions_by_count": dict(count_sizes),
"validation_positions_by_count": dict(validation_sizes),
"split": "within each count/seat/rule cell, hold out 20% of whole games ranked by sha256(seed)"
if multiplayer
else "game id modulo 5",
"map": "Germany",
"run": run,
"training_positions": len(train),
"validation_positions": len(validation),
"dataset_revisions": dataset_revisions,
"dataset_version": version,
"target_mode": target_mode,
}
)
)
HfApi().upload_folder(
repo_id=os.environ["HF_MODEL_REPO"],
folder_path=str(out),
path_in_repo="runs/" + run,
)
else:
metrics.append(metric)
print(json.dumps(metric), flush=True)

27
ai/strong/distill_data.py Normal file
View file

@ -0,0 +1,27 @@
"""Balance replay sources without changing their per-player-count coverage."""
from collections import Counter
def source_count_weights(rows, player_counts):
sizes = Counter((r.get("dataset_source", 0), r["player_count"]) for r in rows)
sources = {source for source, _ in sizes}
expected = {(source, n) for source in sources for n in player_counts}
if not rows or set(sizes) != expected:
raise ValueError("Every teacher source must cover every player count")
return {key: len(rows) / (len(sizes) * size) for key, size in sizes.items()}
def validate_initial_checkpoint(
checkpoint, architecture, revision, state_dim, action_dim
):
expected = dict(
architecture=architecture,
feature_revision=revision,
state_dim=state_dim,
action_dim=action_dim,
)
if any(checkpoint.get(key) != value for key, value in expected.items()):
raise ValueError(
"Distillation warm start requires the exact architecture and feature contract"
)

View file

@ -0,0 +1,24 @@
"""Targets retain uncertainty across sampled counterfactual search actions."""
import numpy as np
def policy_targets(rows, candidates, soft=False):
targets = np.zeros((len(rows), candidates), dtype=np.float32)
for i, row in enumerate(rows):
estimates = row.get("searchValues", [])
if not soft or not estimates:
targets[i, row["target"]] = 1
continue
indices = np.asarray([x[0] for x in estimates], dtype=np.int64)
values = np.asarray([x[1] for x in estimates], dtype=np.float32)
assert len(set(indices.tolist())) == len(indices)
assert np.all((indices >= 0) & (indices < len(row["actions"])))
prior = np.asarray(row["actions"], dtype=np.float32)[indices, 74]
# When rollouts cannot distinguish the actions, retain the economic prior.
scores = (
prior * 2 if values.max() == values.min() else values * 8 + prior * 0.15
)
weights = np.exp(scores - scores.max())
targets[i, indices] = weights / weights.sum()
return targets

View file

@ -0,0 +1,199 @@
// Frozen economic features for historical checkpoints.
// Public-information economic calculations. Never inspect the hidden deck or sealed bids.
const c = require('../core.cjs');
const income = (g, n) => g.paymentTable[Math.max(0, Math.min(g.paymentTable.length - 1, n))];
function replenishment(g, r, step = g.step) {
return g[r + 'Resupply'][g.players.length - 2][step - 1];
}
function fuelVariants(pp) {
const base = [0, 0, 0, 0];
if (pp.type === 4) return Array.from({ length: pp.cost + 1 }, (_, coal) => [coal, pp.cost - coal, 0, 0]);
if (pp.type < 4) base[pp.type] = pp.cost;
return [base];
}
function plans(g, p, unused = false) {
let result = [{ power: 0, used: [0, 0, 0, 0], plants: [] }];
for (const pp of p.powerPlants) {
if (unused && !p.powerPlantsNotUsed.includes(pp.number)) continue;
const next = [...result];
for (const prev of result)
for (const need of fuelVariants(pp))
next.push({
power: prev.power + pp.citiesPowered,
used: prev.used.map((x, i) => x + need[i]),
plants: [...prev.plants, pp.number],
});
result = next;
}
return result;
}
function purchaseCost(g, p, used) {
let cost = 0;
for (let i = 0; i < 4; i++)
for (let k = 0; k < Math.max(0, used[i] - p[c.RES[i] + 'Left']); k++) {
if (k >= g[c.RES[i] + 'Market']) return Infinity;
cost += c.resourcePrice(g, c.RES[i], k);
}
return cost;
}
function plan(g, p, target = p.cities.length, { buy = true, unused = false, budget = p.money, endgame = false } = {}) {
let best = { power: 0, used: [0, 0, 0, 0], plants: [], cost: 0, score: -Infinity };
for (const option of plans(g, p, unused)) {
if (!buy && option.used.some((n, i) => n > p[c.RES[i] + 'Left'])) continue;
const cost = buy ? purchaseCost(g, p, option.used) : 0;
if (cost > budget) continue;
const powered = Math.min(target, option.power + (unused ? p.citiesPowered : 0));
const replacement = option.used.reduce((s, n, i) => s + n * c.resourcePrice(g, c.RES[i]), 0);
const score = (endgame ? powered * 1000 : income(g, powered)) - cost - (buy ? 0 : replacement * 0.2);
if (score > best.score) best = { ...option, powered, cost, score };
}
return best;
}
function demand(g, p) {
return plan(g, p, Math.max(p.cities.length, Math.min(c.capacity(p), p.cities.length + 3))).used;
}
function futurePressure(g, r) {
const i = c.RES.indexOf(r),
needed = g.players.reduce((sum, p) => sum + demand(g, p)[i], 0);
return needed - replenishment(g, r);
}
function context(g, seat) {
const p = g.players[seat],
cap = c.capacity(p),
maxCities = Math.max(...g.players.map((x) => x.cities.length));
const imminent = maxCities >= g.citiesToEndGame - 3;
const target = Math.min(
g.citiesToEndGame,
Math.max(p.cities.length, Math.min(cap, p.cities.length + (p.cities.length ? 3 : 2)))
);
const fuel = plan(g, p, target, { budget: Math.max(0, p.money - (p.cities.length ? 0 : 10)), endgame: imminent });
return { p, cap, maxCities, imminent, target, fuel };
}
function plantValue(g, p, pp) {
const before = plan(g, p, 22),
currentCap = c.capacity(p);
let best = -Infinity;
const portfolios =
p.powerPlants.length < 3
? [[...p.powerPlants, pp]]
: p.powerPlants.map((_, i) => [...p.powerPlants.filter((x, j) => i !== j), pp]);
for (const powerPlants of portfolios) {
const after = plan(g, { ...p, powerPlants }, 22),
gain = powerPlants.reduce((s, x) => s + x.citiesPowered, 0) - currentCap;
const fuelSaving = before.cost - after.cost;
const need = Math.max(0, p.cities.length + 3 - currentCap);
const value = pp.number * 0.55 + gain * (need > 0 ? 10 : 6) + fuelSaving * 2;
best = Math.max(best, value);
}
const reserve = p.cities.length === 0 ? 15 : Math.max(8, Math.min(35, p.cities.length * 1.5));
return Math.max(0, Math.min(p.money - reserve, best));
}
function scores(g, seat, actions = c.candidates(g, seat), style = 'economic') {
const x = context(g, seat),
p = x.p;
let production;
if (g.phase === c.E.Phase.Bureaucracy)
production = plan(g, p, p.cities.length, {
buy: false,
unused: true,
endgame: Math.max(...g.players.map((p) => p.cities.length)) >= g.citiesToEndGame,
});
const building = g.phase === c.E.Phase.Building;
const possible = building ? plan(g, p, p.cities.length + 1, { buy: false }).powered : 0;
const availablePower = building ? plan(g, p, x.cap, { buy: false }).powered : 0;
const opponentPower = building
? Math.max(
...g.players
.filter((z) => z.id !== seat)
.map((z) => plan(g, z, z.cities.length + 2, { buy: false }).powered)
)
: 0;
const bidWorth = g.chosenPowerPlant ? plantValue(g, p, g.chosenPowerPlant) : 0;
return actions.map((a) => {
const d = a.data;
switch (a.name) {
case 'ChoosePowerPlant': {
const pp = g.actualMarket.find((p) => p.number === d);
const v = plantValue(g, p, pp);
return v >= d ? 10 + (v - d) * 0.3 + pp.citiesPowered * 0.3 : -20;
}
case 'Bid': {
const v = bidWorth;
if (g.round === 1 && !actions.some((a) => a.name === 'Pass')) return -d;
return d <= v ? (g.options.fastBid ? 10 - Math.abs(d - v) * 0.5 : 10 - d * 0.2) : -30 - d;
}
case 'DiscardPowerPlant': {
const powerPlants = p.powerPlants.filter((pp) => pp.number !== d);
const pp = plan(g, { ...p, powerPlants }, 22);
return pp.power * 5 - pp.cost;
}
case 'BuyResource': {
const i = c.RES.indexOf(d.resource),
price = c.resourcePrice(g, d.resource);
if (p[d.resource + 'Left'] < x.fuel.used[i]) return 30 - price;
// Stock one extra round only when demand exceeds replenishment and today's price is low.
const surplus = p[d.resource + 'Left'] - x.fuel.used[i],
ownNeed = c.fuelDemand(g, p)[d.resource];
if (
style !== 'rush' &&
ownNeed > 0 &&
surplus < ownNeed &&
price <= 2 &&
p.money > 35 &&
futurePressure(g, d.resource) > 0
)
return 4 - price;
return -20;
}
case 'Build': {
const next = p.cities.length + 1;
if (p.money > 140 || g.round > 18) return 10 - d.price * 0.1;
if (next >= g.citiesToEndGame && possible < opponentPower) return -30;
if (next <= x.cap && (next <= availablePower || x.imminent)) return 25 - d.price * 0.35;
if (style === 'rush' && p.money - d.price > 30) return 8 - d.price * 0.15;
return -20;
}
case 'UsePowerPlant':
return production.plants.includes(d.powerPlant) &&
c.RES.every((r, i) => d.resourcesSpent.filter((x) => x === r).length <= production.used[i])
? 20 +
d.citiesPowered * 0.1 -
d.resourcesSpent.reduce((s, r) => s + c.resourcePrice(g, r), 0) * 0.01
: -10;
case 'DiscardResources':
return p[d + 'Left'] - x.fuel.used[c.RES.indexOf(d)];
case 'Pass':
return 0;
default:
return 0;
}
});
}
function choose(g, seat, rng = () => 0.5, style = 'economic') {
const actions = c.candidates(g, seat),
values = scores(g, seat, actions, style);
let index = 0,
best = -Infinity;
values.forEach((x, i) => {
x += rng() * 0.001;
if (x > best) {
best = x;
index = i;
}
});
return { index, action: actions[index] };
}
module.exports = {
income,
replenishment,
fuelVariants,
plans,
purchaseCost,
plan,
demand,
futurePressure,
context,
plantValue,
scores,
choose,
};

210
ai/strong/economics.cjs Normal file
View file

@ -0,0 +1,210 @@
// Public-information economic calculations. Never inspect the hidden deck or sealed bids.
const c = require('../core.cjs');
const income = (g, n) => g.paymentTable[Math.max(0, Math.min(g.paymentTable.length - 1, n))];
function replenishment(g, r, step = g.step) {
if (
r === 'uranium' &&
g.options.variant === 'recharged' &&
['Germany', 'Italy'].includes(g.options.map) &&
g.card39Bought
)
return 0;
return g[r + 'Resupply'][g.players.length - 2][step - 1];
}
function fuelVariants(pp) {
const base = [0, 0, 0, 0];
if (pp.type === 4) return Array.from({ length: pp.cost + 1 }, (_, coal) => [coal, pp.cost - coal, 0, 0]);
if (pp.type < 4) base[pp.type] = pp.cost;
return [base];
}
function plans(g, p, unused = false) {
let result = [{ power: 0, used: [0, 0, 0, 0], plants: [] }];
for (const pp of p.powerPlants) {
if (unused && !p.powerPlantsNotUsed.includes(pp.number)) continue;
const next = [...result];
for (const prev of result)
for (const need of fuelVariants(pp))
next.push({
power: prev.power + pp.citiesPowered,
used: prev.used.map((x, i) => x + need[i]),
plants: [...prev.plants, pp.number],
});
result = next;
}
return result;
}
function purchaseCost(g, p, used) {
let cost = 0;
for (let i = 0; i < 4; i++) {
const resource = c.RES[i],
needed = Math.max(0, used[i] - p[resource + 'Left']),
count = g[resource + 'Market'],
prices = g[resource + 'Prices'];
for (let k = 0; k < needed; k++) {
if (k >= count) return Infinity;
cost += prices && count > k ? prices[prices.length - count + k] : 20;
}
}
return cost;
}
function plan(g, p, target = p.cities.length, { buy = true, unused = false, budget = p.money, endgame = false } = {}) {
let best = { power: 0, used: [0, 0, 0, 0], plants: [], cost: 0, score: -Infinity };
for (const option of plans(g, p, unused)) {
if (!buy && option.used.some((n, i) => n > p[c.RES[i] + 'Left'])) continue;
const cost = buy ? purchaseCost(g, p, option.used) : 0;
if (cost > budget) continue;
const powered = Math.min(target, option.power + (unused ? p.citiesPowered : 0));
const replacement = buy ? 0 : option.used.reduce((s, n, i) => s + n * c.resourcePrice(g, c.RES[i]), 0);
const score = (endgame ? powered * 1000 : income(g, powered)) - cost - (buy ? 0 : replacement * 0.2);
if (score > best.score) best = { ...option, powered, cost, score };
}
return best;
}
function demand(g, p) {
return plan(g, p, Math.max(p.cities.length, Math.min(c.capacity(p), p.cities.length + 3))).used;
}
function futurePressure(g, r) {
const i = c.RES.indexOf(r),
needed = g.players.reduce((sum, p) => sum + demand(g, p)[i], 0);
return needed - replenishment(g, r);
}
function context(g, seat) {
const p = g.players[seat],
cap = c.capacity(p),
maxCities = Math.max(...g.players.map((x) => x.cities.length));
const imminent = maxCities >= g.citiesToEndGame - 3;
const target = Math.min(
g.citiesToEndGame,
Math.max(p.cities.length, Math.min(cap, p.cities.length + (p.cities.length ? 3 : 2)))
);
const fuel = plan(g, p, target, { budget: Math.max(0, p.money - (p.cities.length ? 0 : 10)), endgame: imminent });
return { p, cap, maxCities, imminent, target, fuel };
}
function plantValue(g, p, pp) {
const before = plan(g, p, 22),
currentCap = c.capacity(p);
let best = -Infinity;
const portfolios =
p.powerPlants.length < 3
? [[...p.powerPlants, pp]]
: p.powerPlants.map((_, i) => [...p.powerPlants.filter((x, j) => i !== j), pp]);
for (const powerPlants of portfolios) {
const after = plan(g, { ...p, powerPlants }, 22),
gain = powerPlants.reduce((s, x) => s + x.citiesPowered, 0) - currentCap;
const fuelSaving = before.cost - after.cost;
const need = Math.max(0, p.cities.length + 3 - currentCap);
const value = pp.number * 0.55 + gain * (need > 0 ? 10 : 6) + fuelSaving * 2;
best = Math.max(best, value);
}
const reserve = p.cities.length === 0 ? 15 : Math.max(8, Math.min(35, p.cities.length * 1.5));
return Math.max(0, Math.min(p.money - reserve, best));
}
function scores(g, seat, actions = c.candidates(g, seat), style = 'economic') {
const x = context(g, seat),
p = x.p;
let production;
if (g.phase === c.E.Phase.Bureaucracy)
production = plan(g, p, p.cities.length, {
buy: false,
unused: true,
endgame: Math.max(...g.players.map((p) => p.cities.length)) >= g.citiesToEndGame,
});
const building = g.phase === c.E.Phase.Building;
const possible = building ? plan(g, p, p.cities.length + 1, { buy: false }).powered : 0;
const availablePower = building ? plan(g, p, x.cap, { buy: false }).powered : 0;
const opponentPower = building
? Math.max(
...g.players
.filter((z) => z.id !== seat)
.map((z) => plan(g, z, z.cities.length + 2, { buy: false }).powered)
)
: 0;
const bidWorth = g.chosenPowerPlant ? plantValue(g, p, g.chosenPowerPlant) : 0;
return actions.map((a) => {
const d = a.data;
switch (a.name) {
case 'ChoosePowerPlant': {
const pp = g.actualMarket.find((p) => p.number === d);
const v = plantValue(g, p, pp);
return v >= d ? 10 + (v - d) * 0.3 + pp.citiesPowered * 0.3 : -20;
}
case 'Bid': {
const v = bidWorth;
if (g.round === 1 && !actions.some((a) => a.name === 'Pass')) return -d;
return d <= v ? (g.options.fastBid ? 10 - Math.abs(d - v) * 0.5 : 10 - d * 0.2) : -30 - d;
}
case 'DiscardPowerPlant': {
const powerPlants = p.powerPlants.filter((pp) => pp.number !== d);
const pp = plan(g, { ...p, powerPlants }, 22);
return pp.power * 5 - pp.cost;
}
case 'BuyResource': {
const i = c.RES.indexOf(d.resource),
price = c.resourcePrice(g, d.resource);
if (p[d.resource + 'Left'] < x.fuel.used[i]) return 30 - price;
// Stock one extra round only when demand exceeds replenishment and today's price is low.
const surplus = p[d.resource + 'Left'] - x.fuel.used[i],
ownNeed = c.fuelDemand(g, p)[d.resource];
if (
style !== 'rush' &&
ownNeed > 0 &&
surplus < ownNeed &&
price <= 2 &&
p.money > 35 &&
futurePressure(g, d.resource) > 0
)
return 4 - price;
return -20;
}
case 'Build': {
const next = p.cities.length + 1;
if (p.money > 140 || g.round > 18) return 10 - d.price * 0.1;
if (next >= g.citiesToEndGame && possible < opponentPower) return -30;
if (next <= x.cap && (next <= availablePower || x.imminent)) return 25 - d.price * 0.35;
if (style === 'rush' && p.money - d.price > 30) return 8 - d.price * 0.15;
return -20;
}
case 'UsePowerPlant':
return production.plants.includes(d.powerPlant) &&
c.RES.every((r, i) => d.resourcesSpent.filter((x) => x === r).length <= production.used[i])
? 20 +
d.citiesPowered * 0.1 -
d.resourcesSpent.reduce((s, r) => s + c.resourcePrice(g, r), 0) * 0.01
: -10;
case 'DiscardResources':
return p[d + 'Left'] - x.fuel.used[c.RES.indexOf(d)];
case 'Pass':
return 0;
default:
return 0;
}
});
}
function choose(g, seat, rng = () => 0.5, style = 'economic') {
const actions = c.candidates(g, seat),
values = scores(g, seat, actions, style);
let index = 0,
best = -Infinity;
values.forEach((x, i) => {
x += rng() * 0.001;
if (x > best) {
best = x;
index = i;
}
});
return { index, action: actions[index] };
}
module.exports = {
income,
replenishment,
fuelVariants,
plans,
purchaseCost,
plan,
demand,
futurePressure,
context,
plantValue,
scores,
choose,
};

8
ai/strong/encoders.cjs Normal file
View file

@ -0,0 +1,8 @@
const current = require('./features.cjs');
function forRevision(revision = current.FEATURE_REVISION) {
if (revision === current.FEATURE_REVISION) return current;
if (revision === '4.0-multiplayer') return require('./features-v4.cjs');
if (revision === '3.0') return require('./features-v3_0.cjs');
throw Error('Unsupported feature revision: ' + revision);
}
module.exports = { forRevision };

227
ai/strong/evaluate.py Normal file
View file

@ -0,0 +1,227 @@
"""Independent CPU arena, with reserved seeds and per-rule results."""
import sys, argparse, json, time
import subprocess
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import numpy as np
from infer import Model
from pool import EnginePool
from async_pool import AsyncEnginePool
from arena_statistics import win_summary, search_summary, validate_pairs
from search_scope import SCOPES, search_enabled
from feature_contract import FEATURE_REVISION, check_revision, model_revision
p = argparse.ArgumentParser()
p.add_argument("model")
p.add_argument("--players", type=int, choices=range(2, 7), default=3)
p.add_argument("--deal-offset", type=int, default=0)
p.add_argument("--search-scope", choices=SCOPES, default="all")
p.add_argument(
"--opponent",
default="economic",
choices=["economic", "heuristic", "rush", "legacy", "search", "search_geo"],
)
p.add_argument("--opponent-model", help="Frozen ONNX policy in every opponent seat")
p.add_argument("--workers", type=int, default=4)
p.add_argument(
"--async-rollout",
action="store_true",
help="Advance ready games independently using one engine process per game",
)
p.add_argument("--geographic-search", action="store_true")
p.add_argument(
"--disable-search-proposal",
action="store_true",
help="Ablation: omit the model candidate from search; keep model actions outside search",
)
p.add_argument(
"--search-samples",
type=int,
default=0,
help="Public-belief search guided by the candidate model",
)
p.add_argument("--games", type=int, default=480)
p.add_argument("--seed", default="strong-screening-v1")
p.add_argument("--output", required=True)
p.add_argument(
"--allow-feature-transfer",
action="store_true",
help="Explicit research-only encoder transfer",
)
args = p.parse_args()
if not 0 <= args.search_samples <= 64:
p.error("--search-samples must be 0..64")
if args.disable_search_proposal and not args.search_samples:
p.error("--disable-search-proposal requires positive --search-samples")
if args.geographic_search and not args.search_samples:
p.error("--geographic-search requires positive --search-samples")
search_max_steps = int(
subprocess.check_output(
[
"node",
"-e",
"console.log(require('./ai/strong/search.cjs').DEFAULT_MAX_STEPS)",
],
text=True,
)
)
model = Model(args.model)
paired_size = 4 * args.players
if args.games < paired_size or args.games % paired_size:
p.error(
f"--games must be a positive multiple of {paired_size} for paired rules and seats"
)
if args.deal_offset < 0:
p.error("--deal-offset cannot be negative")
opponent_model = Model(args.opponent_model) if args.opponent_model else None
for actor in [model, opponent_model]:
if actor and args.players != 3 and model_revision(actor) != "4.0-multiplayer":
p.error("Non-three-player evaluation requires schema 4 for every model")
if args.allow_feature_transfer and model_revision(model) == "4.0-multiplayer":
p.error("Schema 4 cannot be transferred to a schema 3 encoder")
pool_class = AsyncEnginePool if args.async_rollout else EnginePool
engine_workers = args.games if args.async_rollout else min(args.workers, args.games)
pool = pool_class(engine_workers, seed=args.seed, script="ai/strong/bridge.cjs")
feature_revision = (
FEATURE_REVISION if args.allow_feature_transfer else model_revision(model)
)
feature_revisions = (
{} if args.allow_feature_transfer else {"learner": model_revision(model)}
)
if opponent_model and not args.allow_feature_transfer:
feature_revisions["snapshot0"] = model_revision(opponent_model)
try:
current = pool.call(
{
"op": "reset",
"n": args.games,
"playerCount": args.players,
"offset": args.deal_offset * paired_size,
"mode": "snapshot0" if opponent_model else args.opponent,
"arenaSeed": args.seed,
"featureRevisions": feature_revisions,
}
)["observations"]
except BaseException:
pool.close()
raise
rows = []
latency = []
start = time.perf_counter()
last_progress = start
try:
while any(x is not None for x in current):
actions = []
for x in current:
if x is None:
actions.append(None)
continue
t = time.perf_counter()
actor = model if x["roles"][x["seat"]] == "learner" else opponent_model
check_revision(
actor, x.get("featureRevision", "3.0"), args.allow_feature_transfer
)
a, _ = actor.predict(x["state"], x["actions"])
if actor is model:
latency.append(1000 * (time.perf_counter() - t))
actions.append(
{
"proposal": a,
"searchSamples": args.search_samples,
"geography": args.geographic_search,
"disableSearchProposal": args.disable_search_proposal,
}
if actor is model
and args.search_samples
and search_enabled(args.search_scope, x["variant"], x["sealed"])
else a
)
r = pool.call({"op": "step", "actions": actions})
current = r["observations"]
for e in r["ended"]:
seat = e["roles"].index("learner")
rows.append(
{
**e,
"seat": seat,
"variant": "recharged" if e["episode"] % 2 else "original",
"sealed": e["episode"] % 4 < 2,
"win": e["value"][seat],
}
)
if time.perf_counter() - last_progress >= 30:
print(
json.dumps(
{
"stage": "arena_progress",
"completed_games": len(rows),
"requested_games": args.games,
"seconds": time.perf_counter() - start,
"seed": args.seed,
}
),
flush=True,
)
last_progress = time.perf_counter()
finally:
pool.close()
validate_pairs(rows, args.players)
report = {
"async_rollout": args.async_rollout,
"engine_workers": engine_workers,
"player_count": args.players,
"chance_win_rate": 1 / args.players,
"deal_offset": args.deal_offset,
"model": args.model,
"model_sha256": model.sha256,
"model_feature_revision": model_revision(model),
"encoder_feature_revision": feature_revision,
"opponent": args.opponent_model or args.opponent,
"opponent_sha256": opponent_model.sha256 if opponent_model else None,
"opponent_feature_revision": model_revision(opponent_model)
if opponent_model
else None,
"paired_seats": True,
"candidate_search_samples": args.search_samples,
"search_max_steps": search_max_steps,
"candidate_search_scope": args.search_scope,
"candidate_geographic_search": args.geographic_search,
"candidate_search_model_proposal": not args.disable_search_proposal,
"seed": args.seed,
"games": len(rows),
"win_rate": float(np.mean([r["win"] for r in rows])),
"truncated": sum(r["truncated"] for r in rows),
"seconds": time.perf_counter() - start,
"inference_p95_ms": float(np.percentile(latency, 95)),
"by_rules": [
{
"variant": v,
"sealed": s,
"games": len([r for r in rows if r["variant"] == v and r["sealed"] == s]),
"win_rate": float(
np.mean(
[r["win"] for r in rows if r["variant"] == v and r["sealed"] == s]
)
),
}
for v in ["original", "recharged"]
for s in [False, True]
],
"results": rows,
}
report.update(win_summary(rows))
report.update(search_summary(rows))
for group in report["by_rules"]:
group.update(
win_summary(
[
r
for r in rows
if r["variant"] == group["variant"] and r["sealed"] == group["sealed"]
]
)
)
Path(args.output).write_text(json.dumps(report, indent=2))
print(json.dumps({k: v for k, v in report.items() if k != "results"}))

28796
ai/strong/experiments.json Normal file

File diff suppressed because it is too large Load diff

51
ai/strong/export.py Normal file
View file

@ -0,0 +1,51 @@
"""CPU-only checkpoint conversion; no gradient updates."""
import argparse
import json
from pathlib import Path
import torch
from model import policy_from_checkpoint
from feature_contract import embed_revision
p = argparse.ArgumentParser()
p.add_argument("checkpoint")
p.add_argument("output")
p.add_argument("--strategic-only", action="store_true")
args = p.parse_args()
torch.set_num_threads(1)
checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
strategic_only = args.strategic_only or checkpoint.get("strategic_only", False)
if args.strategic_only and checkpoint.get("architecture", "policy") != "policy":
p.error("Strategic-only override requires a single policy")
checkpoint["strategic_only"] = strategic_only
net = policy_from_checkpoint(checkpoint).eval()
torch.onnx.export(
net,
(
torch.zeros(1, checkpoint.get("state_dim", 738)),
torch.zeros(1, 8, checkpoint.get("action_dim", 96)),
torch.ones(1, 8, dtype=torch.bool),
),
args.output,
input_names=["state", "actions", "mask"],
output_names=["logits", "value"],
dynamic_axes={
"state": {0: "batch"},
"actions": {0: "batch", 1: "candidates"},
"mask": {0: "batch", 1: "candidates"},
"logits": {0: "batch", 1: "candidates"},
"value": {0: "batch"},
},
opset_version=17,
dynamo=False,
)
embed_revision(args.output, checkpoint.get("feature_revision", "3.0"))
Path(args.output + ".json").write_text(
json.dumps(
{
"source": args.checkpoint,
"strategic_only": strategic_only,
"schema": checkpoint.get("schema", 3),
}
)
)

View file

@ -0,0 +1,26 @@
"""Keep checkpoints paired with the exact meaning of their input features."""
FEATURE_REVISION = "3.1-uranium39"
METADATA_KEY = "powergrid.feature_revision"
def model_revision(model):
return model.session.get_modelmeta().custom_metadata_map.get(METADATA_KEY, "3.0")
def check_revision(model, observed, allow_transfer=False):
trained = model_revision(model)
if trained != observed and not allow_transfer:
raise ValueError(
f"Feature revision mismatch: model {trained}, encoder {observed}"
)
def embed_revision(path, revision=FEATURE_REVISION):
import onnx
model = onnx.load(str(path))
props = {p.key: p.value for p in model.metadata_props}
props[METADATA_KEY] = revision
onnx.helper.set_model_props(model, props)
onnx.save(model, str(path))

View file

@ -0,0 +1,84 @@
// Frozen encoder for historical checkpoints; do not update its semantics.
const c = require('../core.cjs'),
eco = require('./economics-v3_0.cjs');
const SCHEMA = 3;
const spatial = require('./spatial.cjs');
function observe(g, seat, geometry) {
const state = c.observe(g, seat),
order = [seat, (seat + 1) % 3, (seat + 2) % 3];
for (const r of c.RES) {
const supplies = g[r + 'Resupply'][g.players.length - 2];
state.push(...supplies.map((n) => n / 12), c.resourcePrice(g, r) / 20);
// Exact capped refill available now, and shared demand under full portfolio use.
state.push(Math.min(g[r + 'Supply'], eco.replenishment(g, r), g[r + 'Prices'].length - g[r + 'Market']) / 24);
}
state.push(g.currentPlayers.length / 3, ...order.map((i) => +g.currentPlayers.includes(i)));
for (const id of order) {
const p = g.players[id],
desired = eco.demand(g, p),
fuelled = eco.plan(g, p, 22, { buy: false });
state.push(
c.capacity(p) / 22,
fuelled.power / 22,
...desired.map((n) => n / 12),
...p.powerPlants.slice(0, 4).map((pp) => +p.powerPlantsNotUsed.includes(pp.number)),
...Array(Math.max(0, 4 - p.powerPlants.length)).fill(0)
);
state.push(...Array.from({ length: 4 }, (_, i) => +(p.powerPlants[i]?.type === 6)));
const rank = g.playerOrder.indexOf(id);
state.push(rank / 2, (2 - rank) / 2, +!p.passed, +!p.skipAuction);
for (const r of c.RES) {
const i = c.RES.indexOf(r);
state.push(Math.max(0, desired[i] - p[r + 'Left']) / 12);
}
}
state.push(...g.paymentTable.slice(0, 23).map((n) => n / 200));
if (!state.every(Number.isFinite)) throw Error('nonfinite strong observation');
return [...state, ...spatial.stateFeatures(g, seat, geometry)];
}
function encode(g, seat) {
const moves = c.candidates(g, seat),
prior = eco.scores(g, seat, moves),
p = g.players[seat];
const best = Math.max(...prior);
const geometry = spatial.territories(g, seat),
worth = new Map(),
ownDemand = eco.demand(g, p);
const plantWorth = (pp) => {
if (!worth.has(pp.number)) worth.set(pp.number, eco.plantValue(g, p, pp));
return worth.get(pp.number);
};
const actions = moves.map((a, i) => {
const pp = a.name === 'ChoosePowerPlant' ? g.actualMarket.find((p) => p.number === a.data) : g.chosenPowerPlant;
const cost =
a.name === 'BuyResource'
? c.resourcePrice(g, a.data.resource)
: a.name === 'Bid'
? a.data
: a.data?.price || 0;
const extra = [
Math.max(-10, Math.min(10, prior[i] / 10)),
+(prior[i] === best),
cost / Math.max(1, p.money),
Math.max(0, p.money - cost) / 200,
];
if (pp) extra.push(plantWorth(pp) / 200, pp.citiesPowered / 8, pp.cost / 4);
else extra.push(0, 0, 0);
if (a.name === 'BuyResource') {
const r = a.data.resource,
j = c.RES.indexOf(r);
extra.push(eco.replenishment(g, r) / 12, (ownDemand[j] - p[r + 'Left']) / 12);
} else extra.push(0, 0);
return [...c.actionFeatures(g, seat, a), ...extra, ...spatial.actionFeatures(g, seat, a, geometry)];
});
return {
featureRevision: '3.0',
state: observe(g, seat, geometry),
actions,
moves,
prior: prior.map((x) => Math.max(-10, Math.min(10, x / 10))),
teacher: prior.indexOf(best),
seat,
};
}
module.exports = { SCHEMA, observe, encode };

175
ai/strong/features-v4.cjs Normal file
View file

@ -0,0 +1,175 @@
// Schema 4: fixed-size public observations for 2–6 players. Schema 3 stays frozen.
const c = require('../core.cjs'),
eco = require('./economics.cjs'),
spatial = require('./spatial.cjs');
const FEATURE_REVISION = '4.0-multiplayer',
MAX_PLAYERS = 6;
const pad = (xs, n) => [...xs, ...Array(Math.max(0, n - xs.length)).fill(0)];
const plant = (p) =>
p
? [p.number / 50, p.cost / 4, p.citiesPowered / 8, ...Array.from({ length: 7 }, (_, i) => +(p.type === i))]
: Array(10).fill(0);
function assertScope(g, seat) {
if (
g.map.name !== 'Germany' ||
g.players.length < 2 ||
g.players.length > 6 ||
g.options.randomizeMap ||
g.options.chooseRegions ||
g.options.chooseColors ||
g.map.cities.some((x) => !c.CITIES.includes(x.name))
)
throw Error('Schema 4 supports automatic Germany games with 2–6 players');
if (!Number.isInteger(seat) || seat < 0 || seat >= g.players.length) throw Error('Invalid observing seat');
}
function observe(g, seat, geometry = spatial.territories(g, seat)) {
assertScope(g, seat);
const n = g.players.length,
order = Array.from({ length: n }, (_, i) => (seat + i) % n);
const playerMask = pad(
order.map(() => 1),
MAX_PLAYERS
);
const global = [
...Object.values(c.E.Phase).map((x) => +(x === g.phase)),
g.round / 20,
g.step / 3,
+(g.options.variant === 'recharged'),
+g.options.fastBid,
n / 6,
g.cardsLeft / 50,
+g.nextCardWeak,
(g.options.fastBid ? 0 : g.currentBid || 0) / 100,
(g.minimunBid || 0) / 100,
g.citiesToEndGame / 25,
g.citiesToStep2 / 20,
+!!g.card39Bought,
g.currentPlayers.length / n,
];
for (const r of c.RES)
global.push(
g[r + 'Market'] / 24,
g[r + 'Supply'] / 24,
...pad(
g[r + 'Prices'].map((x) => x / 20),
24
),
...[1, 2, 3].map((step) => eco.replenishment(g, r, step) / 12),
c.resourcePrice(g, r) / 20,
Math.min(g[r + 'Supply'], eco.replenishment(g, r), g[r + 'Prices'].length - g[r + 'Market']) / 24
);
global.push(
...pad(
g.paymentTable.slice(0, 23).map((x) => x / 200),
23
)
);
for (let i = 0; i < 4; i++) global.push(...plant(g.actualMarket[i]), ...plant(g.futureMarket[i]));
global.push(...plant(g.chosenPowerPlant));
const players = order.map((id) => {
const p = g.players[id],
rank = g.playerOrder.indexOf(id),
demand = eco.demand(g, p),
fuel = eco.plan(g, p, 22, { buy: false });
const row = [
p.money / 500,
p.cities.length / 22,
p.housesLeft / 22,
p.citiesPowered / 22,
rank / (n - 1),
(n - 1 - rank) / (n - 1),
+p.skipAuction,
+p.passed,
+g.currentPlayers.includes(id),
+(g.auctioningPlayer === id),
(g.options.fastBid ? 0 : p.bid || 0) / 100,
p.hybridCapacity / 24,
c.capacity(p) / 22,
fuel.power / 22,
];
for (const [j, r] of c.RES.entries())
row.push(
p[r + 'Left'] / 24,
p[r + 'Capacity'] / 24,
demand[j] / 12,
Math.max(0, demand[j] - p[r + 'Left']) / 12
);
for (let i = 0; i < 4; i++)
row.push(
...plant(p.powerPlants[i]),
+!!p.powerPlants[i] && +p.powerPlantsNotUsed.includes(p.powerPlants[i].number)
);
return row;
});
const playerWidth = players[0].length;
while (players.length < MAX_PLAYERS) players.push(Array(playerWidth).fill(0));
const cities = c.CITIES.flatMap((name) => [
+g.map.cities.some((x) => x.name === name),
...pad(
order.map((id) => +g.players[id].cities.some((x) => x.name === name)),
MAX_PLAYERS
),
]);
const territory = [];
for (const [groups, limit] of [
[geometry.regions, 8],
[geometry.islands, 4],
])
for (let i = 0; i < limit; i++) {
const x = groups[i];
territory.push(
...(x
? [
1,
x.size / 64,
x.empty / 64,
x.open / 64,
x.totalFree / 128,
...pad(
x.owned.map((v) => v / 22),
MAX_PLAYERS
),
]
: Array(11).fill(0))
);
}
territory.push((g.map.crossIslandSurcharge || 0) / 100);
const state = [...playerMask, ...global, ...players.flat(), ...cities, ...territory];
if (!state.every(Number.isFinite)) throw Error('Nonfinite schema 4 observation');
return {
state,
playerMask,
playerOrder: order,
layout: { global: global.length, player: playerWidth, cities: cities.length, territory: territory.length },
};
}
function encode(g, seat) {
const geometry = spatial.territories(g, seat),
observation = observe(g, seat, geometry);
const moves = c.candidates(g, seat),
raw = eco.scores(g, seat, moves),
best = Math.max(...raw);
const actions = moves.map((a, i) => {
const geo = spatial.actionFeatures(g, seat, a, geometry),
n = g.players.length;
return [
...c.actionFeatures(g, seat, a),
Math.max(-10, Math.min(10, raw[i] / 10)),
+(raw[i] === best),
...pad(geo.slice(0, n), 6),
...pad(geo.slice(n, 2 * n), 6),
...pad(geo.slice(2 * n, 3 * n), 6),
...geo.slice(3 * n),
];
});
return {
featureRevision: FEATURE_REVISION,
...observation,
actions,
moves,
prior: raw.map((x) => Math.max(-10, Math.min(10, x / 10))),
teacher: raw.indexOf(best),
seat,
};
}
module.exports = { SCHEMA: 4, FEATURE_REVISION, MAX_PLAYERS, observe, encode };

84
ai/strong/features.cjs Normal file
View file

@ -0,0 +1,84 @@
const c = require('../core.cjs'),
eco = require('./economics.cjs');
const SCHEMA = 3;
const FEATURE_REVISION = '3.1-uranium39';
const spatial = require('./spatial.cjs');
function observe(g, seat, geometry) {
const state = c.observe(g, seat),
order = [seat, (seat + 1) % 3, (seat + 2) % 3];
for (const r of c.RES) {
const supplies = [1, 2, 3].map((step) => eco.replenishment(g, r, step));
state.push(...supplies.map((n) => n / 12), c.resourcePrice(g, r) / 20);
// Exact capped refill available now, and shared demand under full portfolio use.
state.push(Math.min(g[r + 'Supply'], eco.replenishment(g, r), g[r + 'Prices'].length - g[r + 'Market']) / 24);
}
state.push(g.currentPlayers.length / 3, ...order.map((i) => +g.currentPlayers.includes(i)));
for (const id of order) {
const p = g.players[id],
desired = eco.demand(g, p),
fuelled = eco.plan(g, p, 22, { buy: false });
state.push(
c.capacity(p) / 22,
fuelled.power / 22,
...desired.map((n) => n / 12),
...p.powerPlants.slice(0, 4).map((pp) => +p.powerPlantsNotUsed.includes(pp.number)),
...Array(Math.max(0, 4 - p.powerPlants.length)).fill(0)
);
state.push(...Array.from({ length: 4 }, (_, i) => +(p.powerPlants[i]?.type === 6)));
const rank = g.playerOrder.indexOf(id);
state.push(rank / 2, (2 - rank) / 2, +!p.passed, +!p.skipAuction);
for (const r of c.RES) {
const i = c.RES.indexOf(r);
state.push(Math.max(0, desired[i] - p[r + 'Left']) / 12);
}
}
state.push(...g.paymentTable.slice(0, 23).map((n) => n / 200));
if (!state.every(Number.isFinite)) throw Error('nonfinite strong observation');
return [...state, ...spatial.stateFeatures(g, seat, geometry)];
}
function encode(g, seat) {
const moves = c.candidates(g, seat),
prior = eco.scores(g, seat, moves),
p = g.players[seat];
const best = Math.max(...prior);
const geometry = spatial.territories(g, seat),
worth = new Map(),
ownDemand = eco.demand(g, p);
const plantWorth = (pp) => {
if (!worth.has(pp.number)) worth.set(pp.number, eco.plantValue(g, p, pp));
return worth.get(pp.number);
};
const actions = moves.map((a, i) => {
const pp = a.name === 'ChoosePowerPlant' ? g.actualMarket.find((p) => p.number === a.data) : g.chosenPowerPlant;
const cost =
a.name === 'BuyResource'
? c.resourcePrice(g, a.data.resource)
: a.name === 'Bid'
? a.data
: a.data?.price || 0;
const extra = [
Math.max(-10, Math.min(10, prior[i] / 10)),
+(prior[i] === best),
cost / Math.max(1, p.money),
Math.max(0, p.money - cost) / 200,
];
if (pp) extra.push(plantWorth(pp) / 200, pp.citiesPowered / 8, pp.cost / 4);
else extra.push(0, 0, 0);
if (a.name === 'BuyResource') {
const r = a.data.resource,
j = c.RES.indexOf(r);
extra.push(eco.replenishment(g, r) / 12, (ownDemand[j] - p[r + 'Left']) / 12);
} else extra.push(0, 0);
return [...c.actionFeatures(g, seat, a), ...extra, ...spatial.actionFeatures(g, seat, a, geometry)];
});
return {
featureRevision: FEATURE_REVISION,
state: observe(g, seat, geometry),
actions,
moves,
prior: prior.map((x) => Math.max(-10, Math.min(10, x / 10))),
teacher: prior.indexOf(best),
seat,
};
}
module.exports = { SCHEMA, FEATURE_REVISION, observe, encode };

View file

@ -0,0 +1,171 @@
{
"status": "prepared; no selected candidate; final seeds unused",
"seed_prefix": "strong-multiplayer-final-reserved-v1",
"scope": {
"map": "Germany",
"players": [2, 3, 4, 5, 6],
"variants": ["original", "recharged"],
"auctions": ["open", "sealed"],
"setup": "automatic"
},
"reason_for_new_protocol": "Scope expanded from three players to 2\u20136 before any final seeds were used. Preserve the original three-player minimum rates; scale other counts by the same fraction of improvement above equal-seat chance. Default-bot minimum stays 90% at every count.",
"pairing": "Every independent deal is repeated in each candidate seat and all four rule combinations. Exactly 4*N matches per deal; disjoint integer deal offsets across shards.",
"intervals": "95% seed-cluster bootstrap; resample deals, retaining their seat/rule repeats. Report each count/rule separately. Intervals are per comparison, not a simultaneous family-wide confidence guarantee.",
"requirements": {
"all_games_complete": true,
"no_illegal_moves": true,
"full_paired_deals": true,
"each_count_overall_interval_lower_bound": "strictly above 1/N",
"each_count_each_rule_interval_lower_bound": "strictly above 1/N",
"search_rollout_counts": "required, with incomplete rollouts explicitly reported",
"export_parity": "All 2553 multiplayer fixtures agree in legal action with checkpoint, finite value outputs, inactive slots zero",
"serving": "All 2553 fixtures return legal moves with correct request/revision and player ordering; benchmark same selected model/search settings on actual AMD 8840U, with results for every count",
"package": "Standalone extracted archive hashes and legal CPU responses verified"
},
"opponents": [
{
"name": "legacy",
"independent_deals_per_count": 40,
"counts": {
"2": {
"games": 320,
"minimum_win_rate": 0.9
},
"3": {
"games": 480,
"minimum_win_rate": 0.9
},
"4": {
"games": 640,
"minimum_win_rate": 0.9
},
"5": {
"games": 800,
"minimum_win_rate": 0.9
},
"6": {
"games": 960,
"minimum_win_rate": 0.9
}
}
},
{
"name": "heuristic",
"independent_deals_per_count": 40,
"counts": {
"2": {
"games": 320,
"minimum_win_rate": 0.775
},
"3": {
"games": 480,
"minimum_win_rate": 0.7000000000000001
},
"4": {
"games": 640,
"minimum_win_rate": 0.6625000000000001
},
"5": {
"games": 800,
"minimum_win_rate": 0.6400000000000001
},
"6": {
"games": 960,
"minimum_win_rate": 0.625
}
}
},
{
"name": "economic",
"independent_deals_per_count": 40,
"counts": {
"2": {
"games": 320,
"minimum_win_rate": 0.6625
},
"3": {
"games": 480,
"minimum_win_rate": 0.55
},
"4": {
"games": 640,
"minimum_win_rate": 0.49375
},
"5": {
"games": 800,
"minimum_win_rate": 0.46
},
"6": {
"games": 960,
"minimum_win_rate": 0.4375
}
}
},
{
"name": "rush",
"independent_deals_per_count": 40,
"counts": {
"2": {
"games": 320,
"minimum_win_rate": 0.625
},
"3": {
"games": 480,
"minimum_win_rate": 0.5
},
"4": {
"games": 640,
"minimum_win_rate": 0.4375
},
"5": {
"games": 800,
"minimum_win_rate": 0.4
},
"6": {
"games": 960,
"minimum_win_rate": 0.375
}
}
},
{
"name": "search_geo",
"independent_deals_per_count": 80,
"counts": {
"2": {
"games": 640,
"minimum_win_rate": 0.55
},
"3": {
"games": 960,
"minimum_win_rate": 0.4
},
"4": {
"games": 1280,
"minimum_win_rate": 0.325
},
"5": {
"games": 1600,
"minimum_win_rate": 0.28
},
"6": {
"games": 1920,
"minimum_win_rate": 0.25
}
}
},
{
"name": "frozen_a260",
"counts": {
"3": {
"games": 960,
"minimum_win_rate": 0.4
}
},
"independent_deals_per_count": 80,
"model_path": "runs/strong-league-v2-a/best.onnx",
"model_revision": "b38515c29e57826de05b55b645c29591e4a886bf",
"model_sha256": "9b46db558669a0c3085412fe2544359eda55ed9f092dffb67bead6af3c409ecd"
}
],
"failure_policy": "A failed gate remains a failure. Do not relax thresholds after seeing final results. New candidate requires a new reserved final seed prefix."
}

View file

@ -0,0 +1,35 @@
{
"status": "prepared; candidate not selected; final seeds unused",
"seed_prefix": "strong-final-reserved-v1",
"scope": "Germany, three players, automatic setup, original/Recharged, open/sealed",
"pairing": "Each independent deal is repeated across all three candidate seats and all four rule combinations.",
"intervals": "95% bootstrap intervals resample independent deals, retaining correlated seat and rule repeats. Intervals are per comparison, not a simultaneous family-wide confidence claim.",
"requirements": {
"all_games_complete": true,
"no_illegal_moves": true,
"no_missing_or_duplicate_paired_matches": true,
"overall_interval_lower_bound_above": 0.3333333333333333,
"each_rule_interval_lower_bound_above": 0.3333333333333333,
"report_search_rollout_truncations": true,
"export_action_parity": "All 427 fixture positions must agree with the training checkpoint.",
"cpu_serving": "All 427 fixtures must return legal moves on the AMD 8840U; report cold, warm, search-only and phase-specific latency.",
"package": "Verify file hashes and legal responses from the extracted standalone archive."
},
"opponents": [
{ "name": "legacy", "games": 480, "minimum_win_rate": 0.9 },
{ "name": "heuristic", "games": 480, "minimum_win_rate": 0.7 },
{ "name": "economic", "games": 480, "minimum_win_rate": 0.55 },
{ "name": "rush", "games": 480, "minimum_win_rate": 0.5 },
{ "name": "search_geo", "games": 960, "minimum_win_rate": 0.4 },
{
"name": "frozen_a260",
"games": 960,
"minimum_win_rate": 0.4,
"model_path": "runs/strong-league-v2-a/best.onnx",
"model_revision": "b38515c29e57826de05b55b645c29591e4a886bf",
"model_sha256": "9b46db558669a0c3085412fe2544359eda55ed9f092dffb67bead6af3c409ecd"
}
],
"failure_policy": "A failed gate is reported as a failure; do not weaken thresholds after seeing final results. Any subsequent model selection uses new development evidence and a new final seed prefix.",
"claim_limits": "These gates establish strength against the measured opponent suite, not expert-human strength, other maps/player counts, or calibrated analysis values."
}

View file

@ -0,0 +1,555 @@
{
"seat": 1,
"options": {
"samples": 48,
"candidates": 6,
"extraCandidates": [39],
"geography": true,
"seed": "arena-guided-127-8"
},
"original": {
"index": 0,
"action": { "name": "Bid", "data": 12 },
"evaluations": 240,
"truncated": 1,
"winEstimate": 0.16666666666666666,
"values": { "0": 8, "1": 6, "2": 7, "19": 0, "39": 6 }
},
"extended": {
"index": 0,
"action": { "name": "Bid", "data": 12 },
"evaluations": 240,
"truncated": 0,
"winEstimate": 0.16666666666666666,
"values": { "0": 8, "1": 6, "2": 8, "19": 0, "39": 6 }
},
"state": {
"map": {
"name": "Germany",
"cities": [
{ "name": "Flensburg", "region": "green", "x": 37, "y": 427 },
{ "name": "Kiel", "region": "green", "x": 106, "y": 392 },
{ "name": "Hamburg", "region": "green", "x": 212, "y": 396 },
{ "name": "Hannover", "region": "green", "x": 378, "y": 395 },
{ "name": "Bremen", "region": "green", "x": 276, "y": 463 },
{ "name": "Wilhelmshaven", "region": "green", "x": 211, "y": 521 },
{ "name": "Cuxhaven", "region": "green", "x": 168, "y": 474 },
{ "name": "Lubeck", "region": "brown", "x": 153, "y": 341 },
{ "name": "Rostock", "region": "brown", "x": 128, "y": 256 },
{ "name": "Schwerin", "region": "brown", "x": 217, "y": 297 },
{ "name": "Stralsund", "region": "brown", "x": 210, "y": 126 },
{ "name": "Magdeburg", "region": "brown", "x": 389, "y": 271 },
{ "name": "Berlin", "region": "brown", "x": 355, "y": 170 },
{ "name": "Frankfurt-O", "region": "brown", "x": 381, "y": 99 },
{ "name": "Halle", "region": "yellow", "x": 493, "y": 259 },
{ "name": "Leipzig", "region": "yellow", "x": 526, "y": 222 },
{ "name": "Dresden", "region": "yellow", "x": 572, "y": 126 },
{ "name": "Erfurt", "region": "yellow", "x": 567, "y": 309 },
{ "name": "Fulda", "region": "yellow", "x": 628, "y": 398 },
{ "name": "W\u00fcrzburg", "region": "yellow", "x": 735, "y": 386 },
{ "name": "Nurnberg", "region": "yellow", "x": 780, "y": 309 },
{ "name": "Aachen", "region": "cyan", "x": 614, "y": 654 },
{ "name": "K\u00f6ln", "region": "cyan", "x": 590, "y": 589 },
{ "name": "Trier", "region": "cyan", "x": 739, "y": 628 },
{ "name": "Mainz", "region": "cyan", "x": 697, "y": 514 },
{ "name": "Frankfurt-M", "region": "cyan", "x": 672, "y": 473 },
{ "name": "Saarbr\u00fccken", "region": "cyan", "x": 818, "y": 568 },
{ "name": "Mannheim", "region": "cyan", "x": 796, "y": 479 },
{ "name": "Freiburg", "region": "purple", "x": 966, "y": 537 },
{ "name": "Stuttgart", "region": "purple", "x": 884, "y": 458 },
{ "name": "Konstanz", "region": "purple", "x": 1011, "y": 459 },
{ "name": "Augsburg", "region": "purple", "x": 911, "y": 346 },
{ "name": "Regensburg", "region": "purple", "x": 846, "y": 256 },
{ "name": "M\u00fcnchen", "region": "purple", "x": 967, "y": 278 },
{ "name": "Passau", "region": "purple", "x": 904, "y": 153 }
],
"connections": [
{ "nodes": ["Flensburg", "Kiel"], "cost": 4 },
{ "nodes": ["Kiel", "Hamburg"], "cost": 8 },
{ "nodes": ["Kiel", "Lubeck"], "cost": 4 },
{ "nodes": ["Hamburg", "Hannover"], "cost": 17 },
{ "nodes": ["Hamburg", "Bremen"], "cost": 11 },
{ "nodes": ["Hamburg", "Cuxhaven"], "cost": 11 },
{ "nodes": ["Hamburg", "Lubeck"], "cost": 6 },
{ "nodes": ["Hamburg", "Schwerin"], "cost": 8 },
{ "nodes": ["Bremen", "Wilhelmshaven"], "cost": 11 },
{ "nodes": ["Bremen", "Hannover"], "cost": 10 },
{ "nodes": ["Bremen", "Cuxhaven"], "cost": 8 },
{ "nodes": ["Hannover", "Schwerin"], "cost": 19 },
{ "nodes": ["Hannover", "Magdeburg"], "cost": 15 },
{ "nodes": ["Hannover", "Erfurt"], "cost": 19 },
{ "nodes": ["Lubeck", "Schwerin"], "cost": 6 },
{ "nodes": ["Schwerin", "Rostock"], "cost": 6 },
{ "nodes": ["Schwerin", "Stralsund"], "cost": 19 },
{ "nodes": ["Schwerin", "Berlin"], "cost": 18 },
{ "nodes": ["Schwerin", "Magdeburg"], "cost": 16 },
{ "nodes": ["Stralsund", "Rostock"], "cost": 19 },
{ "nodes": ["Stralsund", "Berlin"], "cost": 15 },
{ "nodes": ["Berlin", "Magdeburg"], "cost": 10 },
{ "nodes": ["Berlin", "Frankfurt-O"], "cost": 6 },
{ "nodes": ["Berlin", "Halle"], "cost": 17 },
{ "nodes": ["Magdeburg", "Halle"], "cost": 11 },
{ "nodes": ["Frankfurt-O", "Leipzig"], "cost": 21 },
{ "nodes": ["Frankfurt-O", "Dresden"], "cost": 16 },
{ "nodes": ["Halle", "Leipzig"], "cost": 0 },
{ "nodes": ["Leipzig", "Dresden"], "cost": 13 },
{ "nodes": ["Erfurt", "Halle"], "cost": 6 },
{ "nodes": ["Erfurt", "Dresden"], "cost": 19 },
{ "nodes": ["Erfurt", "Nurnberg"], "cost": 21 },
{ "nodes": ["Erfurt", "Fulda"], "cost": 13 },
{ "nodes": ["Fulda", "W\u00fcrzburg"], "cost": 11 },
{ "nodes": ["Fulda", "Frankfurt-M"], "cost": 8 },
{ "nodes": ["W\u00fcrzburg", "Nurnberg"], "cost": 8 },
{ "nodes": ["W\u00fcrzburg", "Frankfurt-M"], "cost": 13 },
{ "nodes": ["W\u00fcrzburg", "Mannheim"], "cost": 10 },
{ "nodes": ["W\u00fcrzburg", "Stuttgart"], "cost": 12 },
{ "nodes": ["W\u00fcrzburg", "Augsburg"], "cost": 19 },
{ "nodes": ["Nurnberg", "Augsburg"], "cost": 18 },
{ "nodes": ["Nurnberg", "Regensburg"], "cost": 12 },
{ "nodes": ["Aachen", "K\u00f6ln"], "cost": 7 },
{ "nodes": ["Aachen", "Trier"], "cost": 19 },
{ "nodes": ["Trier", "K\u00f6ln"], "cost": 20 },
{ "nodes": ["Trier", "Mainz"], "cost": 18 },
{ "nodes": ["Trier", "Saarbr\u00fccken"], "cost": 11 },
{ "nodes": ["Mainz", "Frankfurt-M"], "cost": 0 },
{ "nodes": ["Mainz", "K\u00f6ln"], "cost": 21 },
{ "nodes": ["Mainz", "Saarbr\u00fccken"], "cost": 10 },
{ "nodes": ["Mainz", "Mannheim"], "cost": 11 },
{ "nodes": ["Mannheim", "Saarbr\u00fccken"], "cost": 16 },
{ "nodes": ["Mannheim", "Stuttgart"], "cost": 6 },
{ "nodes": ["Stuttgart", "Saarbr\u00fccken"], "cost": 17 },
{ "nodes": ["Stuttgart", "Freiburg"], "cost": 16 },
{ "nodes": ["Stuttgart", "Konstanz"], "cost": 16 },
{ "nodes": ["Stuttgart", "Augsburg"], "cost": 15 },
{ "nodes": ["Konstanz", "Freiburg"], "cost": 14 },
{ "nodes": ["Konstanz", "Augsburg"], "cost": 17 },
{ "nodes": ["Regensburg", "Augsburg"], "cost": 13 },
{ "nodes": ["Regensburg", "M\u00fcnchen"], "cost": 10 },
{ "nodes": ["Regensburg", "Passau"], "cost": 12 },
{ "nodes": ["Augsburg", "M\u00fcnchen"], "cost": 6 },
{ "nodes": ["Passau", "M\u00fcnchen"], "cost": 14 }
],
"layout": "Landscape",
"mapPosition": [20, 20],
"mapSpecificRules": "Stop resupplying uranium after power plant 39 has been bought.",
"viewBox": [1465, 860],
"adjustRatio": [1, 1],
"playerOrderPosition": [1160, 140],
"cityCountPosition": [0, 0],
"powerPlantMarketPosition": [745, 0],
"actualMarketWidth": 430,
"buttonsPosition": [1305, 0],
"playerBoardsPosition": [1105, 200],
"roundInfoPosition": [20, 590],
"supplyPosition": [0, 720]
},
"players": [
{
"id": 0,
"powerPlants": [],
"coalCapacity": 0,
"coalLeft": 0,
"oilCapacity": 0,
"oilLeft": 0,
"garbageCapacity": 0,
"garbageLeft": 0,
"uraniumCapacity": 0,
"uraniumLeft": 0,
"hybridCapacity": 0,
"hybridLeft": 0,
"money": 50,
"housesLeft": 22,
"cities": [],
"powerPlantsNotUsed": [],
"availableMoves": null,
"lastMove": { "name": "Pass", "data": true },
"isDropped": false,
"isAI": false,
"bid": 7,
"passed": true,
"skipAuction": false,
"citiesPowered": 0,
"resourcesUsed": [],
"totalIncome": 0,
"totalSpentCities": 0,
"totalSpentConnections": 0,
"totalSpentPlants": 0,
"totalSpentResources": 0,
"usedFreeJump": false,
"totalTimeUsed": 0
},
{
"id": 1,
"powerPlants": [],
"coalCapacity": 0,
"coalLeft": 0,
"oilCapacity": 0,
"oilLeft": 0,
"garbageCapacity": 0,
"garbageLeft": 0,
"uraniumCapacity": 0,
"uraniumLeft": 0,
"hybridCapacity": 0,
"hybridLeft": 0,
"money": 50,
"housesLeft": 22,
"cities": [],
"powerPlantsNotUsed": [],
"availableMoves": {
"Bid": [
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
],
"Pass": [true]
},
"lastMove": { "name": "Bid", "data": 8 },
"isDropped": false,
"isAI": false,
"bid": 8,
"passed": false,
"skipAuction": false,
"citiesPowered": 0,
"resourcesUsed": [],
"totalIncome": 0,
"totalSpentCities": 0,
"totalSpentConnections": 0,
"totalSpentPlants": 0,
"totalSpentResources": 0,
"usedFreeJump": false,
"totalTimeUsed": 0
},
{
"id": 2,
"powerPlants": [],
"coalCapacity": 0,
"coalLeft": 0,
"oilCapacity": 0,
"oilLeft": 0,
"garbageCapacity": 0,
"garbageLeft": 0,
"uraniumCapacity": 0,
"uraniumLeft": 0,
"hybridCapacity": 0,
"hybridLeft": 0,
"money": 50,
"housesLeft": 22,
"cities": [],
"powerPlantsNotUsed": [],
"availableMoves": null,
"lastMove": { "name": "Bid", "data": 11 },
"isDropped": false,
"isAI": false,
"bid": 11,
"passed": false,
"skipAuction": false,
"citiesPowered": 0,
"resourcesUsed": [],
"totalIncome": 0,
"totalSpentCities": 0,
"totalSpentConnections": 0,
"totalSpentPlants": 0,
"totalSpentResources": 0,
"usedFreeJump": false,
"totalTimeUsed": 0
},
{
"id": 3,
"powerPlants": [],
"coalCapacity": 0,
"coalLeft": 0,
"oilCapacity": 0,
"oilLeft": 0,
"garbageCapacity": 0,
"garbageLeft": 0,
"uraniumCapacity": 0,
"uraniumLeft": 0,
"hybridCapacity": 0,
"hybridLeft": 0,
"money": 50,
"housesLeft": 22,
"cities": [],
"powerPlantsNotUsed": [],
"availableMoves": null,
"lastMove": { "name": "Pass", "data": true },
"isDropped": false,
"isAI": false,
"bid": 0,
"passed": true,
"skipAuction": false,
"citiesPowered": 0,
"resourcesUsed": [],
"totalIncome": 0,
"totalSpentCities": 0,
"totalSpentConnections": 0,
"totalSpentPlants": 0,
"totalSpentResources": 0,
"usedFreeJump": false,
"totalTimeUsed": 0
},
{
"id": 4,
"powerPlants": [],
"coalCapacity": 0,
"coalLeft": 0,
"oilCapacity": 0,
"oilLeft": 0,
"garbageCapacity": 0,
"garbageLeft": 0,
"uraniumCapacity": 0,
"uraniumLeft": 0,
"hybridCapacity": 0,
"hybridLeft": 0,
"money": 50,
"housesLeft": 22,
"cities": [],
"powerPlantsNotUsed": [],
"availableMoves": null,
"lastMove": { "name": "Pass", "data": true },
"isDropped": false,
"isAI": false,
"bid": 0,
"passed": true,
"skipAuction": false,
"citiesPowered": 0,
"resourcesUsed": [],
"totalIncome": 0,
"totalSpentCities": 0,
"totalSpentConnections": 0,
"totalSpentPlants": 0,
"totalSpentResources": 0,
"usedFreeJump": false,
"totalTimeUsed": 0
},
{
"id": 5,
"powerPlants": [],
"coalCapacity": 0,
"coalLeft": 0,
"oilCapacity": 0,
"oilLeft": 0,
"garbageCapacity": 0,
"garbageLeft": 0,
"uraniumCapacity": 0,
"uraniumLeft": 0,
"hybridCapacity": 0,
"hybridLeft": 0,
"money": 50,
"housesLeft": 22,
"cities": [],
"powerPlantsNotUsed": [],
"availableMoves": null,
"lastMove": { "name": "Pass", "data": true },
"isDropped": false,
"isAI": false,
"bid": 0,
"passed": true,
"skipAuction": false,
"citiesPowered": 0,
"resourcesUsed": [],
"totalIncome": 0,
"totalSpentCities": 0,
"totalSpentConnections": 0,
"totalSpentPlants": 0,
"totalSpentResources": 0,
"usedFreeJump": false,
"totalTimeUsed": 0
}
],
"playerOrder": [0, 1, 2, 3, 4, 5],
"currentPlayers": [1],
"powerPlantsDeck": [
{ "number": 12, "type": 4, "cost": 2, "citiesPowered": 2 },
{ "number": 26, "type": 1, "cost": 2, "citiesPowered": 5 },
{ "number": 42, "type": 0, "cost": 2, "citiesPowered": 6 },
{ "number": 37, "type": 5, "cost": 0, "citiesPowered": 4 },
{ "number": 34, "type": 3, "cost": 1, "citiesPowered": 5 },
{ "number": 46, "type": 4, "cost": 3, "citiesPowered": 7 },
{ "number": 14, "type": 2, "cost": 2, "citiesPowered": 2 },
{ "number": 27, "type": 5, "cost": 0, "citiesPowered": 3 },
{ "number": 25, "type": 0, "cost": 2, "citiesPowered": 5 },
{ "number": 29, "type": 4, "cost": 1, "citiesPowered": 4 },
{ "number": 33, "type": 5, "cost": 0, "citiesPowered": 4 },
{ "number": 19, "type": 2, "cost": 2, "citiesPowered": 3 },
{ "number": 15, "type": 0, "cost": 2, "citiesPowered": 3 },
{ "number": 24, "type": 2, "cost": 2, "citiesPowered": 4 },
{ "number": 30, "type": 2, "cost": 3, "citiesPowered": 6 },
{ "number": 16, "type": 1, "cost": 2, "citiesPowered": 3 },
{ "number": 31, "type": 0, "cost": 3, "citiesPowered": 6 },
{ "number": 23, "type": 3, "cost": 1, "citiesPowered": 3 },
{ "number": 35, "type": 1, "cost": 1, "citiesPowered": 5 },
{ "number": 17, "type": 3, "cost": 1, "citiesPowered": 2 },
{ "number": 39, "type": 3, "cost": 1, "citiesPowered": 6 },
{ "number": 50, "type": 6, "cost": 0, "citiesPowered": 6 },
{ "number": 20, "type": 0, "cost": 3, "citiesPowered": 5 },
{ "number": 44, "type": 5, "cost": 0, "citiesPowered": 5 },
{ "number": 40, "type": 1, "cost": 2, "citiesPowered": 6 },
{ "number": 36, "type": 0, "cost": 3, "citiesPowered": 7 },
{ "number": 18, "type": 5, "cost": 0, "citiesPowered": 2 },
{ "number": 3, "type": 1, "cost": 2, "citiesPowered": 1 },
{ "number": 22, "type": 5, "cost": 0, "citiesPowered": 2 },
{ "number": 38, "type": 2, "cost": 3, "citiesPowered": 7 },
{ "number": 21, "type": 4, "cost": 2, "citiesPowered": 4 },
{ "number": 32, "type": 1, "cost": 3, "citiesPowered": 6 },
{ "number": 28, "type": 3, "cost": 1, "citiesPowered": 4 },
{ "number": 7, "type": 1, "cost": 3, "citiesPowered": 2 },
{ "number": 99, "type": 7, "cost": 0, "citiesPowered": 6 }
],
"coalSupply": 0,
"oilSupply": 6,
"garbageSupply": 15,
"uraniumSupply": 10,
"coalResupply": [
[3, 4, 3],
[4, 5, 3],
[5, 6, 4],
[5, 7, 5],
[7, 9, 6]
],
"oilResupply": [
[2, 2, 4],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7]
],
"garbageResupply": [
[1, 2, 3],
[1, 2, 3],
[2, 3, 4],
[3, 3, 5],
[3, 5, 6]
],
"uraniumResupply": [
[1, 1, 1],
[1, 1, 1],
[1, 2, 2],
[2, 3, 2],
[2, 3, 3]
],
"coalMarket": 24,
"oilMarket": 18,
"garbageMarket": 9,
"uraniumMarket": 2,
"coalPrices": [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8],
"oilPrices": [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8],
"garbagePrices": [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8],
"uraniumPrices": [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16],
"actualMarket": [
{ "number": 4, "type": 0, "cost": 2, "citiesPowered": 1 },
{ "number": 5, "type": 4, "cost": 2, "citiesPowered": 1 },
{ "number": 6, "type": 2, "cost": 1, "citiesPowered": 1 },
{ "number": 8, "type": 0, "cost": 3, "citiesPowered": 2 }
],
"futureMarket": [
{ "number": 9, "type": 1, "cost": 1, "citiesPowered": 1 },
{ "number": 10, "type": 0, "cost": 2, "citiesPowered": 2 },
{ "number": 11, "type": 3, "cost": 1, "citiesPowered": 2 },
{ "number": 13, "type": 5, "cost": 0, "citiesPowered": 1 }
],
"chosenPowerPlant": { "number": 6, "type": 2, "cost": 1, "citiesPowered": 1 },
"currentBid": 11,
"highestBidders": [],
"auctioningPlayer": 0,
"step": 1,
"phase": "Auction",
"options": {
"fastBid": false,
"map": "Germany",
"variant": "recharged",
"showMoney": true,
"useNewRechargedSetup": true,
"trackTotalSpent": true,
"chooseRegions": false,
"chooseColors": false
},
"log": [
{ "type": "event", "event": "Game Start!" },
{
"type": "move",
"player": 0,
"move": { "name": "ChoosePowerPlant", "data": 6 },
"simple": "undefined chooses Power Plant 6 to initiate an auction.",
"pretty": "<span style=\"background-color: limegreen; font-weight: bold; padding: 0 3px;\">undefined</span> chooses Power Plant <b>6</b> to initiate an auction."
},
{
"type": "move",
"player": 0,
"move": { "name": "Bid", "data": 7 },
"simple": "undefined bids $7.",
"pretty": "<span style=\"background-color: limegreen; font-weight: bold; padding: 0 3px;\">undefined</span> bids <span style=\"color: green\">$7</span>."
},
{
"type": "move",
"player": 1,
"move": { "name": "Bid", "data": 8 },
"simple": "undefined bids $8.",
"pretty": "<span style=\"background-color: mediumorchid; font-weight: bold; padding: 0 3px;\">undefined</span> bids <span style=\"color: green\">$8</span>."
},
{
"type": "move",
"player": 2,
"move": { "name": "Bid", "data": 11 },
"simple": "undefined bids $11.",
"pretty": "<span style=\"background-color: red; font-weight: bold; padding: 0 3px;\">undefined</span> bids <span style=\"color: green\">$11</span>."
},
{
"type": "move",
"player": 3,
"move": { "name": "Pass", "data": true },
"simple": "undefined passes.",
"pretty": "<span style=\"background-color: dodgerblue; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
},
{
"type": "move",
"player": 4,
"move": { "name": "Pass", "data": true },
"simple": "undefined passes.",
"pretty": "<span style=\"background-color: yellow; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
},
{
"type": "move",
"player": 5,
"move": { "name": "Pass", "data": true },
"simple": "undefined passes.",
"pretty": "<span style=\"background-color: brown; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
},
{
"type": "move",
"player": 0,
"move": { "name": "Pass", "data": true },
"simple": "undefined passes.",
"pretty": "<span style=\"background-color: limegreen; font-weight: bold; padding: 0 3px;\">undefined</span> passes."
}
],
"hiddenLog": [],
"seed": "multiplayer-search-strong-probe-v1-6p-5",
"round": 1,
"newTurn": true,
"auctionSkips": 0,
"citiesToStep2": 6,
"citiesToEndGame": 14,
"resourceResupply": ["[7, 5, 3, 2]", "[9, 6, 5, 3]", "[6, 7, 6, 3]"],
"paymentTable": [
10, 22, 33, 44, 54, 64, 73, 82, 90, 98, 105, 112, 118, 124, 129, 134, 138, 142, 145, 148, 150, 150
],
"variant": "recharged",
"minimunBid": 6,
"plantDiscountActive": true,
"discardSmallestPlant": false,
"cardsLeft": 35,
"nextCardWeak": true,
"card39Bought": false,
"knownPowerPlantDeck": [
{ "number": 4, "type": 0, "cost": 2, "citiesPowered": 1 },
{ "number": 5, "type": 4, "cost": 2, "citiesPowered": 1 },
{ "number": 6, "type": 2, "cost": 1, "citiesPowered": 1 },
{ "number": 8, "type": 0, "cost": 3, "citiesPowered": 2 },
{ "number": 9, "type": 1, "cost": 1, "citiesPowered": 1 },
{ "number": 10, "type": 0, "cost": 2, "citiesPowered": 2 },
{ "number": 11, "type": 3, "cost": 1, "citiesPowered": 2 },
{ "number": 13, "type": 5, "cost": 0, "citiesPowered": 1 }
],
"knownPowerPlantDeckStep3": []
},
"provenance": "HF search-horizon-diagnostic-v1; exact replay of six-player arena deal 5, Recharged/open, seat 1, decision arena-guided-127-8."
}

View file

@ -0,0 +1,84 @@
"""HF CPU job: independent games produce a versioned, private teacher shard."""
import concurrent.futures
import gzip
import json
import os
from pathlib import Path
import subprocess
from huggingface_hub import HfApi
shard = int(os.environ["SHARD"])
games = int(os.getenv("GAMES", "128"))
version = os.getenv("DATA_VERSION", "search-teacher-v1")
output = Path(f"{version}-{shard}.jsonl.gz")
counts = {
"games": 0,
"positions": 0,
"teacher_disagreements": 0,
"truncated": 0,
"search_rollouts": 0,
"search_rollouts_truncated": 0,
"opponent_search_rollouts": 0,
"opponent_search_rollouts_truncated": 0,
}
def generate(game):
result = subprocess.run(
["node", "ai/strong/search-teacher.cjs", str(game)],
text=True,
capture_output=True,
check=True,
)
return json.loads(result.stdout)
with concurrent.futures.ThreadPoolExecutor(
int(os.getenv("DATA_WORKERS", "24"))
) as pool:
futures = [pool.submit(generate, shard * games + i) for i in range(games)]
with gzip.open(output, "wt") as stream:
for future in concurrent.futures.as_completed(futures):
game = future.result()
counts["games"] += 1
counts["truncated"] += game["truncated"]
counts["search_rollouts"] += game["searchStats"]["evaluations"]
counts["search_rollouts_truncated"] += game["searchStats"]["truncated"]
counts["opponent_search_rollouts"] += game.get(
"opponentSearchStats", {}
).get("evaluations", 0)
counts["opponent_search_rollouts_truncated"] += game.get(
"opponentSearchStats", {}
).get("truncated", 0)
# Keep truncated metadata, but never turn incomplete outcomes into targets.
if game["truncated"]:
game["rows"] = []
counts["positions"] += len(game["rows"])
counts["teacher_disagreements"] += sum(
not r["teacherAgrees"] for r in game["rows"]
)
stream.write(json.dumps(game, separators=(",", ":")) + "\n")
print(json.dumps({"shard": shard, **counts}), flush=True)
api = HfApi()
repo = os.environ["HF_DATA_REPO"]
api.upload_file(
repo_id=repo,
repo_type="dataset",
path_or_fileobj=str(output),
path_in_repo=version + "/" + output.name,
)
api.upload_file(
repo_id=repo,
repo_type="dataset",
path_or_fileobj=json.dumps(
{
"shard": shard,
"schema": 4 if os.getenv("FEATURE_REVISION") == "4.0-multiplayer" else 3,
"feature_revision": os.getenv("FEATURE_REVISION", "3.1-uranium39"),
"player_count": int(os.getenv("PLAYER_COUNT", "3")),
**counts,
}
).encode(),
path_in_repo=f"{version}/shard-{shard}-metrics.json",
)

View file

@ -0,0 +1,42 @@
// Proposal diversity only: the rules engine and rollout outcomes choose the move.
const graph = require('./public-graph.cjs');
const cache = new WeakMap();
function distances(map, topology) {
if (cache.has(map)) return cache.get(map);
const n = topology.nodes.length,
matrix = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 0 : Infinity)));
for (const edge of topology.edges) {
matrix[edge.a][edge.b] = Math.min(matrix[edge.a][edge.b], edge.cost);
matrix[edge.b][edge.a] = Math.min(matrix[edge.b][edge.a], edge.cost);
}
for (let k = 0; k < n; k++)
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++) matrix[i][j] = Math.min(matrix[i][j], matrix[i][k] + matrix[k][j]);
cache.set(map, matrix);
return matrix;
}
function rank(g, seat, actions) {
const topology = graph.encode(g, seat),
matrix = distances(g.map, topology),
index = new Map(topology.nodes.map((n, i) => [n.name, i])),
open = topology.nodes
.map((node, i) => ({ node, i }))
.filter(({ node }) => node.openSlots > 0 && !node.owners[0]);
return actions
.flatMap((action, i) => {
if (action.name !== 'Build') return [];
const at = index.get(action.data.name),
node = topology.nodes[at],
growth = open
.filter(({ i }) => i !== at)
.map(({ i }) => matrix[at][i])
.filter(Number.isFinite)
.sort((a, b) => a - b)
.slice(0, 3);
const score =
action.data.price + (growth.length ? growth.reduce((a, b) => a + b, 0) / growth.length : 1000);
return [{ index: i, region: node.region, island: node.island, score }];
})
.sort((a, b) => a.score - b.score || a.index - b.index);
}
module.exports = { rank };

View file

@ -0,0 +1,86 @@
{
"date": "2026-10-04",
"status": "paused",
"no_qualified_model": true,
"final_seeds_used": false,
"active_hf_jobs_at_check": 0,
"model_repo": "coyotte508/powergrid-ai-germany-v1",
"model_snapshot_revision": "daef30ae69d6a96f21e46abd8a30909689682364",
"dataset_repo": "coyotte508/powergrid-ai-training-v1",
"dataset_revision": "d07e072058ee877112d609280980fc806ee8ce28",
"diagnostic": {
"status": "COMPLETED",
"source_revision": "d07e072058ee877112d609280980fc806ee8ce28",
"source_archive": "strong-source-v36.tgz",
"source_sha256": "6c4170317a74a5148c2a576ad93d1170441e0d8e791a7e6c23197c51dad69109",
"base_revision": "aee5febe0ea0c60988f76a937521e87956544526",
"changed_files": [
"ai/strong/search.cjs",
"ai/strong/test-search-samples.cjs",
"ai/strong/audit-search-budget.cjs",
"ai/strong/audit-search-budgets.py"
],
"fixture_sha256": "855b34ad7f07665dfcb012a673147f0780820a9e7560fda268a9a39478c60ff4",
"positions": 60,
"samples_per_batch": 384,
"batches": [
"a",
"b"
],
"continuations": [
"mixed",
"economic",
"heuristic"
],
"search_max_steps": 2400,
"workers_per_job": 24,
"jobs": [
{
"run": "teacher-reliability-v2-2p",
"players": 2,
"job_id": "6abe1df0fbc85ba682360bd8",
"observed_stage": "COMPLETED"
},
{
"run": "teacher-reliability-v2-3p",
"players": 3,
"job_id": "6abe1df1404719ba3761721e",
"observed_stage": "COMPLETED"
},
{
"run": "teacher-reliability-v2-4p",
"players": 4,
"job_id": "6abe1df2fbc85ba682360bda",
"observed_stage": "COMPLETED"
},
{
"run": "teacher-reliability-v2-5p",
"players": 5,
"job_id": "6abe1df2fbc85ba682360bdc",
"observed_stage": "COMPLETED"
},
{
"run": "teacher-reliability-v2-6p",
"players": 6,
"job_id": "6abe1df3fbc85ba682360be0",
"observed_stage": "COMPLETED"
}
],
"purpose": "Separate finite-sample instability from dependence on continuation policy using nested budgets and shared public scenarios. Diagnostic only; no gradients and no strength claim.",
"tests": "3 search regression tests pass, including preservation of defaults and identical fixed-policy samples.",
"artifact_revision": "daef30ae69d6a96f21e46abd8a30909689682364",
"artifact_path": "runs/teacher-reliability-v2",
"summary_path": "ai/strong/handoff/teacher-reliability-v2-summary.json",
"audit_date": "2026-10-04",
"evaluations": 721152,
"truncated": 0,
"decision": "Research remains paused. Archive audit: 47/60 mixed-policy selected actions agree at384 samples versus39/60 at48;14/60 positions have opposite fixed-policy confirmation preferences. Descriptive reused-development diagnostics, not strength evidence; no new jobs or gradients."
},
"artifact_sha256": {
"2": "b24c3c463dd6735374996033eaf0d6d507abdc140730ff610ab720a317838fb9",
"3": "d4bcef77002d4a77e2019a108fb0bb245579af43dff43e8dfefa27761977e5cd",
"4": "795a431a4a9f2f3be3d95bf380e43bd7cece0caaa1d65ae1aecef3460073fc8d",
"5": "cb90571dcb3e6f31048b7ea3e2064d11af594e0a898b564d507062c1417b7e38",
"6": "8d2c85e69f4851451d76583f7a83f47b9f9e52161ee3fbcc291501dfc9116a09"
}
}

File diff suppressed because it is too large Load diff

86
ai/strong/infer.py Normal file
View file

@ -0,0 +1,86 @@
"""Persistent CPU ONNX worker for versioned public-information states."""
import sys, json, argparse, time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from infer import Model, Node
from feature_contract import check_revision, model_revision
from search_scope import SCOPES, search_enabled
p = argparse.ArgumentParser()
p.add_argument("model")
p.add_argument("--search-scope", choices=SCOPES, default="all")
p.add_argument("--search-samples", type=int, default=0)
p.add_argument("--geographic-search", action="store_true")
args = p.parse_args()
if not 0 <= args.search_samples <= 64:
p.error("--search-samples must be 0..64")
if args.geographic_search and not args.search_samples:
p.error("--geographic-search requires positive --search-samples")
model = Model(args.model)
node = Node("strong/worker.cjs")
try:
for line in sys.stdin:
q = {}
try:
obj = json.loads(line)
if not isinstance(obj, dict):
raise ValueError("Expected object")
q = obj
start = time.perf_counter()
r = node.call({**q, "op": "rank", "featureRevision": model_revision(model)})
if "error" in r:
raise ValueError(r["error"])
check_revision(model, r.get("featureRevision", "3.0"))
index, values = model.predict(r["state"], r["actions"])
search = None
if args.search_samples and search_enabled(
args.search_scope,
q["state"]["options"].get("variant"),
q["state"]["options"].get("fastBid"),
):
search = node.call(
{
**q,
"op": "search",
"proposal": index,
"samples": args.search_samples,
"featureRevision": model_revision(model),
"geography": args.geographic_search,
}
)
if "error" in search:
raise ValueError(search["error"])
index = search["index"]
print(
json.dumps(
{
"requestId": q.get("requestId"),
"revision": q.get("revision"),
"move": r["moves"][index],
"winProbabilities": values[: len(r["playerOrder"])],
"valueStatus": "uncalibrated-training-opponents",
"playerOrder": r["playerOrder"],
"schema": r["schema"],
"featureRevision": r["featureRevision"],
"search": {
k: v
for k, v in search.items()
if k in ["evaluations", "truncated", "winEstimate"]
}
if search
else None,
"modelSha256": model.sha256,
"elapsedMs": 1000 * (time.perf_counter() - start),
}
),
flush=True,
)
except Exception as e:
print(
json.dumps({"requestId": q.get("requestId"), "error": str(e)}),
flush=True,
)
finally:
node.close()

19
ai/strong/launch-a.sh Normal file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor a10g-large --timeout 3h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=strong-league-v2-a --env TRAIN_SEED=201 --env LR=.0001 --env ENTROPY=.01 --env ANCHOR=.01 --env UPDATES=300 --env EVAL_EVERY=20 \
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=strong-league-v2-a \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/train.py
'

24
ai/strong/launch-arena.sh Normal file
View file

@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
# name model-path revision opponent samples geography games seed
extra_env=()
if [[ -n "${OPPONENT_MODEL_PATH:-}" ]]; then
extra_env+=(--env "OPPONENT_MODEL_PATH=$OPPONENT_MODEL_PATH" --env "OPPONENT_MODEL_REVISION=${OPPONENT_MODEL_REVISION:?pin opponent revision}")
fi
hf jobs run --detach --flavor cpu-performance --timeout 3h \
--secrets HF_TOKEN "${extra_env[@]}" \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 --env SEARCH_SCOPE="${SEARCH_SCOPE:-all}" \
--env RUN_NAME="${1:?name}" --env MODEL_PATH="${2:?model path}" --env MODEL_REVISION="${3:?revision}" \
--env OPPONENT="${4:?opponent}" --env SEARCH_SAMPLES="${5:?samples}" --env GEOGRAPHY="${6:?geography}" \
--env GAMES="${7:?games}" --env EVAL_SEED="${8:?seed}" --env WORKERS=24 \
--label project=powergrid-ai --label stage="$1" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnxruntime==1.30.0 numpy==2.4.6
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v15.tgz\",repo_type=\"dataset\", revision=\"5346157377b6ba0c716b6bf3c7b434cc3696fb1d\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
python -u ai/strong/arena-job.py
'

19
ai/strong/launch-b.sh Normal file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor l4x1 --timeout 3h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=strong-league-v2-b --env TRAIN_SEED=202 --env LR=.0003 --env ENTROPY=.01 --env ANCHOR=.01 --env UPDATES=300 --env EVAL_EVERY=20 \
--env ENVS=128 --env WORKERS=4 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=strong-league-v2-b \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/train.py
'

19
ai/strong/launch-c.sh Normal file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor h200 --timeout 3h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=strong-league-v2-c --env TRAIN_SEED=203 --env LR=.0001 --env ENTROPY=.025 --env ANCHOR=.003 --env UPDATES=300 --env EVAL_EVERY=20 \
--env ENVS=128 --env WORKERS=12 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=strong-league-v2-c \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/train.py
'

19
ai/strong/launch-d.sh Normal file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor a10g-large --timeout 3h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=strong-league-v2-d --env TRAIN_SEED=204 --env LR=.0003 --env ENTROPY=.025 --env ANCHOR=.003 --env UPDATES=300 --env EVAL_EVERY=20 \
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=strong-league-v2-d \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v3.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/train.py
'

View file

@ -0,0 +1,21 @@
#!/usr/bin/env bash
set -euo pipefail
mode=${1:-hard}
[[ "$mode" == hard || "$mode" == soft ]]
hf jobs run --detach --flavor a10g-large --timeout 2h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME="search-distillation-v2-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=310 --env EPOCHS=20 --env DATA_VERSION=search-teacher-v2 --env SHARDS=8 --env DISAGREEMENT_WEIGHT=2 \
--label project=powergrid-ai --label stage="search-distillation-v2-$mode" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx onnxruntime
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v7.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/distill.py
'

View file

@ -0,0 +1,21 @@
#!/usr/bin/env bash
set -euo pipefail
mode=${1:-hard}
[[ "$mode" == hard || "$mode" == soft ]]
hf jobs run --detach --flavor a10g-large --timeout 2h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME="search-distillation-v3-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=310 --env EPOCHS=20 --env DATA_VERSION=search-teacher-v3 --env SHARDS=8 --env DISAGREEMENT_WEIGHT=2 \
--label project=powergrid-ai --label stage="search-distillation-v3-$mode" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx onnxruntime
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v8.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/distill.py
'

View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor a10g-large --timeout 2h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=search-distillation-v1 --env TRAIN_SEED=310 --env EPOCHS=30 \
--label project=powergrid-ai --label stage=search-distillation-v1 \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx onnxruntime
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v5.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/distill.py
'

149
ai/strong/launch-final.py Normal file
View file

@ -0,0 +1,149 @@
"""Launch or resume one frozen final evaluation plan; default is a dry run."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
p = argparse.ArgumentParser()
p.add_argument("candidate")
p.add_argument("--protocol", default="ai/strong/final-protocol.json")
p.add_argument("--launch", action="store_true")
a = p.parse_args()
root = Path(__file__).resolve().parents[2]
protocol = json.loads(Path(a.protocol).read_text())
candidate = json.loads(Path(a.candidate).read_text())
plan = []
prefix = protocol["seed_prefix"]
multiplayer = isinstance(protocol.get("scope"), dict)
launcher = (
"ai/strong/launch-multiplayer-arena.sh"
if multiplayer
else "ai/strong/launch-arena.sh"
)
for opponent in protocol["opponents"]:
counts = opponent["counts"] if multiplayer else {"3": {"games": opponent["games"]}}
for count, spec in counts.items():
n = int(count)
shard_games = 4 * n * 4
assert spec["games"] % shard_games == 0
for shard in range(spec["games"] // shard_games):
plan.append(
{
"name": f"{prefix}-{opponent['name']}-{n}p-{shard:02}"
if multiplayer
else f"{prefix}-{opponent['name']}-{shard:02}",
"seed": f"{prefix}-{n}p" if multiplayer else f"{prefix}-{shard}",
"player_count": n,
"deal_offset": shard * 4 if multiplayer else 0,
"opponent": opponent,
"games": shard_games,
}
)
print(
json.dumps(
{
"candidate": candidate,
"jobs": len(plan),
"games": sum(x["games"] for x in plan),
"launch": a.launch,
}
),
flush=True,
)
if not a.launch:
raise SystemExit(0)
if candidate.get("status") != "selected":
raise ValueError("Select and freeze the candidate before spending final seeds")
if multiplayer and candidate.get("feature_revision") != "4.0-multiplayer":
raise ValueError("Multiplayer final requires a schema-4 candidate")
from huggingface_hub import hf_hub_download
model = Path(
hf_hub_download(
"coyotte508/powergrid-ai-germany-v1",
candidate["model_path"],
revision=candidate["model_revision"],
)
)
assert hashlib.sha256(model.read_bytes()).hexdigest() == candidate["model_sha256"]
manifest_path = root / "ai/strong/experiments.json"
manifest = json.loads(manifest_path.read_text())
launcher_sha256 = hashlib.sha256((root / launcher).read_bytes()).hexdigest()
fingerprint = hashlib.sha256(
json.dumps(
{
"candidate": candidate,
"protocol": protocol,
"launcher_sha256": launcher_sha256,
},
sort_keys=True,
).encode()
).hexdigest()
run = manifest.setdefault("final_runs", {}).setdefault(
prefix,
{
"fingerprint": fingerprint,
"launcher_sha256": launcher_sha256,
"candidate": candidate,
"protocol": protocol,
"jobs": {},
},
)
if run["fingerprint"] != fingerprint:
raise ValueError(
"Final seeds were already assigned to a different candidate or protocol"
)
manifest["final_seed_prefix_used"] = True
manifest_path.write_text(json.dumps(manifest, indent=4) + "\n")
for item in plan:
if item["name"] in run["jobs"]:
print("Already dispatched", item["name"], run["jobs"][item["name"]], flush=True)
continue
opponent = item["opponent"]
env = os.environ.copy()
env.pop("OPPONENT_MODEL_PATH", None)
env.pop("OPPONENT_MODEL_REVISION", None)
env["SEARCH_SCOPE"] = candidate.get("search_scope", "all")
env["DISABLE_SEARCH_PROPOSAL"] = "0"
if multiplayer:
env["ASYNC_ARENA"] = "1"
env["PLAYER_COUNT"] = str(item["player_count"])
env["DEAL_OFFSET"] = str(item["deal_offset"])
if "model_path" in opponent:
env.update(
OPPONENT_MODEL_PATH=opponent["model_path"],
OPPONENT_MODEL_REVISION=opponent["model_revision"],
)
result = subprocess.run(
[
"bash",
launcher,
item["name"],
candidate["model_path"],
candidate["model_revision"],
"economic" if "model_path" in opponent else opponent["name"],
str(candidate["search_samples"]),
str(int(candidate["geographic_search"])),
str(item["games"]),
item["seed"],
],
cwd=root,
env=env,
capture_output=True,
text=True,
check=True,
)
ids = re.findall(r"\b[0-9a-f]{24}\b", result.stdout)
if not ids:
raise RuntimeError(
"Launch response was ambiguous; inspect HF job labels before retrying: "
+ result.stdout
)
run["jobs"][item["name"]] = ids[-1]
manifest["jobs"][item["name"]] = ids[-1]
manifest_path.write_text(json.dumps(manifest, indent=4) + "\n")
print(item["name"], ids[-1], flush=True)

View file

@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor cpu-performance --timeout 2h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--label project=powergrid-ai --label stage=b160-guided-16-screening \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnxruntime
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(\"coyotte508/powergrid-ai-germany-v1\",\"runs/strong-league-v2-b/best.onnx\",revision=\"55e2354f08c8088edd1f6634e1bb7d903dbfaf94\",local_dir=\"models\")"
python ai/strong/evaluate.py models/runs/strong-league-v2-b/best.onnx --opponent search --search-samples 16 --games 96 --workers 24 --seed strong-search-screening-v1 --output evaluation.json
python -c "import os;from huggingface_hub import HfApi;HfApi().upload_file(repo_id=os.environ[\"HF_MODEL_REPO\"],path_or_fileobj=\"evaluation.json\",path_in_repo=\"runs/b160-guided-16-screening/evaluation.json\")"
'

View file

@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor cpu-performance --timeout 2h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--label project=powergrid-ai --label stage=b160-guided-48-screening \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnxruntime
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(\"coyotte508/powergrid-ai-germany-v1\",\"runs/strong-league-v2-b/best.onnx\",revision=\"55e2354f08c8088edd1f6634e1bb7d903dbfaf94\",local_dir=\"models\")"
python ai/strong/evaluate.py models/runs/strong-league-v2-b/best.onnx --opponent search --search-samples 48 --games 96 --workers 24 --seed strong-search-screening-v1 --output evaluation.json
python -c "import os;from huggingface_hub import HfApi;HfApi().upload_file(repo_id=os.environ[\"HF_MODEL_REPO\"],path_or_fileobj=\"evaluation.json\",path_in_repo=\"runs/b160-guided-48-screening/evaluation.json\")"
'

View file

@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor cpu-performance --timeout 2h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--label project=powergrid-ai --label stage=b20-guided-search-screening \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnxruntime
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(\"coyotte508/powergrid-ai-germany-v1\",\"runs/strong-league-v2-b/best.onnx\",revision=\"f9dfad5bde9862bc41aa42d77d9622621d70e8ce\",local_dir=\"models\")"
python ai/strong/evaluate.py models/runs/strong-league-v2-b/best.onnx --opponent search --search-samples 16 --games 96 --workers 24 --seed strong-search-screening-v1 --output evaluation.json
python -c "import os;from huggingface_hub import HfApi;HfApi().upload_file(repo_id=os.environ[\"HF_MODEL_REPO\"],path_or_fileobj=\"evaluation.json\",path_in_repo=\"runs/b20-guided-search-screening/evaluation.json\")"
'

View file

@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Controlled league-admission comparison; optimization runs only on HF Jobs.
set -euo pipefail
checkpoint=${1:?Supply selected ordered-model checkpoint path}
revision=${2:?Pin its immutable model repository commit}
run=${3:?Supply a unique refinement run name}
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
[[ "$checkpoint" == runs/*/best.pt ]]
[[ "$run" =~ ^[a-zA-Z0-9_-]+$ ]]
admission=${SNAPSHOT_ADMISSION:?Choose best or periodic_anchor}
[[ "$admission" == best || "$admission" == periodic_anchor ]]
hf jobs run --detach --flavor "${HF_FLAVOR:-cpu-performance}" --timeout "${JOB_TIMEOUT:-8h}" \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env INIT_CHECKPOINT="$checkpoint" --env INIT_REVISION="$revision" --env ANCHOR_POLICY=initial \
--env ARCHITECTURE=multiplayer_ordered --env MIX_PLAYER_COUNTS=1 --env OPPONENT_MODE="${OPPONENT_MODE:-mixed_search_geo}" \
--env RUN_NAME="$run" --env TRAIN_SEED="${TRAIN_SEED:-9021}" \
--env ASYNC_ROLLOUT="${ASYNC_ROLLOUT:-1}" --env TRAIN_DEVICE="${TRAIN_DEVICE:-cpu}" --env TORCH_THREADS="${TORCH_THREADS:-4}" \
--env SNAPSHOT_ADMISSION="$admission" --env SNAPSHOT_INTERVAL=5 \
--env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 \
--env UPDATES="${UPDATES:-20}" --env EVAL_EVERY=10 \
--env ENVS=240 --env WORKERS="${WORKERS:-240}" --env BATCH_SIZE=512 \
--label project=powergrid-ai --label stage="$run" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v34.tgz\",repo_type=\"dataset\",revision=\"2c273f96562d0cc2f8c05a2735d8c0492ab77fd8\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python ai/strong/test_teacher_contract.py
python ai/strong/test_model_v4.py
python ai/strong/test_snapshot_league.py
python ai/strong/test_multiplayer_bridge.py
python ai/strong/test_async_pool.py
python -u ai/strong/train.py
'

View file

@ -0,0 +1,35 @@
#!/usr/bin/env bash
set -euo pipefail
# name model-path revision opponent samples geography games seed
case "${4:?opponent}" in
economic|heuristic|rush|legacy|search|search_geo) ;;
*) echo "Unsupported opponent mode; use OPPONENT_MODEL_PATH for a frozen model" >&2; exit 2 ;;
esac
if [[ "${6:?geography}" == 1 ]] && ! [[ "${5:?samples}" =~ ^[1-9][0-9]*$ ]]; then
echo "Candidate geographic search requires a positive sample budget; opponent search_geo is configured separately" >&2
exit 2
fi
extra_env=()
if [[ -n "${OPPONENT_MODEL_PATH:-}" ]]; then
extra_env+=(--env "OPPONENT_MODEL_PATH=$OPPONENT_MODEL_PATH" --env "OPPONENT_MODEL_REVISION=${OPPONENT_MODEL_REVISION:?pin opponent revision}")
fi
hf jobs run --detach --flavor cpu-performance --timeout 3h \
--secrets HF_TOKEN "${extra_env[@]}" \
--env ASYNC_ARENA="${ASYNC_ARENA:-1}" \
--env DISABLE_SEARCH_PROPOSAL="${DISABLE_SEARCH_PROPOSAL:-0}" \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 --env SEARCH_SCOPE="${SEARCH_SCOPE:-all}" \
--env RUN_NAME="${1:?name}" --env MODEL_PATH="${2:?model path}" --env MODEL_REVISION="${3:?revision}" \
--env OPPONENT="${4:?opponent}" --env SEARCH_SAMPLES="${5:?samples}" --env GEOGRAPHY="${6:?geography}" \
--env PLAYER_COUNT="${PLAYER_COUNT:?Specify player count}" --env DEAL_OFFSET="${DEAL_OFFSET:-0}" \
--env GAMES="${7:?games}" --env EVAL_SEED="${8:?seed}" --env WORKERS=24 \
--label project=powergrid-ai --label stage="$1" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnxruntime==1.30.0 numpy==2.4.6
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v32.tgz\",repo_type=\"dataset\", revision=\"37465b08df007221665d796448aea57e6828257e\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
python -u ai/strong/arena-job.py
'

View file

@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
revision=${1:?Pin completed dataset revision}
mode=${2:-soft}
[[ "$mode" == hard || "$mode" == soft ]]
hf jobs run --detach --flavor "${HF_FLAVOR:-a10g-large}" --timeout 3h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME="multiplayer-distillation-v2-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=622 --env ARCHITECTURE=multiplayer_ordered --env DATA_REVISION="$revision" --env EPOCHS=20 --env DATA_VERSION=multiplayer-teacher-v1 --env SHARDS=5 --env DISAGREEMENT_WEIGHT=2 \
--label project=powergrid-ai --label stage="multiplayer-distillation-v2-$mode" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v20.tgz\",repo_type=\"dataset\",revision=\"c259cc1664fe39565bdbdd5d64789c9825a62692\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python ai/strong/test_teacher_contract.py
python ai/strong/test_model_v4.py
python -u ai/strong/distill.py
'

View file

@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
revision=${1:?Pin completed dataset revision}
mode=${2:-soft}
[[ "$mode" == hard || "$mode" == soft ]]
hf jobs run --detach --flavor "${HF_FLAVOR:-a10g-large}" --timeout 3h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME="multiplayer-distillation-v1-$mode" --env TARGET_MODE="$mode" --env TRAIN_SEED=622 --env ARCHITECTURE=multiplayer --env DATA_REVISION="$revision" --env EPOCHS=20 --env DATA_VERSION=multiplayer-teacher-v1 --env SHARDS=5 --env DISAGREEMENT_WEIGHT=2 \
--label project=powergrid-ai --label stage="multiplayer-distillation-v1-$mode" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v18.tgz\",repo_type=\"dataset\",revision=\"49cc1bb94678e6ede37b606ae1ce9a8cb2018c1d\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python ai/strong/test_teacher_contract.py
python ai/strong/test_model_v4.py
python -u ai/strong/distill.py
'

View file

@ -0,0 +1,21 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor a10g-large --timeout 3h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=multiplayer-pipeline-v1 --env TRAIN_SEED=621 --env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 --env UPDATES=10 --env EVAL_EVERY=5 --env ARCHITECTURE=multiplayer --env OPPONENT_MODE=mixed_search \
--env ENVS=120 --env WORKERS=10 --env BATCH_SIZE=512 \
--label project=powergrid-ai --label stage=multiplayer-pipeline-v1 \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v16.tgz\",repo_type=\"dataset\",revision=\"6064b1683379153e0a5dbca24903d41a972cbe0a\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs ai/strong/test-v4.cjs
python ai/strong/test_model_v4.py
python ai/strong/test_multiplayer_bridge.py
python -u ai/strong/train.py
'

View file

@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Warm-start balanced 2–6 player PPO after independent teacher-model screening.
set -euo pipefail
checkpoint=${1:?Supply selected ordered-model checkpoint path}
revision=${2:?Pin its immutable model repository commit}
run=${3:?Supply a unique refinement run name}
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
[[ "$checkpoint" == runs/*/best.pt ]]
[[ "$run" =~ ^[a-zA-Z0-9_-]+$ ]]
hf jobs run --detach --flavor "${HF_FLAVOR:-h200}" --timeout "${JOB_TIMEOUT:-12h}" \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env INIT_CHECKPOINT="$checkpoint" --env INIT_REVISION="$revision" --env ANCHOR_POLICY=initial \
--env ARCHITECTURE=multiplayer_ordered --env MIX_PLAYER_COUNTS=1 --env OPPONENT_MODE="${OPPONENT_MODE:-mixed_search}" \
--env RUN_NAME="$run" --env TRAIN_SEED="${TRAIN_SEED:-623}" \
--env ASYNC_ROLLOUT="${ASYNC_ROLLOUT:-0}" --env TRAIN_DEVICE="${TRAIN_DEVICE:-cuda}" --env TORCH_THREADS="${TORCH_THREADS:-2}" \
--env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 \
--env UPDATES="${UPDATES:-80}" --env EVAL_EVERY=10 \
--env ENVS=240 --env WORKERS="${WORKERS:-16}" --env BATCH_SIZE=512 \
--label project=powergrid-ai --label stage="$run" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0 onnx==1.20.1 onnxruntime==1.30.0
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v26.tgz\",repo_type=\"dataset\",revision=\"80fcc719b64b13fe1592e206712b68f94ef19951\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python ai/strong/test_teacher_contract.py
python ai/strong/test_model_v4.py
python ai/strong/test_multiplayer_bridge.py
python ai/strong/test_async_pool.py
python -u ai/strong/train.py
'

View file

@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euo pipefail
players=${1:?Specify player count 2–6}
[[ "$players" =~ ^[2-6]$ ]]
shard=$((players - 2))
[[ "$shard" =~ ^[0-9]+$ ]]
hf jobs run --detach --flavor cpu-performance --timeout 3h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env SHARD="$shard" --env GAMES=240 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=16 --env GEOGRAPHY=1 --env FEATURE_REVISION=4.0-multiplayer --env PLAYER_COUNT="$players" --env DATA_VERSION=multiplayer-teacher-v1 --env INCLUDE_ALL_PHASES=1 \
--label project=powergrid-ai --label stage="multiplayer-teacher-v1-$shard" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet --timeout 120 --retries 5 huggingface_hub==2.0.0
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v17.tgz\",repo_type=\"dataset\",revision=\"36c3d6b2f8545bd3551fc571a8cb6cb45a8f88b1\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/generate-search-data.py
'

View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor l4x4 --timeout 3h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env RUN_NAME=strong-league-v1 --env UPDATES=300 --env EVAL_EVERY=20 \
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 --env ROLLOUT_SAMPLES=8000 \
--label project=powergrid-ai --label stage=strong-league-v1 \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v2.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/population.py
'

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor a10g-large --timeout 4h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env INIT_CHECKPOINT=runs/strong-league-v2-a/best.pt --env INIT_REVISION=b38515c29e57826de05b55b645c29591e4a886bf --env ANCHOR_POLICY=initial --env ALLOW_URANIUM39_TRANSFER=1 \
--env RUN_NAME=strong-refine-a260-v1 --env TRAIN_SEED=412 --env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.03 --env UPDATES=80 --env EVAL_EVERY=10 \
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 \
--label project=powergrid-ai --label stage=strong-refine-a260-v1 \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v12.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/train.py
'

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor a10g-large --timeout 4h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env INIT_CHECKPOINT=runs/search-distillation-v3-soft/best.pt --env INIT_REVISION=45a839c001fce2fe3dd9b1f5c7a523db8ceee890 --env ANCHOR_POLICY=initial \
--env RUN_NAME=strong-refine-v1-full --env TRAIN_SEED=410 --env LR=.0001 --env ENTROPY=.005 --env ANCHOR=.03 --env UPDATES=120 --env EVAL_EVERY=10 \
--env ENVS=128 --env WORKERS=8 --env BATCH_SIZE=512 \
--label project=powergrid-ai --label stage=strong-refine-v1-full \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v10.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/train.py
'

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
hf jobs run --detach --flavor h200 --timeout 4h \
--secrets HF_TOKEN \
--env HF_MODEL_REPO=coyotte508/powergrid-ai-germany-v1 \
--env INIT_CHECKPOINT=runs/search-distillation-v3-soft/best.pt --env INIT_REVISION=45a839c001fce2fe3dd9b1f5c7a523db8ceee890 --env ANCHOR_POLICY=initial --env OPPONENT_MODE=mixed_search --env STRATEGIC_ONLY=1 \
--env RUN_NAME=strong-refine-v1-search --env TRAIN_SEED=411 --env LR=.00005 --env ENTROPY=.005 --env ANCHOR=.05 --env UPDATES=80 --env EVAL_EVERY=10 \
--env ENVS=128 --env WORKERS=20 --env BATCH_SIZE=512 \
--label project=powergrid-ai --label stage=strong-refine-v1-search \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub onnx
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v10.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/train.py
'

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
shard=${1:?Specify numeric shard}
[[ "$shard" =~ ^[0-9]+$ ]]
hf jobs run --detach --flavor cpu-performance --timeout 2h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env SHARD="$shard" --env GAMES=256 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=12 --env DATA_VERSION=search-teacher-v2 --env INCLUDE_ALL_PHASES=1 \
--label project=powergrid-ai --label stage="search-teacher-v2-$shard" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v6.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/generate-search-data.py
'

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
shard=${1:?Specify numeric shard}
[[ "$shard" =~ ^[0-9]+$ ]]
hf jobs run --detach --flavor cpu-performance --timeout 2h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env SHARD="$shard" --env GAMES=256 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=12 --env DATA_VERSION=search-teacher-v3 --env INCLUDE_ALL_PHASES=1 \
--label project=powergrid-ai --label stage="search-teacher-v3-$shard" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v8.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/generate-search-data.py
'

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
shard=${1:?Specify numeric shard}
[[ "$shard" =~ ^[0-9]+$ ]]
hf jobs run --detach --flavor cpu-performance --timeout 2h \
--secrets HF_TOKEN \
--env HF_DATA_REPO=coyotte508/powergrid-ai-training-v1 \
--env SHARD="$shard" --env GAMES=128 --env DATA_WORKERS=24 --env SEARCH_SAMPLES=4 \
--label project=powergrid-ai --label stage="search-teacher-v1-$shard" \
-- pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime bash -lc '
set -euo pipefail
python -m pip install --quiet huggingface_hub
mkdir -p /workspace
python -c "import urllib.request,tarfile; urllib.request.urlretrieve(\"https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz\",\"/tmp/node.tar.xz\");tarfile.open(\"/tmp/node.tar.xz\").extractall(\"/opt\")"
export PATH=/opt/node-v24.14.0-linux-x64/bin:$PATH
python -c "from huggingface_hub import hf_hub_download;import tarfile;p=hf_hub_download(\"coyotte508/powergrid-ai-training-v1\",\"strong-source-v4.tgz\",repo_type=\"dataset\");tarfile.open(p).extractall(\"/workspace\")"
cd /workspace
node --test ai/test.cjs ai/strong/test.cjs
python -u ai/strong/generate-search-data.py
'

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