Preserve revealed traitor income and No-Field timing
Verify and publish checkpoint container / container (push) Successful in 11m12s

This commit is contained in:
Quintine committed 2026-11-16 21:19:53 +11:00
1 parent a2e7029a72
commit e81725e4b2
12 files changed
+497 -4

No files matched your search

@@ -0,0 +1,113 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { applyAction, createGame, joinGame, newPlayer, viewGame, type Action, type Game } from '../game/engine';
import { TERRITORIES } from '../game/board';
import { traitorDeck } from '../game/traitors';
import { validateNexusTraitorSnapshot } from '../game/nexus-traitor-exchange';
import { nextHarkonnenBetrayalNativeStep, settleHarkonnenBetrayalNativeCounters } from './fixture-nexus-harkonnen-betrayal';
const act = (game: Game, actor: string, action: Action) => applyAction(game, actor, action);
function player(game: Game, id: string) {
const p = game.players.find(seat => seat.id === id); assert.ok(p); return p;
}
function step(game: Game): Game {
const next = nextHarkonnenBetrayalNativeStep(game);
try { return act(game, next.actor, next.action); }
catch (error) { throw Error(`Native CHOAM Nexus step ${game.turn}/${game.phase}/${game.decision?.kind} ${JSON.stringify(next)}: ${String(error)}`); }
}
function advance(game: Game, predicate: (game: Game) => boolean): Game {
for (let count = 0; count < 1800; count++) {
if (predicate(game)) return game;
assert.notEqual(game.status, 'finished'); game = step(game);
}
throw Error(`Native CHOAM Nexus journey stalled at ${game.status}/${game.turn}/${game.phase}/${game.decision?.kind}`);
}
function physical(game: Game) {
validateNexusTraitorSnapshot({ reserve: game.traitorReserve!, players: game.players.map(({id, faction, traitors, faceDancers}) =>
({ id, faction, traitors, ...(faceDancers ? {faceDancers} : {}) })) }, traitorDeck(game.players));
}
/** Genuine public Advanced setup and Nexus draw. Only unopened Spice/Nexus
* order, one conserved held/reserve Traitor exchange, and two physical reserve
* forces per side are staged. Battle selection, both support commitments,
* Traitor voting and the cancelable CHOAM income response are native. */
function beforeCall(): Game {
let game = createGame('CHOAMNEXUSINCOME', newPlayer('c', 'CHOAM', 'choam'), true, ['choam', 'ecaz']);
for (const [id, faction] of [['h', 'harkonnen'], ['g', 'guild'], ['a', 'atreides']] as const)
joinGame(game, newPlayer(id, faction, faction));
game = act(game, 'c', {type:'moduleOption', module:'nexusCards', enabled:true});
for (const p of game.players) game = act(game, p.id, {type:'ready'});
game = act(game, 'c', {type:'start', advancedPreview:true});
assert.equal(game.nexusHarkonnenBetrayalPreview, true);
game = advance(game, g => g.status === 'playing');
const identity = player(game, 'c').leaders.find(l => !l.dead && l.id !== 'choam-auditor')!.id;
const harkonnen = player(game, 'h');
if (!harkonnen.traitors.includes(identity)) {
const old = harkonnen.traitors[0]; assert.ok(old);
const owner = game.players.find(p => p.id !== 'h' && p.traitors.includes(identity));
if (owner) owner.traitors[owner.traitors.indexOf(identity)] = old;
else { const index = game.traitorReserve!.indexOf(identity); assert.ok(index >= 0); game.traitorReserve![index] = old; }
harkonnen.traitors[0] = identity;
}
physical(game);
const nexus = game.nexusCards!.cards!, nx = nexus.deck.indexOf('harkonnen'); assert.ok(nx >= 0);
nexus.deck.unshift(nexus.deck.splice(nx, 1)[0]);
for (let pos = 0; pos < 2; pos++) {
const index = game.spiceDeck.findIndex((card, i) => i >= pos && 'territory' in card); assert.ok(index >= pos);
game.spiceDeck.splice(pos, 0, game.spiceDeck.splice(index, 1)[0]);
}
game = advance(game, g => g.turn === 2 && g.phase === 1 && !g.response && !g.decision);
const worm = game.spiceDeck.findIndex(card => 'worm' in card && !card.greatMaker && !card.suppressed); assert.ok(worm >= 0);
game.spiceDeck.unshift(game.spiceDeck.splice(worm, 1)[0]);
game = advance(game, g => g.nexus && !g.spiceWindow && !g.spiceResolution && !g.response && !g.decision);
game = act(game, 'h', {type:'alliance', target:'g'});
game = act(game, 'g', {type:'alliance', target:'h'});
game = advance(game, g => g.nexusCards?.phase?.stage === 'drawing');
assert.ok(game.nexusCards!.phase!.eligible.includes('c'));
game = act(game, 'c', {type:'nexusCardChoice', turn:game.turn, card:null, choice:'draw', ownRedraws:0});
assert.equal(game.nexusCards!.cards!.hands.c, 'harkonnen');
game = advance(game, g => g.phase === 5 && !g.response && !g.decision && !g.pendingGuildBetrayal);
const territory = TERRITORIES.find(t => t.type === 'sand' && !t.sectors.includes(game.storm) &&
game.players.every(p => !Object.keys(p.forces).some(key => key.startsWith(`${t.id}:`))));
assert.ok(territory);
for (const id of ['h', 'c']) {
const p = player(game, id); assert.ok(p.reserves >= 2 && p.spice >= 2);
p.reserves -= 2; p.forces[`${territory.id}:${territory.sectors[0]}`] = 2;
}
game = advance(game, g => g.phase === 6 && !!g.active && !g.phaseOpening && !g.response && !g.decision);
const choice = viewGame(game, game.active!).battleChoices.find(b => b.territory === territory.id); assert.ok(choice);
game = act(game, choice.chooser, {type:'chooseBattle', territory:territory.id,
target:choice.attacker === choice.chooser ? choice.defender : choice.attacker});
game = advance(game, g => !!g.battle && !g.response && !g.decision && !g.battle.preparation &&
(!g.battle.preLeader || g.battle.preLeader.closed));
for (const id of [game.battle!.attacker, game.battle!.defender])
game = act(game, id, {type:'battlePlan', dial:2, support:2,
leader:id === 'c' ? identity : player(game, id).leaders.find(l => !l.dead && !l.usedAt)!.id});
assert.equal(game.battle!.revealed, true);
return advance(game, g => !g.response && !g.decision);
}
for (const cancel of [false, true]) void test(`Advanced CHOAM ${cancel ? 'forgoes income after a revealed and Nexus-canceled traitor' : 'receives income when neither side reveals a traitor'}`, () => {
let game = beforeCall();
const event = game.battle!.event, choamSpice = player(game, 'c').spice, harkonnenSpice = player(game, 'h').spice;
game = act(game, 'h', {type:'traitorCall', call:cancel});
if (cancel) {
game = settleHarkonnenBetrayalNativeCounters(game);
const reaction = viewGame(game, 'c').nexusHarkonnenBetrayalReaction; assert.ok(reaction?.canUse);
assert.ok(player(game, 'h').revealedTraitors?.includes(reaction.identity));
game = act(game, 'c', {type:'nexusHarkonnenBetrayalUse', event:reaction.event});
}
// Finish only the original vote and any income cancellation responses. Stop
// before unrelated capture, collection, or subsequent phase income.
for (let count = 0; count < 200; count++) {
if (game.lastBattleContext?.event === event && !game.pendingChoamBattleIncome && game.response?.kind !== 'choamBattleIncome') break;
assert.equal(game.phase, 6); game = step(game);
}
assert.equal(game.lastBattleContext?.event, event);
assert.equal(game.lastBattleContext?.result, 'normal');
assert.equal(player(game, 'h').spice, harkonnenSpice - 2);
assert.equal(player(game, 'c').spice, choamSpice - 2 + (cancel ? 0 : 1));
assert.equal(game.log.some(entry => entry.text.includes('received 1 spice from battle force payments')), !cancel);
assert.equal(game.nexusCards!.cards!.hands.c, cancel ? null : 'harkonnen');
physical(game);
});
@@ -0,0 +1,65 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { leaders } from '../game/cards';
import {
BattleResolutionQuoteError,
quoteBattleResolution,
type BattleResolutionInput,
type ResolutionCombatant,
} from '../game/battle-resolution-quote';
/** Two actual leader identities and paid forces; CHOAM is a third seat. The
* caller supplies the final public-reveal flag from the same battle receipt. */
function battle(): BattleResolutionInput {
const side = (id: string, faction: 'harkonnen' | 'atreides'): ResolutionCombatant => {
const leader = leaders(faction)[0];
return { id, faction, leader, spice: 10, hand: [],
plan: { dial: 2, support: 2, leader: leader.id, weapon: null, defense: null },
forces: { normal: 5, elite: 0, eliteStrength: 2, freeSupport: false } };
};
return { advanced: true, turn: 2, territory: 'arrakeen',
attacker: side('h', 'harkonnen'), defender: side('a', 'atreides'),
voters: [{ id: 'h', beneficiary: 'h', called: false, traitors: [] },
{ id: 'a', beneficiary: 'a', called: false, traitors: [] }],
participants: [{ id: 'h', faction: 'harkonnen' }, { id: 'a', faction: 'atreides' },
{ id: 'c', faction: 'choam' }],
physicalCards: [], pendingAuditorPresent: false, pendingRetentionPresent: false };
}
void test('a Nexus-canceled public Traitor reveal suppresses CHOAM income without changing the normal battle or payment', () => {
const normal = battle();
const canceled: BattleResolutionInput = { ...structuredClone(normal), nexusCanceledTraitorRevealed: true };
const before = structuredClone(canceled);
const ordinaryQuote = quoteBattleResolution(normal), canceledQuote = quoteBattleResolution(canceled);
assert.equal(ordinaryQuote.result, 'normal');
assert.deepEqual(ordinaryQuote.choamIncome, { owner: 'c', amount: 2 });
assert.equal(canceledQuote.choamIncome, null);
assert.deepEqual({ ...canceledQuote, choamIncome: ordinaryQuote.choamIncome }, ordinaryQuote);
assert.deepEqual(canceled, before);
});
void test('ordinary sole and mutual Traitor calls retain their native income and support rules', () => {
for (const mutual of [false, true]) {
const input = battle();
input.voters[0].called = true;
input.voters[0].traitors = [input.defender.plan.leader!];
if (mutual) {
input.voters[1].called = true;
input.voters[1].traitors = [input.attacker.plan.leader!];
}
const quote = quoteBattleResolution(input);
assert.equal(quote.result, mutual ? 'mutualTraitors' : 'traitor');
assert.equal(quote.choamIncome, null);
assert.equal(quote.payments.find(p => p.player === 'h')!.ownPayment, mutual ? 2 : 0);
assert.equal(quote.payments.find(p => p.player === 'a')!.ownPayment, 2);
}
});
void test('the private source flag is true or absent and does not mutate a rejected quote', () => {
for (const invalid of [false, null, 'true']) {
const input = { ...battle(), nexusCanceledTraitorRevealed: invalid } as unknown as BattleResolutionInput;
const before = structuredClone(input);
assert.throws(() => quoteBattleResolution(input), BattleResolutionQuoteError);
assert.deepEqual(input, before);
}
});
@@ -0,0 +1,98 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createGame, newPlayer, type Game } from '../game/engine';
import { richeseRevealInterruptSupported } from '../game/richese-reveal-interruption';
import { createStrongholdCards } from '../game/stronghold-cards';
import { createTechTokens } from '../game/tech-tokens';
/** These are quote fixtures, not claims that a staged phase is a full game.
* Parent integration and actual physical markers belong to the runtime tests. */
function auction(advanced = false): Game {
const game = createGame('REVEALPHASE', newPlayer('r', 'Richese', 'richese'), advanced, ['choam']);
game.players.push(newPlayer('c', 'CHOAM', 'choam'), newPlayer('e', 'Emperor', 'emperor'));
game.status = 'playing'; game.phase = 3; game.turn = 2;
game.decision = {kind:'auctionPayment', player:'e'};
game.auction = {cards:[], index:0, bid:3, bidder:'e', active:'e', passed:[], opener:0};
return game;
}
function withModules(game: Game, tech: boolean, strongholds: boolean): Game {
if (tech) {
game.techTokens = createTechTokens(game.players);
game.techTokens.axlotl.owner = 'c';
game.techTokens.axlotl.spice = 2;
game.techTokens.axlotl.triggeredTurn = 1;
}
if (strongholds) {
game.strongholdCards = createStrongholdCards();
game.strongholdCards.owners.arrakeen = 'e';
game.strongholdCards.claimedTurn = 1;
}
return game;
}
void test('actual selected phase-module custody admits the existing auction parent without changing it', () => {
for (const [advanced, tech, strongholds] of [
[false, true, false], [true, true, false], [true, false, true], [true, true, true],
] as const) {
const game = withModules(auction(advanced), tech, strongholds);
const before = structuredClone(game);
assert.equal(richeseRevealInterruptSupported(game), true, `${advanced}/${tech}/${strongholds}`);
assert.deepEqual(game, before);
}
});
void test('phase modules admit the previously supported CHOAM market and Emperor gift parents', () => {
for (const strongholds of [false, true]) {
const market = withModules(auction(strongholds), true, strongholds);
market.auction = null;
market.decision = {kind:'choamMarket', player:'c'};
market.choamMarket = {owner:'c', resume:'phase', blocked:[]};
assert.equal(richeseRevealInterruptSupported(market), true);
const gift = withModules(auction(strongholds), true, strongholds);
gift.auction = null; gift.decision = null;
gift.players[2].ally = 'r'; gift.players[0].ally = 'e'; gift.players[2].spice = 5;
gift.response = {kind:'emperorGift', owner:'e', recipient:'r', amount:2, elite:0, passed:[]};
assert.equal(richeseRevealInterruptSupported(gift), true);
}
});
void test('phase modules require valid selected rosters, seat counts and physical component states', () => {
const malformed: Array<(game: Game) => void> = [
game => { game.players.pop(); },
game => { game.players[1].faction = 'richese'; },
game => { game.players[1].faction = 'ixians'; },
game => { delete (game.techTokens as Partial<NonNullable<Game['techTokens']>>).axlotl; },
game => { game.techTokens!.production.owner = 'absent'; },
game => { game.techTokens!.production.spice = -1; },
game => { game.techTokens!.production.triggeredTurn = game.turn + 1; },
];
for (const mutate of malformed) {
const game = withModules(auction(), true, false); mutate(game);
const before = structuredClone(game);
assert.equal(richeseRevealInterruptSupported(game), false);
assert.deepEqual(game, before);
}
for (const mutate of [
(game: Game) => { game.advanced = false; },
(game: Game) => { delete (game.strongholdCards!.owners as Partial<NonNullable<Game['strongholdCards']>['owners']>).arrakeen; },
(game: Game) => { game.strongholdCards!.owners.arrakeen = 'absent'; },
(game: Game) => { game.strongholdCards!.claimedTurn = game.turn + 1; },
]) {
const game = withModules(auction(true), false, true); mutate(game);
assert.equal(richeseRevealInterruptSupported(game), false);
}
});
void test('phase modules do not remove existing child, truth or commitment restrictions', () => {
const cases: Array<(game: Game) => void> = [
game => { game.leaderSkills = {} as NonNullable<Game['leaderSkills']>; },
game => { game.discoveryEnabled = true; },
game => { game.pendingNullentropy = {} as NonNullable<Game['pendingNullentropy']>; },
game => { game.shipmentPromises = [{turn:game.turn, player:'e', asker:'r', answer:true, territory:'carthag', minimum:3}]; },
game => { delete game.truthHistory; },
];
for (const mutate of cases) {
const game = withModules(auction(true), true, true); mutate(game);
assert.equal(richeseRevealInterruptSupported(game), false);
}
});
@@ -0,0 +1,121 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyAction, viewGame, type Game } from '../game/engine';
import { TERRITORIES } from '../game/board';
import { presenceAt } from '../game/force-presence';
import { strongholdControllers, type StrongholdId } from '../game/stronghold-cards';
import {
createMixedPhaseModulesFixture, mixedPhaseModulesClean, mixedPhaseModulesInventory,
mixedPhaseModulesPlayer, nextMixedPhaseModules,
} from './fixture-mixed-phase-modules';
const owner = 'richese';
const seat = mixedPhaseModulesPlayer;
/** Drive only existing public controls; leave a clean current movement turn
* and the target original CHOAM market decision to the actual test. */
function reach(game: Game, until: (state: Game) => boolean): Game {
for (let count = 0; count < 1800; count++) {
if (until(game)) return game;
assert.notEqual(game.status, 'finished', 'The real game ended before its target decision');
const step = nextMixedPhaseModules(game);
assert.ok(step, `Missing native continuation at ${game.turn}/${game.phase}/${game.decision?.kind}`);
game = applyAction(game, step.actor, step.action);
}
throw Error('The native phase-module game did not reach its target');
}
/** Public start, normal setup/phase controls and one paid No-Field shipment.
* Value three goes to the sheltered Polar Sink; zero goes to an empty legal
* stronghold. The shared fixture selects unopened Spice positions only. */
function source(advanced: boolean, tech: boolean, strongholds: boolean, value: 0 | 3 = 3) {
const started = createMixedPhaseModulesFixture({
factions: ['richese', 'choam', 'emperor'], expansions: ['choam'],
advanced, tech, strongholds,
});
let game = started.game;
assert.equal(game.status, 'playing');
assert.equal(game.advanced, advanced);
assert.equal(!!game.techTokens, tech);
assert.equal(!!game.strongholdCards, strongholds);
game = reach(game, state => state.turn === 1 && state.phase === 5 &&
state.active === owner && mixedPhaseModulesClean(state));
const player = seat(game, owner), token = player.noField!.tokens.find(item => item.value === value);
assert.ok(token && player.noFieldEvent);
const shipmentEvent = player.noFieldEvent, beforeSpice = player.spice;
// Shield Wall shelter keeps the original marker safe through the next
// actual Storm; no future storm or faction control is staged.
const destination = value === 0 ? TERRITORIES.find(territory => ['arrakeen','carthag'].includes(territory.id) &&
!territory.sectors.includes(game.storm) && game.players.every(p =>
!Object.entries(p.forces).some(([location, count]) => count > 0 && location.startsWith(`${territory.id}:`)))) :
TERRITORIES.find(territory => territory.id === 'polar_sink');
assert.ok(destination);
const sector = destination.sectors[0];
game = applyAction(game, owner, {type:'ship', noField:token.id, event:shipmentEvent,
territory:destination.id, sector, allyPayment:0});
game = reach(game, state => state.turn === 1 && state.phase === 5 &&
state.active === owner && mixedPhaseModulesClean(state));
assert.equal(seat(game, owner).spice, beforeSpice - (value === 0 ? 1 : 2));
assert.equal(seat(game, owner).noField?.deployed?.tokenId, token.id);
game = applyAction(game, owner, {type:'endMovement'});
game = reach(game, state => state.turn === 2 && state.decision?.kind === 'choamMarket' &&
!state.response && !state.phaseOpening);
const event = seat(game, owner).noFieldEvent;
assert.ok(event && seat(game, owner).noField?.deployed?.tokenId === token.id);
return { game, token: token.id, event, inventory: started.originalInventory, territory: destination.id };
}
for (const options of [
{name:'Basic Tech', advanced:false, tech:true, strongholds:false},
{name:'Advanced Strongholds', advanced:true, tech:false, strongholds:true},
{name:'Advanced Tech and Strongholds', advanced:true, tech:true, strongholds:true},
] as const) void test(`${options.name}: native CHOAM market continues after voluntary No-Field reveal`, () => {
const f = source(options.advanced, options.tech, options.strongholds);
const before = structuredClone(f.game), marker = seat(before, owner);
const decision = structuredClone(before.decision), market = structuredClone(before.choamMarket);
const tech = structuredClone(before.techTokens), strongholds = structuredClone(before.strongholdCards);
assert.equal(viewGame(before, owner).richeseNoField?.canReveal, true);
const after = applyAction(before, owner, {type:'revealNoField', token:f.token, event:f.event});
assert.deepEqual(after.decision, decision);
assert.deepEqual(after.choamMarket, market);
assert.deepEqual(after.techTokens, tech);
assert.deepEqual(after.strongholdCards, strongholds);
assert.equal(seat(after, owner).noField?.deployed, null);
assert.equal(seat(after, owner).reserves, marker.reserves - 3);
assert.equal(seat(after, owner).forces['polar_sink:0'], (marker.forces['polar_sink:0'] ?? 0) + 3);
assert.equal(seat(after, owner).spice, marker.spice);
assert.deepEqual(mixedPhaseModulesInventory(after), f.inventory);
assert.throws(() => applyAction(after, owner, {type:'revealNoField', token:f.token, event:f.event}));
assert.ok(decision?.kind === 'choamMarket');
const continued = applyAction(after, decision.player, {type:'decision', done:true});
assert.notDeepEqual(continued.decision, decision);
assert.equal(seat(continued, owner).forces['polar_sink:0'], 3);
assert.deepEqual(continued.techTokens, tech);
assert.deepEqual(continued.strongholdCards, strongholds);
assert.deepEqual(mixedPhaseModulesInventory(continued), f.inventory);
});
void test('Advanced phase modules keep their claimed card when a zero marker vacates an empty stronghold during CHOAM market', () => {
const f = source(true, true, true, 0);
const before = structuredClone(f.game), decision = structuredClone(before.decision);
const market = structuredClone(before.choamMarket), tech = structuredClone(before.techTokens);
const strongholds = structuredClone(before.strongholdCards), territory = f.territory as StrongholdId;
assert.equal(presenceAt(seat(before, owner), territory), 1);
assert.equal(strongholdControllers(before.players, false)[territory], owner);
assert.equal(strongholds!.owners[territory], owner, 'The earlier actual Mentat claimed the occupied card');
assert.equal(viewGame(before, owner).richeseNoField?.canReveal, true);
const after = applyAction(before, owner, {type:'revealNoField', token:f.token, event:f.event});
assert.equal(presenceAt(seat(after, owner), territory), 0);
assert.equal(strongholdControllers(after.players, false)[territory], null);
assert.equal(seat(after, owner).reserves, seat(before, owner).reserves);
assert.deepEqual(after.decision, decision);
assert.deepEqual(after.choamMarket, market);
assert.deepEqual(after.techTokens, tech);
assert.deepEqual(after.strongholdCards, strongholds, 'Card ownership waits for the normal next Mentat');
assert.deepEqual(mixedPhaseModulesInventory(after), f.inventory);
assert.ok(decision?.kind === 'choamMarket');
const continued = applyAction(after, decision.player, {type:'decision', done:true});
assert.equal(presenceAt(seat(continued, owner), territory), 0);
assert.deepEqual(continued.techTokens, tech);
assert.deepEqual(continued.strongholdCards, strongholds);
});