Fix interactive analysis cash and manual-seat policy

This commit is contained in:
coyotte508 2026-11-10 08:25:37 +00:00
commit 5fc0e22236
8 changed files with 235 additions and 15 deletions

View file

@ -0,0 +1,54 @@
# Interactive analysis policy
The host-facing `dist/wrapper.js` export `createAnalysisScenario(data, { player, seed })` uses the interactive policy. The strong AI imports
`dist/src/analysis.js` directly; its default information-set sampler is unchanged.
Do not point AI callers at the wrapper's interactive export.
For hidden-money sources (`options.showMoney !== true`), interactive creation
initializes **every** seat to $999, including the requester. These are finite,
hypothetical balances: ordinary costs, affordability checks and income apply.
`analysisMoney: 'hypothetical'` identifies this state to secret stripping and the
viewer. Re-sampling an existing marked branch preserves its evolved balances;
creating a fresh branch from a live source starts a new $999 scenario. Public-money
sources retain their public balances.
Interactive creation does not reconstruct cash from history. It discards private
powering revision snapshots, all source sealed bids (including the requester's),
private logs and automation. Partially sealed auctions reopen every eligible seat
for manual input. Unknown cards still come from the public catalogue, not the
source deck or seed. The source object is not mutated.
`analysisMove` calls only the ordinary atomic rules engine, not the live wrapper's
premoves or affordability/preference auto-passes. Mandatory resolution, market
updates, income and phase transitions remain in effect. No bot/drop status may
choose moves for a seat. Existing one-turn buffer boundaries remain enforced.
## Host integration
No new host API or option is required for the confirmed ongoing-analysis route:
load the updated wrapper export for scenario creation, call its `analysisMove`
for each manually submitted turn, and continue selecting an active seat. Send the
branch's `analysisMoney` field through to the viewer. Never route these moves to
ordinary `move`/`moveAI`, or replace the evolving branch with the live source.
Existing persisted scenarios created before this change need a new branch to get
the new initial-cash policy.
The separate `createAnalysis` exact historical replay hook still retains the
existing finished-source policy (real, now-public historical balances and deck).
Its actors are manual too. Whether hidden-money _finished_ sources should instead
be forced through the hypothetical scenario policy remains a policy decision;
that routing has not been changed here. Ongoing hidden-money sources must use
`createAnalysisScenario`, never exact historical replay.
These changes have not been published. After integrating release master through
`0f0f3eb`, package versions remain engine 2.0.24 / viewer 2.3.26; release bumps are
pending successful publication authorization. The available account can log in,
but the BGS admin metadata request for Powergrid version 13 returns HTTP 403.
No upload or activation was attempted. Historical release receipts are not a
fresh verification of the currently deployed engine.
Post-integration checks: 423 engine tests, engine TypeScript build, 95 viewer unit
tests, viewer library packaging and bundle-size check, eight locale tests, and the
action-label browser smoke checks pass. A local-only hypothetical analysis fixture
also verifies all three seats display `Hypothetical: $999`; it is not evidence of
a deployed host analysis session.

View file

@ -23,9 +23,16 @@ import { shuffle } from './utils';
/** Unknown cards come from the published catalogue, never the live draw pile. */
export function createAnalysisScenario(
data: GameState,
{ player, seed }: { player?: number; seed: string }
{ player, seed, interactive = false }: { player?: number; seed: string; interactive?: boolean }
): GameState {
const s: GameState = JSON.parse(JSON.stringify(stripSecret(data, player)));
// Interactive branches never retain even the requester's sealed bid or private
// revision snapshot. The default remains the AI information-set sampler.
const s: GameState = JSON.parse(JSON.stringify(stripSecret(data, interactive ? undefined : player)));
if (interactive) {
delete s.poweringChoices;
delete s.revisedPowering;
if (!s.options.showMoney) s.analysisMoney = 'hypothetical';
}
delete s.powerPlantDeckAfterStep3;
const rng = seedrandom(seed);
const name = s.map.name;
@ -242,20 +249,30 @@ export function createAnalysisScenario(
}, bottom ${fixedBottom}, recycled ${[...recycled]}`
);
// The visible history permits money accounting without reading hidden balances.
const publicReplay = reconstructState(s, s.log.length, true);
const publicReplay = interactive ? undefined : reconstructState(s, s.log.length, true);
s.players.forEach((p, i) => {
if (p.money < 0) p.money = publicReplay.players[i].money;
if (interactive && !s.options.showMoney && data.analysisMoney !== 'hypothetical') p.money = 999;
else if (p.money < 0 && publicReplay) p.money = publicReplay.players[i].money;
p.isAI = false;
p.isDropped = false;
p.lastMove = null;
delete p.targetCitiesPowered;
if (s.options.fastBid && i !== player) {
if (s.options.fastBid && (interactive || i !== player)) {
p.bid =
s.chosenPowerPlant && !s.currentPlayers.includes(i) && !p.skipAuction && p.money >= s.minimunBid
!interactive &&
s.chosenPowerPlant &&
!s.currentPlayers.includes(i) &&
!p.skipAuction &&
p.money >= s.minimunBid
? Math.min(p.money, s.minimunBid + Math.floor(rng() * Math.max(1, p.money - s.minimunBid + 1)))
: 0;
}
});
if (interactive && s.options.fastBid && s.chosenPowerPlant) {
// A partially sealed auction is reopened for ALL eligible seats; no
// sampled or source commitment may make a choice on a human's behalf.
s.currentPlayers = s.playerOrder.filter((id) => !s.players[id].skipAuction);
}
s.seed = seed;
s.hiddenLog = [];
delete s.automation;

View file

@ -769,7 +769,7 @@ export function stripSecret(G: GameState, player?: number): GameState {
...pl,
settings: undefined,
availableMoves: pl.availableMoves ? {} : null,
money: ended(G) || G.options.showMoney ? pl.money : -1,
money: ended(G) || G.options.showMoney || G.analysisMoney === 'hypothetical' ? pl.money : -1,
bid: G.options.fastBid ? 0 : pl.bid,
};
}

View file

@ -194,6 +194,8 @@ export enum Phase {
}
export interface GameState {
/** Interactive sandbox cash, initialized once; never attached to live games. */
analysisMoney?: 'hypothetical';
poweringChoices?: Record<number, import('./choice-revisions').PoweringChoice>;
revisedPowering?: Record<number, number>;
pendingMessages?: string[];

View file

@ -0,0 +1,117 @@
import { expect } from 'chai';
import 'mocha';
import * as wrapper from '../wrapper';
import { availableMoves } from './available-moves';
import { setup, stripSecret } from './engine';
import { GameState, Phase } from './gamestate';
import { MoveName } from './move';
const clone = (s: GameState): GameState => JSON.parse(JSON.stringify(s));
describe('manual interactive analysis policy', () => {
it('uses only hypothetical cash and reopens sealed commitments for every seat', async () => {
const live = setup(3, { fastBid: true }, 'private');
const actor = live.currentPlayers[0];
let source = await wrapper.analysisMove(
live,
{ name: MoveName.ChoosePowerPlant, data: live.actualMarket[0].number },
actor
);
source = await wrapper.analysisMove(source, { name: MoveName.Bid, data: 20 }, source.currentPlayers[0]);
const before = clone(source);
const other = clone(source);
other.seed = 'another-private-seed';
other.powerPlantsDeck.reverse();
other.powerPlantDeckAfterStep3 = [];
other.hiddenLog = [];
other.players.forEach((p) => {
p.money += 123;
p.bid += 37;
});
const branch = wrapper.createAnalysisScenario(source, { player: actor, seed: 'sandbox' });
expect(branch).to.deep.equal(wrapper.createAnalysisScenario(other, { player: actor, seed: 'sandbox' }));
expect(branch.players.map((p) => p.money)).to.deep.equal([999, 999, 999]);
expect(branch.players.map((p) => p.bid)).to.deep.equal([0, 0, 0]);
expect(branch.currentPlayers).to.have.length(3);
expect(branch.analysisMoney).to.equal('hypothetical');
expect(stripSecret(branch).players.map((p) => p.money)).to.deep.equal([999, 999, 999]);
expect(stripSecret(source).players.map((p) => p.money)).to.deep.equal([-1, -1, -1]);
expect(clone(source)).to.deep.equal(before);
});
it('hands off opponents manually and spends finite cash without resetting on move or resample', async () => {
let branch = wrapper.createAnalysisScenario(setup(3, { fastBid: true }, 'source'), { seed: 'sandbox' });
const actor = branch.currentPlayers[0];
branch = await wrapper.analysisMove(
branch,
{ name: MoveName.ChoosePowerPlant, data: branch.actualMarket[0].number },
actor
);
const bidder = branch.currentPlayers[0];
branch = await wrapper.analysisMove(branch, { name: MoveName.Bid, data: 999 }, bidder);
expect(branch.currentPlayers).to.have.length(2);
expect(branch.players.filter((p) => p.bid > 0)).to.have.length(1);
const second = branch.currentPlayers[0];
branch = await wrapper.analysisMove(branch, { name: MoveName.Bid, data: 998 }, second);
expect(branch.currentPlayers).to.have.length(1);
branch = await wrapper.analysisMove(branch, { name: MoveName.Pass, data: true }, branch.currentPlayers[0]);
expect(branch.players[bidder].money).to.be.lessThan(999);
expect(branch.players[bidder].money).to.be.at.least(0);
expect(wrapper.createAnalysisScenario(branch, { seed: 'resample' }).players.map((p) => p.money)).to.deep.equal(
branch.players.map((p) => p.money)
);
// Finite hypothetical cash still uses the ordinary affordability rules.
branch.phase = Phase.Auction;
branch.chosenPowerPlant = undefined;
branch.round = 2;
branch.currentPlayers = [bidder];
branch.players[bidder].skipAuction = false;
branch.players[bidder].passed = false;
const legal = availableMoves(branch, branch.players[bidder]);
expect(legal.ChoosePowerPlant || []).to.have.length(0);
});
it('credits ordinary income to the evolving hypothetical balance', async () => {
let branch = wrapper.createAnalysisScenario(setup(3, {}, 'source'), { seed: 'sandbox' });
branch.phase = Phase.Bureaucracy;
branch.currentPlayers = [...branch.playerOrder];
branch.players.forEach((p) => {
p.passed = false;
p.availableMoves = availableMoves(branch, p);
});
const actor = branch.currentPlayers[0];
branch = await wrapper.analysisMove(branch, { name: MoveName.Pass, data: true }, actor);
expect(branch.players[actor].money).to.equal(1009);
expect(branch.currentPlayers).to.have.length(2);
expect(branch.players[branch.currentPlayers[0]].money).to.equal(999);
});
it('preserves public cash rather than replacing it with hypothetical cash', () => {
const source = setup(3, { showMoney: true }, 'source');
source.players[0].money = 123;
const branch = wrapper.createAnalysisScenario(source, { seed: 'sandbox' });
expect(branch.players.map((p) => p.money)).to.deep.equal(source.players.map((p) => p.money));
expect(branch.analysisMoney).to.equal(undefined);
});
for (const showMoney of [false, true])
it(`does not auto-pass unaffordable opponents (public=${showMoney})`, async () => {
const branch = setup(3, { showMoney }, 'manual');
branch.round = 2;
const actor = branch.currentPlayers[0];
branch.players.forEach((p) => {
p.settings = { autoPassBids: true };
if (p.id !== actor) p.money = 0;
});
let result = await wrapper.analysisMove(
branch,
{ name: MoveName.ChoosePowerPlant, data: branch.actualMarket[0].number },
actor
);
result = await wrapper.analysisMove(result, { name: MoveName.Bid, data: result.minimunBid }, actor);
expect(result.currentPlayers).to.have.length(1);
expect(result.currentPlayers[0]).not.to.equal(actor);
expect(result.players[result.currentPlayers[0]].money).to.equal(0);
expect(result.players[result.currentPlayers[0]].availableMoves!.Pass).not.to.be.empty;
expect(result.automation).to.equal(undefined);
});
});

View file

@ -1,4 +1,5 @@
import type { GameState } from './index';
import { createAnalysisScenario as sampleAnalysisScenario } from './src/analysis';
import { autoPassAuctions } from './src/auction-auto-pass';
import { alreadyCreditedPowering, canReviseChoice } from './src/choice-revisions';
import * as engine from './src/engine';
@ -152,7 +153,10 @@ export function toSave(G: GameState): GameState | undefined {
return G.newTurn === false ? undefined : G;
}
export { createAnalysisScenario } from './src/analysis';
/** Host-facing interactive policy; AI callers import the sampler from src/analysis. */
export function createAnalysisScenario(data: GameState, options: { player?: number; seed: string }): GameState {
return sampleAnalysisScenario(data, { ...options, interactive: true });
}
export { ended, scores, stripSecret } from './src/engine';
/**
@ -373,7 +377,10 @@ export function createAnalysis(data: GameState, { to }: { to: number; sourceEnde
if (!Number.isInteger(to) || to < 0 || to > data.log.length) throw new Error('Invalid history position');
const copy = replay(JSON.parse(JSON.stringify(data)), { to });
delete copy.automation;
for (const player of copy.players) player.isDropped = false;
for (const player of copy.players) {
player.isDropped = false;
player.isAI = false;
}
copy.newTurn = true;
return copy;
}
@ -381,7 +388,22 @@ export function createAnalysis(data: GameState, { to }: { to: number; sourceEnde
export async function analysisMove(data: GameState, input: Move | Move[], player: number): Promise<GameState> {
if (isPremoveCommand(input)) throw new Error('Premoves are not available in an analysis');
delete data.automation;
const result = await move(data, input, player);
delete result.automation;
return result;
// Deliberately bypass the live wrapper: clearing premoves alone does not
// suppress preference/public-money auto-passes. engine.move still performs
// mandatory auction resolution, upkeep and phase transitions.
data.players.forEach((seat) => {
seat.isAI = false;
seat.isDropped = false;
});
const moves = Array.isArray(input) ? input : [input];
if (!moves.length) return { ...data, newTurn: false };
const now = Date.now();
for (let i = 0; i < moves.length; i++) {
const atomic = { ...moves[i] };
delete atomic.poweringClock;
data = engine.move(data, { ...atomic, serverTime: now }, player);
if (data.newTurn !== false && i < moves.length - 1)
throw new Error('The turn buffer continues past a turn boundary: only one turn may be played per call');
}
return data;
}

View file

@ -608,7 +608,8 @@
:ended="gameEnded(G)"
:isPlayer="player == playerIndex"
:ranking="sortedPlayers.findIndex((x) => x.id == G.players[playerIndex].id) + 1"
:showMoney="player == playerIndex || moneyIsPublic"
:showMoney="player == playerIndex || moneyIsPublic || G.analysisMoney === 'hypothetical'"
:hypotheticalMoney="G.analysisMoney === 'hypothetical'"
:showBid="!G.options.fastBid"
:phase="G.phase"
:isAustralia="G.map.name === 'Australia'"

View file

@ -39,8 +39,14 @@
>
{{ getPlayerName() }}
</text>
<text v-if="showMoney" x="250" y="13" font-weight="600" :fill="colorText(color)"
>Money: ${{ player.money }}</text
<text
v-if="showMoney"
x="250"
y="13"
font-weight="600"
:font-size="hypotheticalMoney ? 10 : undefined"
:fill="colorText(color)"
>{{ hypotheticalMoney ? 'Hypothetical' : 'Money' }}: ${{ player.money }}</text
>
<!-- Keep the full preference inside the viewer's own player card. -->
@ -234,6 +240,7 @@ export default class PlayerBoard extends Vue {
@Prop() isPlayer?: boolean;
@Prop() ranking?: number;
@Prop() showMoney?: boolean;
@Prop() hypotheticalMoney?: boolean;
@Prop() showBid?: boolean;
@Prop() phase?: Phase;
// Australia: uranium plants are "mines" — flag so the hand marks them distinctly.