From 49fc40dc40464be426f97312548d11f548a96dd0 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Tue, 8 Sep 2026 10:03:24 +0200 Subject: [PATCH] feat(engine): simultaneous sealed bidding - any order, hidden until all in (BGS contract) - engine.sealedBidPendingSeats(): seats still owing a bid (undefined outside bid phases) - move()/loadTurnMoves: accept silentBid/preferenceBid from ANY pending seat regardless of playerToMove (was: strict turn-order assert -> 'not your turn to play' for off-turn bidders) - bid phases resolve on the LAST pending bid, not on the sequential turn walk - move() attributes the log line to the actual bidder, not playerToMove - wrapper.currentPlayer() returns number[] of pending seats during bid phases (the platform's /move route authorizes any seat in game.currentPlayers, which it fills from currentPlayer()) - deterministic auction tiebreaks (last faction-nominator wins) replace the seeded PRNG, so the resolution no longer needs map.rng - which crashed hosted simultaneous bidding on a reloaded engine ('map.rng is not a function'); bids + nominations alone now reproduce the result - viewer: SealedBidPanel drops the waiting-for-turn gate (every pending seat bids at once) and seat-prefixes the emitted move so the engine can parse the bidder engine 4.12.0, viewer 5.16.0 --- engine/package.json | 2 +- .../preference-split-auction.spec.ts | 129 ++++++++---------- .../algorithms/preference-split-auction.ts | 55 ++++---- engine/src/algorithms/silent-auction.spec.ts | 9 +- engine/src/algorithms/silent-auction.ts | 23 +++- engine/src/engine.ts | 85 ++++++++++-- engine/src/move/phase.ts | 20 ++- .../src/silent-auction-simultaneous.spec.ts | 90 ++++++++++++ engine/wrapper.ts | 18 ++- viewer/package.json | 2 +- .../src/components/PreferenceSplitBid.spec.ts | 5 +- viewer/src/components/SealedBidPanel.ts | 32 +++-- .../src/components/SilentAuctionBid.spec.ts | 20 ++- viewer/vitest.setup.ts | 25 ++++ 14 files changed, 370 insertions(+), 145 deletions(-) create mode 100644 engine/src/silent-auction-simultaneous.spec.ts diff --git a/engine/package.json b/engine/package.json index fbd5e01f..1862bfdb 100644 --- a/engine/package.json +++ b/engine/package.json @@ -1,6 +1,6 @@ { "name": "@gaia-project/engine", - "version": "4.11.1", + "version": "4.12.0", "description": "Javascript engine for project gaia", "main": "dist/index.js", "types": "index.ts", diff --git a/engine/src/algorithms/preference-split-auction.spec.ts b/engine/src/algorithms/preference-split-auction.spec.ts index fac8fe78..ea7ea3c6 100644 --- a/engine/src/algorithms/preference-split-auction.spec.ts +++ b/engine/src/algorithms/preference-split-auction.spec.ts @@ -23,15 +23,14 @@ function bidsFrom(vectors: number[][], factions = FACTIONS): PreferenceSplitBid[ return bids; } -/** A deterministic stand-in for the engine's seeded PRNG - cycles through the given values. */ -function seededRandom(values: number[]): () => number { - let i = 0; - return () => values[i++ % values.length]; -} +/** The fixture convention: PLAYERS[i] nominated FACTIONS[i] in the pick round (Player1 -> Itars, + * Player2 -> Taklons, Player3 -> Xenos, Player4 -> Gleens). Both tiebreaks resolve off this - + * deterministically, latest nominator first. */ +const NOMINATED: Map = new Map(PLAYERS.map((p, i) => [p, FACTIONS[i]] as [PlayerEnum, Faction])); /** * The required end-to-end fixture, adapted to this project's factions. Every faction totals 40, so - * the whole faction ranking is a four-way tie that has to be broken at random. + * the whole faction ranking is a four-way tie broken by nomination order. */ const ALL_TIED = [ [20, 12, 6, 2], @@ -143,7 +142,7 @@ describe("Preference Split Auction", () => { describe("resolution", () => { it("ranks factions by their total bid, highest first", () => { - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, NOMINATED); expect(result.order).to.deep.equal([Faction.Gleens, Faction.Itars, Faction.Taklons, Faction.Xenos]); expect(result.factions.map((f) => f.total)).to.deep.equal([51, 38, 36, 35]); @@ -153,7 +152,7 @@ describe("Preference Split Auction", () => { }); it("awards each faction to the highest bidder who is still unassigned", () => { - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, NOMINATED); // Gleens (rank 1): p4 bid 25, the highest of all four. // Itars (rank 2): p1 bid 20, highest among the three still in the running. @@ -168,7 +167,7 @@ describe("Preference Split Auction", () => { }); it("excludes already-assigned players from later allocations", () => { - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, NOMINATED); expect(result.allocations.map((a) => a.eligible.length)).to.deep.equal([4, 3, 2, 1]); // p4 took Gleens first and is gone from every later pool, even though their 11 on Xenos was @@ -178,7 +177,7 @@ describe("Preference Split Auction", () => { }); it("keeps assigned players' original bids in every faction's total and average", () => { - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, NOMINATED); // Xenos is awarded last, when only p3 remains - but its average still divides all four // original bids (6 + 8 + 10 + 11 = 35) by four, not just p3's own. @@ -190,7 +189,7 @@ describe("Preference Split Auction", () => { }); it("charges the faction average, whatever the winner bid themselves", () => { - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, NOMINATED); const gleens = result.allocations[0]; expect(gleens.winnerBid).to.equal(25); @@ -212,7 +211,7 @@ describe("Preference Split Auction", () => { [4, 12, 22, 2], [6, 4, 16, 14], ]; - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(overBid), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(overBid), 40, NOMINATED); const itars = result.allocations.find((a) => a.faction === Faction.Itars); expect(itars.winner).to.equal(PlayerEnum.Player4); @@ -231,7 +230,7 @@ describe("Preference Split Auction", () => { [5, 5, 25, 5], [21, 19, 0, 0], ]; - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(zeroBid), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(zeroBid), 40, NOMINATED); const last = result.allocations[result.allocations.length - 1]; expect(last.faction).to.equal(Faction.Gleens); @@ -256,7 +255,7 @@ describe("Preference Split Auction", () => { [1, 2, 20, 17], [2, 3, 16, 19], ]; - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(nearTie), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(nearTie), 40, NOMINATED); const taklons = result.allocations.find((a) => a.faction === Faction.Taklons); expect(taklons.winner).to.equal(PlayerEnum.Player1); @@ -268,23 +267,22 @@ describe("Preference Split Auction", () => { expect(itars.payment).to.equal(6); }); - it("breaks a faction-total tie at random and records who was tied", () => { + it("breaks a faction-total tie by nomination order (latest nominator first) and records who was tied", () => { const bids = bidsFrom(ALL_TIED); - // Every faction totals 40, so the four-way tie is decided entirely by the random source. - const first = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, seededRandom([0.99, 0.99, 0.99])); - const second = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, seededRandom([0, 0, 0])); + // Every faction totals 40, so the four-way tie is decided entirely by nomination order: the + // faction nominated LATEST in setup order (highest FACTIONS index) ranks first, so the + // resolved ranking is exactly the reverse of FACTIONS. + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, NOMINATED); - expect(first.factions.map((f) => f.total)).to.deep.equal([40, 40, 40, 40]); - expect([...first.order].sort()).to.deep.equal([...FACTIONS].sort()); - expect(first.factions.every((f) => f.tiedWith.length === 3)).to.equal(true); - expect(first.order).to.not.deep.equal(second.order); - // Same random source -> same order, every time. - expect(resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, seededRandom([0, 0, 0])).order).to.deep.equal( - second.order - ); + expect(result.factions.map((f) => f.total)).to.deep.equal([40, 40, 40, 40]); + expect(result.order).to.deep.equal([Faction.Gleens, Faction.Xenos, Faction.Taklons, Faction.Itars]); + expect(result.factions.map((f) => f.rank)).to.deep.equal([1, 2, 3, 4]); + expect(result.factions.every((f) => f.tiedWith.length === 3)).to.equal(true); + // Deterministic: the same bids always produce exactly this order. + expect(resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, NOMINATED).order).to.deep.equal(result.order); }); - it("breaks a player tie at random among only the tied eligible players", () => { + it("breaks a player tie by nomination order (latest nominator wins), among only the tied eligible players", () => { // p1 and p2 both bid 20 on Itars, which is also the top-ranked faction (total 44). const playerTie = [ [20, 12, 6, 2], @@ -293,30 +291,19 @@ describe("Preference Split Auction", () => { [2, 4, 9, 25], ]; const bids = bidsFrom(playerTie); - const toP1 = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, seededRandom([0])); - const toP2 = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, seededRandom([0.99])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, NOMINATED); - const itarsA = toP1.allocations.find((a) => a.faction === Faction.Itars); - const itarsB = toP2.allocations.find((a) => a.faction === Faction.Itars); - expect(itarsA.tiedPlayers).to.deep.equal([PlayerEnum.Player1, PlayerEnum.Player2]); - expect(itarsA.winner).to.equal(PlayerEnum.Player1); - expect(itarsB.winner).to.equal(PlayerEnum.Player2); - // Total points bid across all factions is identical for everyone (that's the whole point of a - // fixed budget), so it is never used to separate them. - expect(itarsA.tiedPlayers).to.deep.equal(itarsB.tiedPlayers); + const itars = result.allocations.find((a) => a.faction === Faction.Itars); + expect(itars.tiedPlayers).to.deep.equal([PlayerEnum.Player1, PlayerEnum.Player2]); + // p1 nominated Itars (index 0), p2 nominated Taklons (index 1) - the later nominator wins. + expect(itars.winner).to.equal(PlayerEnum.Player2); // Untied allocations record no tiebreak at all. - expect(toP1.allocations.filter((a) => a.tiedPlayers.length > 0)).to.have.length(1); + expect(result.allocations.filter((a) => a.tiedPlayers.length > 0)).to.have.length(1); }); it("gives every player exactly one faction and every faction exactly one winner", () => { for (const vectors of [NO_TIES, ALL_TIED]) { - const result = resolvePreferenceSplitAuction( - FACTIONS, - PLAYERS, - bidsFrom(vectors), - 40, - seededRandom([0.1, 0.7, 0.3, 0.9]) - ); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(vectors), 40, NOMINATED); expect([...new Set(result.allocations.map((a) => a.winner))]).to.have.length(4); expect([...new Set(result.allocations.map((a) => a.faction))]).to.have.length(4); expect(result.allocations).to.have.length(4); @@ -325,7 +312,7 @@ describe("Preference Split Auction", () => { it("rounds every payment with the same half-up rule", () => { // Totals 38/36/35/51 -> averages 9.5, 9, 8.75, 12.75, none of them whole. - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, seededRandom([0])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, NOMINATED); for (const allocation of result.allocations) { expect(allocation.payment).to.equal(roundVictoryPoints(Math.min(allocation.basePrice, allocation.winnerBid))); @@ -334,19 +321,18 @@ describe("Preference Split Auction", () => { expect(result.allocations.map((a) => a.payment)).to.deep.equal([13, 10, 9, 9]); }); - it("is fully determined by the bids once the random source is fixed", () => { + it("is fully determined by the bids alone - no random source at all", () => { const bids = bidsFrom(ALL_TIED); - const random = () => 0.42; - const a = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, random); - const b = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, random); + const a = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, NOMINATED); + const b = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, NOMINATED); expect(JSON.stringify(a)).to.equal(JSON.stringify(b)); }); describe("end-to-end: the four-way-tied fixture", () => { - // Not asserting a particular random order - only that whatever order comes out is internally - // consistent, which is what the rules actually promise here. + // The tie resolves deterministically now - this pins the internal consistency the rules + // promise, not the order itself (the dedicated tiebreak test above does that). const bids = bidsFrom(ALL_TIED); - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, seededRandom([0.3, 0.8, 0.1, 0.6])); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bids, 40, NOMINATED); it("contains all four factions exactly once in the resolved order", () => { expect([...result.order].sort()).to.deep.equal([...FACTIONS].sort()); @@ -384,9 +370,7 @@ describe("Preference Split Auction", () => { describe("end-to-end: the deterministic fixture", () => { it("produces exactly this allocation and these payments", () => { - const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, () => { - throw new Error("no tie should ever need the random source here"); - }); + const result = resolvePreferenceSplitAuction(FACTIONS, PLAYERS, bidsFrom(NO_TIES), 40, NOMINATED); expect( result.allocations.map((a) => ({ @@ -449,7 +433,13 @@ describe("Preference Split Auction", () => { ], factions ); - const result = resolvePreferenceSplitAuction(factions, players, bids, 30, seededRandom([0])); + const result = resolvePreferenceSplitAuction( + factions, + players, + bids, + 30, + new Map(players.map((p, i) => [p, factions[i]] as [PlayerEnum, Faction])) + ); expect(result.order).to.deep.equal([Faction.Xenos, Faction.Taklons, Faction.Itars]); expect(result.factions.map((f) => f.average)).to.deep.equal([11, 10, 9]); @@ -463,9 +453,9 @@ describe("Preference Split Auction", () => { it("resolves a two-player auction, where each player simply takes the one they rated higher", () => { const factions = FACTIONS.slice(0, 2); const players = PLAYERS.slice(0, 2); - // itars 14+6 = 20 (avg 10), taklons 6+14 = 20 (avg 10) - a total tie, so the order is random, - // but at two players the order cannot change who gets what: whoever bid more on one bid less - // on the other. + // itars 14+6 = 20 (avg 10), taklons 6+14 = 20 (avg 10) - a total tie, so the order comes + // from the nomination-order tiebreak, but at two players the order cannot change who gets + // what: whoever bid more on one bid less on the other. const bids = bidsFrom( [ [14, 6], @@ -473,15 +463,14 @@ describe("Preference Split Auction", () => { ], factions ); - for (const random of [seededRandom([0]), seededRandom([0.99])]) { - const result = resolvePreferenceSplitAuction(factions, players, bids, 20, random); - const itars = result.allocations.find((a) => a.faction === Faction.Itars); - const taklons = result.allocations.find((a) => a.faction === Faction.Taklons); - expect(itars.winner).to.equal(PlayerEnum.Player1); - expect(taklons.winner).to.equal(PlayerEnum.Player2); - expect(itars.payment).to.equal(10); - expect(taklons.payment).to.equal(10); - } + const nominated = new Map(players.map((p, i) => [p, factions[i]] as [PlayerEnum, Faction])); + const result = resolvePreferenceSplitAuction(factions, players, bids, 20, nominated); + const itars = result.allocations.find((a) => a.faction === Faction.Itars); + const taklons = result.allocations.find((a) => a.faction === Faction.Taklons); + expect(itars.winner).to.equal(PlayerEnum.Player1); + expect(taklons.winner).to.equal(PlayerEnum.Player2); + expect(itars.payment).to.equal(10); + expect(taklons.payment).to.equal(10); }); it("always bills the table exactly the budget, whatever the player count", () => { @@ -516,7 +505,7 @@ describe("Preference Split Auction", () => { players, bidsFrom(vectors, factions), budget, - seededRandom([0]) + new Map(players.map((p, i) => [p, factions[i]] as [PlayerEnum, Faction])) ); const exact = result.allocations.reduce((sum, a) => sum + a.basePrice, 0); expect(exact).to.equal(budget); diff --git a/engine/src/algorithms/preference-split-auction.ts b/engine/src/algorithms/preference-split-auction.ts index db228843..5975967b 100644 --- a/engine/src/algorithms/preference-split-auction.ts +++ b/engine/src/algorithms/preference-split-auction.ts @@ -13,11 +13,12 @@ import assert from "../utils/assert"; * 1. Each faction's `total` is the sum of EVERY original bid on it, and its `average` is that * total divided by the number of players. Both are computed once, from the original bids, and * are never recomputed as players drop out of the running. - * 2. Factions are ranked by `total`, highest first. Factions on an equal total are ordered - * randomly (recorded in `tiedWith`). + * 2. Factions are ranked by `total`, highest first. Factions on an equal total are ordered by + * nomination order, LATEST first (recorded in `tiedWith`). * 3. Working down that ranking, each faction goes to whichever still-unassigned player bid the - * most on it. Players on an equal highest bid are separated randomly (recorded in - * `tiedPlayers`). A player who wins a faction is out of the running for the rest. + * most on it. Players on an equal highest bid are separated by NOMINATION ORDER - the player who + * nominated LATEST wins (recorded in `tiedPlayers`). A player who wins a faction is out of the + * running for the rest. * 4. The winner pays the faction's `average`, rounded to a whole VP. **Always the average, whatever * they bid themselves** - their own bid decides which faction they get, never what it costs. * @@ -34,8 +35,11 @@ import assert from "../utils/assert"; * tied to what it is actually worth to the table. The accepted cost is that a winner can pay more * than they personally bid; in exchange the rule is one sentence long. * - * The only randomness is the two tiebreaks. Pass a seeded `random` (the engine passes the game's - * own seeded PRNG) and the whole resolution is reproducible from the submitted bids alone. + * Both tiebreaks are DETERMINISTIC (owner decision, 2026-09): on a tie, the LATER nominator wins - + * the last faction-picker picks a booster first (setup booster order is reverse nomination order) + * and the owner ruled they win auction ties. No PRNG - the resolution is reproducible from the + * submitted bids alone, with nothing to persist or reseed across a server round-trip (the old + * seeded-`random` tiebreak is what crashed hosted simultaneous bidding on a reloaded engine). */ /** Fewest players the variant makes sense for. Nothing above this is count-specific: the auction @@ -180,27 +184,12 @@ export function preferenceSplitBidError( return null; } -/** Fisher-Yates over a copy, driven by the supplied (seeded) random source. */ -function shuffled(items: T[], random: () => number): T[] { - const result = [...items]; - for (let i = result.length - 1; i > 0; i--) { - const j = pick(i + 1, random); - [result[i], result[j]] = [result[j], result[i]]; - } - return result; -} - -/** A uniform index in [0, count), guarded against a random source that can return exactly 1. */ -function pick(count: number, random: () => number): number { - return Math.min(count - 1, Math.max(0, Math.floor(random() * count))); -} - export function resolvePreferenceSplitAuction( factions: Faction[], players: PlayerEnum[], bids: PreferenceSplitBid[], budget: number, - random: () => number = Math.random + nominatedFaction: Map ): PreferenceSplitResult { assert( players.length >= MIN_PREFERENCE_SPLIT_PLAYERS, @@ -250,9 +239,14 @@ export function resolvePreferenceSplitAuction( }; }); - // Ranking: highest total first. `sort` is stable, so factions sharing a total arrive here in - // their `factions` order and the shuffle below is the ONLY thing that decides between them. - const byTotal = [...summaries].sort((a, b) => b.total - a.total); + // Ranking: highest total first. `sort` is stable, so factions sharing a total keep their + // `factions` (nomination) order. Deterministic tiebreak (no PRNG): the LATER-nominated faction + // ranks higher - the last faction-picker picks a booster first (booster order is reverse + // nomination order) and, per the owner's ruling, wins auction ties. So within a tied group, + // reverse the nomination order so the latest nominee resolves first. + const byTotal = [...summaries].sort( + (a, b) => b.total - a.total || factions.indexOf(b.faction) - factions.indexOf(a.faction) + ); const ordered: PreferenceSplitFactionSummary[] = []; for (let i = 0; i < byTotal.length;) { let j = i; @@ -265,10 +259,8 @@ export function resolvePreferenceSplitAuction( for (const summary of group) { summary.tiedWith = tied.filter((faction) => faction !== summary.faction); } - ordered.push(...shuffled(group, random)); - } else { - ordered.push(...group); } + ordered.push(...group); // already in deterministic setup order i = j; } ordered.forEach((summary, index) => { @@ -280,7 +272,12 @@ export function resolvePreferenceSplitAuction( const eligible = [...remaining]; const highest = Math.max(...eligible.map((player) => bidOf(player, summary.faction))); const tiedPlayers = eligible.filter((player) => bidOf(player, summary.faction) === highest); - const winner = tiedPlayers.length === 1 ? tiedPlayers[0] : tiedPlayers[pick(tiedPlayers.length, random)]; + // Deterministic tiebreak, no PRNG (reproducible from the bids alone): the player who nominated + // their faction LATEST in setup order wins. The last faction-picker picks a booster first + // (booster order is reverse nomination order) and, per the owner's ruling, wins auction ties. + // A player's nomination position is the index in `factions` of the faction they nominated. + const nominationPos = (player: PlayerEnum) => factions.indexOf(nominatedFaction.get(player)); + const winner = tiedPlayers.reduce((a, b) => (nominationPos(a) >= nominationPos(b) ? a : b)); remaining.splice(remaining.indexOf(winner), 1); return { diff --git a/engine/src/algorithms/silent-auction.spec.ts b/engine/src/algorithms/silent-auction.spec.ts index 3e8639b4..d0526355 100644 --- a/engine/src/algorithms/silent-auction.spec.ts +++ b/engine/src/algorithms/silent-auction.spec.ts @@ -33,9 +33,10 @@ describe("resolveSilentAuction", () => { [C, Faction.Taklons], ]); - // Only one tiebreak in the whole trace reaches rule #3 (random): B's turn 11, indifferent - // between Itars and Taklons. Force it to pick the 2nd candidate (Taklons), as the guide does. - const result = resolveSilentAuction(factions, [A, B, C], bids, nominatedFaction, () => 0.99); + // Only one tiebreak in the whole trace reaches rule #3 (setup order): B's turn 11, indifferent + // between Itars and Taklons. The deterministic rule picks the LATEST-nominated faction in setup + // order - Taklons (index 1) over Itars (index 0) - which happens to match the guide's pick. + const result = resolveSilentAuction(factions, [A, B, C], bids, nominatedFaction); expect(result.winners.get(Faction.Taklons)).to.equal(A); expect(result.winners.get(Faction.Itars)).to.equal(B); @@ -50,7 +51,7 @@ describe("resolveSilentAuction", () => { expect(result.log).to.have.length(18); expect(result.log[8]).to.deep.include({ player: C, faction: Faction.Itars, price: 7, tiebreak: "existing" }); expect(result.log[9]).to.deep.include({ player: A, faction: Faction.Taklons, skipped: true }); - expect(result.log[10]).to.deep.include({ player: B, faction: Faction.Taklons, price: 1, tiebreak: "random" }); + expect(result.log[10]).to.deep.include({ player: B, faction: Faction.Taklons, price: 1, tiebreak: "setupOrder" }); expect(result.log[11]).to.deep.include({ player: C, faction: Faction.Itars, skipped: true }); expect(result.log[12]).to.deep.include({ player: A, faction: Faction.Taklons, price: 2 }); }); diff --git a/engine/src/algorithms/silent-auction.ts b/engine/src/algorithms/silent-auction.ts index 95652b39..336d4f4d 100644 --- a/engine/src/algorithms/silent-auction.ts +++ b/engine/src/algorithms/silent-auction.ts @@ -56,7 +56,7 @@ export type SilentAuctionStep = { price: number; /** true when the player already led `faction` (their best-value option) and made no bid */ skipped: boolean; - tiebreak?: "existing" | "nominated" | "random"; + tiebreak?: "existing" | "nominated" | "setupOrder"; }; export type SilentAuctionResult = { @@ -79,15 +79,20 @@ export type SilentAuctionResult = { * its price to (current price + 1), or to 0 if it's unclaimed, and become its new leader (bumping * off whoever led it before). Ties in value are broken by, in order: preferring to raise an * existing bid over claiming an untouched faction, preferring the faction the player originally - * picked in the nomination/pick phase, then uniformly at random. The auction ends once a full - * round passes with every player skipped. + * picked in the nomination/pick phase, then DETERMINISTICALLY by faction setup order (the order the + * factions were nominated in) - earliest first. The auction ends once a full round passes with + * every player skipped. + * + * The last tiebreak used to be `random()` (seeded PRNG). It is deterministic now (owner decision, + * 2026-09) so the resolution depends ONLY on the submitted bids - no PRNG to persist or reseed + * across a server round-trip, which is what broke hosted simultaneous bidding when the last bid + * landed on a reloaded engine (`map.rng is not a function`). */ export function resolveSilentAuction( factions: Faction[], seatOrder: PlayerEnum[], bids: SilentAuctionBid[], - nominatedFaction: Map, - random: () => number = Math.random + nominatedFaction: Map ): SilentAuctionResult { const maxBid = (player: PlayerEnum, faction: Faction) => bids.find((b) => b.player === player && b.faction === faction)?.max ?? 0; @@ -142,8 +147,12 @@ export function resolveSilentAuction( } } if (candidates.length > 1) { - candidates = [candidates[Math.floor(random() * candidates.length)]]; - tiebreak = "random"; + // Deterministic, no PRNG (reproducible from the bids alone - nothing to reseed across a + // server round-trip): the LATEST-nominated faction in setup order. The last faction-picker + // picks a booster first (setup booster order is reverse nomination order), and the owner + // ruled that the first booster-picker wins auction ties. `factions` IS the nomination order. + candidates = [candidates.reduce((a, b) => (factions.indexOf(a) >= factions.indexOf(b) ? a : b))]; + tiebreak = "setupOrder"; } const best = candidates[0]; diff --git a/engine/src/engine.ts b/engine/src/engine.ts index 5baa1161..68ebfec5 100644 --- a/engine/src/engine.ts +++ b/engine/src/engine.ts @@ -312,6 +312,27 @@ export default class Engine { // written exactly once, when the last submission lands, and never recomputed afterwards. preferenceSplitBids: PreferenceSplitBid[] = []; preferenceSplitResult?: PreferenceSplitResult; + + /** + * Simultaneous sealed bidding (Silent / Preference Split Auction). The seats that still owe a + * bid, derived from the phase + the bids already recorded - `undefined` outside a bid phase, so + * callers can tell "not a bid phase" apart from "bid phase, nobody left". + * + * The bid phases collect one whole bid vector per seat, in ANY order (the platform accepts a move + * from every seat `currentPlayer()` names). Nothing is derived from any bid until the last one + * lands, so collecting them simultaneously is equivalent to collecting them in turn order - only + * without forcing players to wait. Recorded bids are keyed by seat, so the order they arrive in + * never affects the resolution. + */ + sealedBidPendingSeats(): PlayerEnum[] | undefined { + const isBidPhase = this.phase === Phase.SetupSilentBid || this.phase === Phase.SetupPreferenceBid; + if (!isBidPhase) { + return undefined; + } + const bids = this.phase === Phase.SetupSilentBid ? this.silentAuctionBids : this.preferenceSplitBids; + const bidSeats = new Set(bids.map((bid) => bid.player as number)); + return this.players.map((pl) => pl.player as PlayerEnum).filter((seat) => !bidSeats.has(seat)); + } options: EngineOptions = {}; tiles: { boosters: { @@ -495,9 +516,21 @@ export default class Engine { const move = _move.trim(); this.pendingMove = move; let moveToShow = move; - if (this.playerToMove !== undefined) { - this.log(this.playerToMove, undefined, 0, undefined); - moveToShow = createMoveToShow(move, this.player(this.playerToMove), this.map, execute); + // Attribute the move to whoever actually played it. In simultaneous sealed bidding the mover is + // NOT the sequential `playerToMove` (any pending seat may bid in any order), so parse the seat + // off the move string for those; everywhere else it is the turn player as before. + const pendingSeats = this.sealedBidPendingSeats(); + const isSealedBid = pendingSeats !== undefined && /^(p[1-7]|\S+)\s+(silentBid|preferenceBid)\b/.test(move); + let actingPlayer = this.playerToMove; + if (isSealedBid) { + const seatMatch = /^p([1-7])\b/.exec(move); + if (seatMatch) { + actingPlayer = (+seatMatch[1] - 1) as PlayerEnum; + } + } + if (actingPlayer !== undefined) { + this.log(actingPlayer, undefined, 0, undefined); + moveToShow = createMoveToShow(move, this.player(actingPlayer), this.map, execute); } else { execute(); } @@ -998,10 +1031,24 @@ export default class Engine { } if (!this.replay) { - assert( - this.playerToMove === (player as PlayerEnum), - "Wrong turn order in move " + move + ", expected player " + (this.playerToMove + 1) - ); + // Simultaneous sealed bidding (Silent / Preference Split Auction): a bid is legal from ANY + // seat still owing one, regardless of where the engine's sequential `playerToMove` pointer + // happens to sit. The bid phases collect submissions in any order (the platform accepts moves + // from every seat `currentPlayer()` names) and resolve only once the last one lands - the + // turn pointer is meaningless during them. Everywhere else the strict turn-order check stands. + const pending = this.sealedBidPendingSeats(); + const isSealedBidMove = pending !== undefined && /^(p[1-7]|\S+)\s+(silentBid|preferenceBid)\b/.test(move.trim()); + if (isSealedBidMove) { + assert( + pending.includes(player as PlayerEnum), + "Player " + (player + 1) + " has already submitted their bids (or is not in this auction)" + ); + } else { + assert( + this.playerToMove === (player as PlayerEnum), + "Wrong turn order in move " + move + ", expected player " + (this.playerToMove + 1) + ); + } } this.processedPlayer = player; @@ -1085,6 +1132,20 @@ export default class Engine { }; } + /** + * The seat actually executing the current command. Identical to `playerToMove` everywhere except + * a simultaneous sealed-bid phase, where `loadTurnMoves` has already parsed the bidding seat off + * the move string into `processedPlayer` - use that, so `silentBid`/`preferenceBid` are recorded + * against the real bidder (not wherever the sequential turn pointer happens to sit). + */ + private get actingSeat(): PlayerEnum { + const pending = this.sealedBidPendingSeats(); + if (pending !== undefined && this.processedPlayer !== undefined) { + return this.processedPlayer as PlayerEnum; + } + return this.playerToMove; + } + processNextMove(subphase?: SubPhase, data?: any, required = false) { if (subphase) { this.generateAvailableCommands(subphase, data); @@ -1154,7 +1215,7 @@ export default class Engine { [Command.ExamineArtifact]: moveExamineArtifact, [Command.ChooseArtifactToken]: moveChooseArtifactToken, }; - moveRegistry[move.command](this, this.avCommand(), this.playerToMove, ...move.args); + moveRegistry[move.command](this, this.avCommand(), this.actingSeat, ...move.args); return move; } @@ -1165,7 +1226,13 @@ export default class Engine { checkCommand(command: Command) { this.availableCommand = this.findAvailableCommand(this.playerToMove, command); - if (!this.availableCommand && !this.replay) { + // Simultaneous sealed bidding: availableCommands are only generated for the sequential + // `playerToMove`, so an off-turn bidder's command won't be in the list - that's expected, not + // illegal. `moveSilentBid`/`movePreferenceBid` do their own legality check (the shared + // silentAuctionBidError / preferenceSplitBidError), which is the check that actually matters. + const isSealedBid = + this.sealedBidPendingSeats() !== undefined && [Command.SilentBid, Command.PreferenceBid].includes(command); + if (!this.availableCommand && !this.replay && !isSealedBid) { assert(this.availableCommand, `Command ${command} is not in the list of available commands`); } } diff --git a/engine/src/move/phase.ts b/engine/src/move/phase.ts index dbc7125d..e8865987 100644 --- a/engine/src/move/phase.ts +++ b/engine/src/move/phase.ts @@ -98,14 +98,20 @@ export function phaseSetupAuction(engine: Engine, move: string) { export function phaseSetupSilentBid(engine: Engine, move: string) { engine.loadTurnMoves(move, { split: false, processFirst: true }); - if (!engine.moveToNextPlayer(engine.turnOrder, { loop: false })) { + // Simultaneous collection: resolve as soon as the LAST pending bid lands, regardless of the + // order they arrived in (`sealedBidPendingSeats` reads the recorded bids, so the sequential + // `moveToNextPlayer` walk is no longer what gates resolution). The old sequential walk is kept + // only to keep `currentPlayer` moving for any client still reading it, but it no longer decides + // when the auction resolves. + engine.moveToNextPlayer(engine.turnOrder, { loop: false }); + + if ((engine.sealedBidPendingSeats() ?? []).length === 0) { const nominatedFaction = new Map(engine.players.map((pl) => [pl.player as PlayerEnum, pl.faction])); const result = resolveSilentAuction( engine.setup, engine.players.map((pl) => pl.player as PlayerEnum), engine.silentAuctionBids, - nominatedFaction, - () => engine.map.rng() + nominatedFaction ); engine.silentAuctionLog = result.log; for (const player of engine.players) { @@ -137,7 +143,10 @@ export function phaseSetupSilentBid(engine: Engine, move: string) { export function phaseSetupPreferenceBid(engine: Engine, move: string) { engine.loadTurnMoves(move, { split: false, processFirst: true }); - if (!engine.moveToNextPlayer(engine.turnOrder, { loop: false })) { + // Simultaneous collection: resolve as soon as the last pending bid lands (see phaseSetupSilentBid). + engine.moveToNextPlayer(engine.turnOrder, { loop: false }); + + if ((engine.sealedBidPendingSeats() ?? []).length === 0) { resolvePreferenceSplitPhase(engine); endSetupFactionPhase(engine); } @@ -150,12 +159,13 @@ function resolvePreferenceSplitPhase(engine: Engine) { return; } + const nominatedFaction = new Map(engine.players.map((pl) => [pl.player as PlayerEnum, pl.faction])); const result = resolvePreferenceSplitAuction( engine.setup, engine.players.map((pl) => pl.player as PlayerEnum), engine.preferenceSplitBids, engine.preferenceSplitBudget, - () => engine.map.rng() + nominatedFaction ); engine.preferenceSplitResult = result; diff --git a/engine/src/silent-auction-simultaneous.spec.ts b/engine/src/silent-auction-simultaneous.spec.ts new file mode 100644 index 00000000..6b316de0 --- /dev/null +++ b/engine/src/silent-auction-simultaneous.spec.ts @@ -0,0 +1,90 @@ +import { expect } from "chai"; +import { currentPlayer } from "../wrapper"; +import Engine, { AuctionVariant } from "./engine"; +import { Phase } from "./enums"; + +/** + * Simultaneous sealed bidding (boardgamers.space contract). The Silent Auction's bid phase must let + * every seat still owing a bid submit in ANY order - the platform's `/move` route authorizes a move + * when the user is in `game.currentPlayers`, which the game-server fills from `currentPlayer()`. + * Returning a single seat (the old behavior) is what made off-turn bidders hit "not your turn". + */ +describe("Silent Auction - simultaneous sealed bids", () => { + const auctionOptions = { auction: AuctionVariant.Silent }; + + // Ban + faction-pick moves, stopping right before the bid phase. + const preBidMoves = Engine.parseMoves(` + init 3 djfjjv4k + p1 banFaction terrans + p2 banFaction lantids + p3 banFaction hadsch-hallas + p1 faction itars + p2 faction xenos + p3 faction taklons + `); + + const bid = (seat: number, amounts: number[]) => + `p${seat + 1} silentBid itars ${amounts[0]} xenos ${amounts[1]} taklons ${amounts[2]}`; + + function toBidPhase(): Engine { + return new Engine(preBidMoves, auctionOptions); + } + + it("exposes every pending seat via wrapper.currentPlayer during the bid phase", () => { + const engine = toBidPhase(); + expect(engine.phase).to.equal(Phase.SetupSilentBid); + + const current = currentPlayer(engine); + expect(Array.isArray(current) ? current : [current]).to.have.members([0, 1, 2]); + }); + + it("accepts bids in any order and resolves only when the last one lands", () => { + const engine = toBidPhase(); + + // p3 bids FIRST (not p1, whose turn the sequential pointer is on). + engine.move(bid(2, [7, 0, 0])); + expect(engine.phase).to.equal(Phase.SetupSilentBid); + expect(engine.sealedBidPendingSeats()).to.have.members([0, 1]); + expect(currentPlayer(engine)).to.have.members([0, 1]); + + // p1 bids second. + engine.move(bid(0, [15, 0, 10])); + expect(engine.phase).to.equal(Phase.SetupSilentBid); + expect(engine.sealedBidPendingSeats()).to.deep.equal([1]); + + // p2 bids last - the auction resolves and setup moves on. + engine.move(bid(1, [15, 5, 8])); + expect(engine.phase).to.equal(Phase.SetupBuilding); + }); + + it("rejects a second bid from a seat that already submitted", () => { + const engine = toBidPhase(); + engine.move(bid(2, [7, 0, 0])); + expect(() => engine.move(bid(2, [9, 0, 0]))).to.throw(); + }); + + it("rejects a non-bid move from a seat whose turn it isn't, even during the bid phase", () => { + const engine = toBidPhase(); + // A non-bid command still goes through the strict turn-order check. + expect(() => engine.move("p2 build m 0x0")).to.throw(); + }); + + it("produces the same resolution regardless of submission order", () => { + // Order A: p1, p2, p3 (seat order). + const inOrder = new Engine( + Engine.parseMoves([...preBidMoves, bid(0, [15, 0, 10]), bid(1, [15, 5, 8]), bid(2, [7, 0, 0])].join("\n")), + auctionOptions + ); + // Order B: p3, p1, p2 (reverse-ish). + const outOfOrder = new Engine( + Engine.parseMoves([...preBidMoves, bid(2, [7, 0, 0]), bid(0, [15, 0, 10]), bid(1, [15, 5, 8])].join("\n")), + auctionOptions + ); + + for (const e of [inOrder, outOfOrder]) { + expect(e.players[0].faction).to.equal("taklons"); + expect(e.players[1].faction).to.equal("itars"); + expect(e.players[2].faction).to.equal("xenos"); + } + }); +}); diff --git a/engine/wrapper.ts b/engine/wrapper.ts index 9ec42a96..8be5b52f 100644 --- a/engine/wrapper.ts +++ b/engine/wrapper.ts @@ -236,7 +236,23 @@ export async function dropPlayer(engine: Engine, player: number) { return engine; } -export function currentPlayer(engine: Engine) { +/** + * Whose move the platform should accept right now. Returns a single seat in sequential play, an + * ARRAY of seats during a simultaneous sealed-bid phase (Silent / Preference Split Auction - every + * seat still owing a bid may submit in any order), and `undefined` when the game is over or between + * phases. The platform normalizes both shapes (`Array.isArray(current) ? current : [current]`) and + * persists all of them to `game.currentPlayers`, which is the check its `/move` route authorizes + * against - returning the array is what lifts the "not your turn to play" rejection off-turn + * bidders used to hit. Same array convention as the other BGS games (Outpost / Power Grid). + */ +export function currentPlayer(engine: Engine): number | number[] | undefined { + const pending = engine.sealedBidPendingSeats(); + if (pending !== undefined) { + if (pending.length === 0) { + return undefined; + } + return pending.length === 1 ? pending[0] : pending; + } return engine.playerToMove; } diff --git a/viewer/package.json b/viewer/package.json index 45a1652c..5d1f15db 100644 --- a/viewer/package.json +++ b/viewer/package.json @@ -1,6 +1,6 @@ { "name": "@gaia-project/viewer", - "version": "5.15.6", + "version": "5.16.0", "description": "Functions to visualize the map and boards for gaia project inside html canvas", "contributors": [ "coyotte508", diff --git a/viewer/src/components/PreferenceSplitBid.spec.ts b/viewer/src/components/PreferenceSplitBid.spec.ts index aea0c5d3..6f5fe4bf 100644 --- a/viewer/src/components/PreferenceSplitBid.spec.ts +++ b/viewer/src/components/PreferenceSplitBid.spec.ts @@ -204,7 +204,7 @@ describe("PreferenceSplitBid", () => { ]); }); - it("falls back to an ordinary move in offline/hot-seat play, for the seat on turn", async () => { + it("falls back to an ordinary move in offline/hot-seat play, seat-prefixed for the engine", async () => { // No lock AND no backend - the offline case, where the seat on turn is the one to bid for. const { store } = biddingStore({ seat: null }); const { container, emitted } = render(PreferenceSplitBid, { store }); @@ -212,7 +212,8 @@ describe("PreferenceSplitBid", () => { await fill(container, [20, 12, 6, 2]); await fireEvent.click(submitButton(container)); - expect(emitted().command[0]).to.deep.equal(["preferenceBid itars 20 taklons 12 xenos 6 terrans 2"]); + // Seat-prefixed so the engine parses the bidder (any pending seat's bid is accepted now). + expect(emitted().command[0]).to.deep.equal(["p1 preferenceBid itars 20 taklons 12 xenos 6 terrans 2"]); }); it("stays hidden outside the bid phase", () => { diff --git a/viewer/src/components/SealedBidPanel.ts b/viewer/src/components/SealedBidPanel.ts index c6415362..3430db15 100644 --- a/viewer/src/components/SealedBidPanel.ts +++ b/viewer/src/components/SealedBidPanel.ts @@ -75,10 +75,11 @@ export default class SealedBidPanel extends Vue { /** * Online play without a sealed backend (boardgamers.space): this device holds exactly one locked - * seat and a bid is an ordinary move relayed through the platform. The engine collects bids one - * seat at a time, but the platform's stripSecret masks every submitted bid from the other - * clients until the reveal - so the round is sequential-but-sealed: you may have to wait for - * your turn to submit, yet nobody ever sees a value before the auction resolves. + * seat and a bid is an ordinary move relayed through the platform. The engine collects bids from + * EVERY pending seat simultaneously (its `currentPlayer()` returns all of them, and `move()` + * accepts a bid from any of them in any order), while the platform's stripSecret masks every + * submitted bid from the other clients until the reveal - so the round is truly simultaneous AND + * sealed: nobody waits for a turn, and nobody ever sees a value before the auction resolves. */ get onlineSequential(): boolean { if (this.backend || this.$store.state.analysisMode) { @@ -88,17 +89,14 @@ export default class SealedBidPanel extends Vue { return typeof locked === "number" && locked >= 0; } - /** True while this device's seat may not submit yet (online sequential play, not on turn). */ + /** Kept for the template: simultaneous bidding means a pending seat may always submit now. */ get waitingForTurn(): boolean { - return this.onlineSequential && this.seat !== null && this.gameData?.playerToMove !== this.seat; + return false; } - /** Small hint under the form while `waitingForTurn` - the inputs stay editable so the bids can - * be prepared, only the submit waits. */ + /** Kept for the template: no turn to wait for anymore - every pending seat bids at once. */ get turnHint(): string { - return this.waitingForTurn - ? "Waiting for your turn to submit - bids already made stay sealed until everyone has bid." - : ""; + return ""; } // ------------------------------------------------------------------------- @@ -351,9 +349,15 @@ export default class SealedBidPanel extends Vue { this.locallySubmitted = [...this.locallySubmitted, seat]; this.resetValues(); } else { - // Offline/hot-seat: no server to seal anything, so the bid is an ordinary move for the seat - // on turn and secrecy is whoever else is looking at the screen. - this.$emit("command", `${this.commandName} ${this.entries.map((e) => `${e.faction} ${e.points}`).join(" ")}`); + // No sealed backend (offline/hot-seat, or boardgamers.space): the bid is an ordinary move. + // Prefix it with the seat (`p${seat+1}`) - the engine parses the bidder off that token, and + // with simultaneous bidding it accepts the bid from ANY pending seat, not just the one its + // turn pointer is on. Omitting the prefix left the seat unparseable, which is what made + // off-turn submissions fail with "Wrong turn order ... expected player NaN". + this.$emit( + "command", + `p${seat + 1} ${this.commandName} ${this.entries.map((e) => `${e.faction} ${e.points}`).join(" ")}` + ); this.resetValues(); } } catch (err) { diff --git a/viewer/src/components/SilentAuctionBid.spec.ts b/viewer/src/components/SilentAuctionBid.spec.ts index 52621b47..ce9e0815 100644 --- a/viewer/src/components/SilentAuctionBid.spec.ts +++ b/viewer/src/components/SilentAuctionBid.spec.ts @@ -196,14 +196,30 @@ describe("SilentAuctionBid", () => { ]); }); - it("falls back to an ordinary move in offline/hot-seat play, for the seat on turn", async () => { + it("falls back to an ordinary move in offline/hot-seat play, seat-prefixed for the engine", async () => { const { store } = biddingStore({ seat: null }); const { container, emitted } = render(SilentAuctionBid, { store }); await fill(container, [15, 0, 10]); await fireEvent.click(submitButton(container)); - expect(emitted().command[0]).to.deep.equal(["silentBid itars 15 xenos 0 taklons 10"]); + // The seat prefix lets the engine parse the bidder - with simultaneous bidding any pending + // seat's bid is accepted, so the prefix (not the turn pointer) is what identifies the bidder. + expect(emitted().command[0]).to.deep.equal(["p1 silentBid itars 15 xenos 0 taklons 10"]); + }); + + it("an off-turn seat's bid is seat-prefixed and immediately submittable (no waiting for turn)", async () => { + // Seat 1 (p2) while the turn pointer is on seat 0 - the exact case that used to be blocked. + const { store } = biddingStore({ seat: 1 }); + const { container, emitted } = render(SilentAuctionBid, { store }); + + expect(submitButton(container).disabled).to.equal(false); + expect(container.textContent).to.not.contain("Waiting for your turn"); + + await fill(container, [5, 3, 8]); + await fireEvent.click(submitButton(container)); + + expect(emitted().command[0]).to.deep.equal(["p2 silentBid itars 5 xenos 3 taklons 8"]); }); it("renders in a hosted test game, where one account holds every seat and there is no seat lock", async () => { diff --git a/viewer/vitest.setup.ts b/viewer/vitest.setup.ts index d022727d..60cf1c32 100644 --- a/viewer/vitest.setup.ts +++ b/viewer/vitest.setup.ts @@ -3,6 +3,31 @@ // assertions in the existing specs import chai explicitly - keep that working plus a DOM root. import { expect } from "vitest"; +// jsdom's localStorage is intermittently broken in this environment (getItem/setItem missing on +// `window.localStorage`). Several stores read/write it at module scope, so install a tiny in-memory +// polyfill whenever the real one is absent or non-functional. +(() => { + const broken = + typeof globalThis.localStorage === "undefined" || typeof globalThis.localStorage.getItem !== "function"; + if (!broken) { + return; + } + const store = new Map(); + const ls = { + getItem: (k: string) => (store.has(String(k)) ? (store.get(String(k)) as string) : null), + setItem: (k: string, v: string) => void store.set(String(k), String(v)), + removeItem: (k: string) => void store.delete(String(k)), + clear: () => store.clear(), + key: (i: number) => Array.from(store.keys())[i] ?? null, + get length() { + return store.size; + }, + }; + for (const target of [globalThis, ...(typeof window !== "undefined" ? [window] : [])] as any[]) { + Object.defineProperty(target, "localStorage", { value: ls, configurable: true, writable: true }); + } +})(); + // Some specs mount components into document.body (launcher.spec.ts uses unique ids); // jsdom provides the DOM. Nothing else needed globally - chai is imported per-spec. export { expect };