diff --git a/components/game-table.tsx b/components/game-table.tsx index 5040e0ea..c036550a 100644 --- a/components/game-table.tsx +++ b/components/game-table.tsx @@ -1,6 +1,7 @@ 'use client'; import { SaphoArrivalOrder } from './sapho-arrival-order'; import { SaphoStationPriority } from './sapho-station-priority'; +import { SaphoGreatMakerPriority } from './sapho-great-maker-priority'; import { EmperorExtortionPriority } from './emperor-extortion-priority'; import { EmperorPhaseOpeningPriority } from './emperor-phase-opening-priority'; import { RicheseBidPromisePanel } from './richese-bid-promise-panel'; @@ -397,7 +398,7 @@ export function GameTable({ const harkonnenBetrayalOwnsControls = !!g.nexusHarkonnenBetrayalReaction && !g.response && !g.decision && !g.truthtrance && !g.phaseOpening && !g.automaticContinuationPending && !g.nexusCards?.waiting.length && !g.nexusTraitors?.pending; - const busy = reactionBusy || !!g.saphoStationPriority || !!g.saphoArrivalOrder || !!g.victoryContinuation || !!g.nexusFremenRideBetrayal || g.automaticContinuationPending || !!g.semutaReaction || !!g.kullReaction || !!g.richeseBetrayalReaction || !!g.guildBetrayalReaction || !!g.nexusIxianReplacement || ixianBetrayalOwnsControls || harkonnenBetrayalOwnsControls; + const busy = reactionBusy || !!g.saphoStationPriority || !!g.saphoGreatMakerPriority || !!g.saphoArrivalOrder || !!g.victoryContinuation || !!g.nexusFremenRideBetrayal || g.automaticContinuationPending || !!g.semutaReaction || !!g.kullReaction || !!g.richeseBetrayalReaction || !!g.guildBetrayalReaction || !!g.nexusIxianReplacement || ixianBetrayalOwnsControls || harkonnenBetrayalOwnsControls; const reactionOwnsControls = !!g.saphoArrivalOrder || !!g.nexusFremenRideBetrayal || !!g.kullReaction || !!g.kullCounterEvent || !!g.richeseBetrayalReaction || !!g.guildBetrayalReaction || !!g.nexusIxianReplacement || ixianBetrayalOwnsControls || harkonnenBetrayalOwnsControls; const canSpendKarama = (card: Card, purpose: KullPurpose) => !kullPurposeBlock(g, purpose) && canUseAsKaramaRole(g, me, card); @@ -1545,6 +1546,8 @@ export function GameTable({ {g.emperorExtortionPriority && } {g.saphoStationPriority && } + {g.saphoGreatMakerPriority && } {g.saphoArrivalOrder && g.players.find(player => player.id === id)?.name ?? id} act={act} />} @@ -4069,7 +4072,7 @@ export function GameTable({ ) : g.decision.kind === 'discoveryDiscard' ? ( ) : g.decision.kind === 'greatMakerVote' || g.decision.kind === 'greatMakerRide' ? ( - + ) : g.decision.kind === 'nexusFremenProtection' ? (

@@ -6132,8 +6135,8 @@ export function GameTable({ - diff --git a/components/great-maker.tsx b/components/great-maker.tsx index d4af44c2..72aa6a5b 100644 --- a/components/great-maker.tsx +++ b/components/great-maker.tsx @@ -17,8 +17,9 @@ export function GreatMakerDecision({ game, act, busy }: Props) {

Great Maker · Nexus vote

- Vote in storm order. A majority must vote yes for this encounter to - create a Nexus; a tie means no Nexus. + Voting starts in storm order, subject to available order changes. A + majority must vote yes for this encounter to create a Nexus; a tie + means no Nexus.

{frame.votes.map((vote) => (

diff --git a/components/juice-of-sapho.tsx b/components/juice-of-sapho.tsx index be437860..eac09109 100644 --- a/components/juice-of-sapho.tsx +++ b/components/juice-of-sapho.tsx @@ -12,6 +12,8 @@ function unavailableReason(game: GameView) { return 'Order changes are available during play.'; if (game.phase === 5) return 'Movement order supports clean combined-turn boundaries and queuing behind a started active turn. Your own started turn may be paused at a clean boundary and resumed last, with spent actions retained. Finish pending interactions and preparations first. The Advanced Guild retains its next timing choice; another player cannot displace an already granted Guild turn, and last remains after the Guild. A Karama-locked privilege stays locked. Completed turns and actual shipment and movement counters stay unchanged. Already-held positions and committed cards remain unavailable.'; + if (game.decision?.kind === 'greatMakerVote') + return 'Change your position among the remaining Great Maker votes. Votes already cast remain; you cannot vote twice. This online priority is provisional.'; if (game.truthtrance || game.response || game.phaseOpening || (game.decision && !(game.phase === 8 && game.decision.kind === 'moritaniExtortion'))) return 'Finish the current interaction before changing turn order.'; @@ -68,7 +70,7 @@ export function SaphoOrderButton({ > {option.scope === 'battleAggressor' ? 'Become aggressor and discard Juice of Sapho' : (option.scope === 'movement' || option.scope === 'revival' || option.scope === 'charity') && option.resumeOwn ? `Resume your ${option.scope} last and discard Juice of Sapho` : - `${bidding ? 'Bid' : option.scope === 'battleOrder' ? 'Choose battles' : option.scope === 'extortion' ? 'Take your Extortion choice' : option.scope === 'testingStation' ? 'Take your Testing Station choice' : option.scope === 'revival' ? 'Take your Revival turn' : option.scope === 'charity' ? 'Take your Charity turn' : 'Take your movement turn'} ${option.mode} and discard Juice of Sapho`} + `${bidding ? 'Bid' : option.scope === 'battleOrder' ? 'Choose battles' : option.scope === 'extortion' ? 'Take your Extortion choice' : option.scope === 'testingStation' ? 'Take your Testing Station choice' : option.scope === 'greatMakerVote' ? 'Cast your Great Maker vote' : option.scope === 'revival' ? 'Take your Revival turn' : option.scope === 'charity' ? 'Take your Charity turn' : 'Take your movement turn'} ${option.mode} and discard Juice of Sapho`} ); } @@ -113,6 +115,7 @@ export function JuiceOfSapho({ const aggressor = option.scope === 'battleAggressor'; const extortion = option.scope === 'extortion'; const testingStation = option.scope === 'testingStation'; + const greatMakerVote = option.scope === 'greatMakerVote'; const revival = option.scope === 'revival'; const charity = option.scope === 'charity'; const resumeOwn = (option.scope === 'movement' || revival || charity) && option.resumeOwn; @@ -166,6 +169,8 @@ export function JuiceOfSapho({ ? `Take your Extortion choice ${option.mode} among unanswered players. Earlier declines and Moritani’s five-spice bank collection remain. You may decline instead of paying; the first actual three-spice payment ends all offers.` : testingStation ? `Take your Testing Station choice ${option.mode}. Each occupant still chooses once; their adjustments apply in the selected order to the original storm movement. This priority is provisional.` + : greatMakerVote + ? `Cast your Great Maker vote ${option.mode} among the remaining voters. Votes already cast stay finished; each player still votes once. This priority is provisional.` : cyclic ? `Bid ${option.mode} in the current cyclic lot. Provisional duration: this lot only. Existing bids, funding and passes stay committed. Later circuits use the changed cycle; the next lot returns to its normal opener.` : once diff --git a/components/sapho-great-maker-priority.tsx b/components/sapho-great-maker-priority.tsx new file mode 100644 index 00000000..96c3f526 --- /dev/null +++ b/components/sapho-great-maker-priority.tsx @@ -0,0 +1,35 @@ +'use client'; + +import type { Action } from '@/game/engine'; +import { Button } from './ui/button'; + +/** The opportunity is public; card custody is projected separately to its owner. */ +export type SaphoGreatMakerPriorityView = { + event: string; + canPass: boolean; + waiting: boolean; +}; + +export type SaphoGreatMakerPriorityProps = { + game: { saphoGreatMakerPriority?: SaphoGreatMakerPriorityView | null }; + act: (action: Action) => void; + busy: boolean; +}; + +export function SaphoGreatMakerPriority({ game, act, busy }: SaphoGreatMakerPriorityProps) { + const view = game.saphoGreatMakerPriority; + if (!view) return null; + const event = view.event; + const canAct = () => !busy && game.saphoGreatMakerPriority === view && + view.event === event && typeof event === 'string' && event.length > 0 && view.canPass; + + return

+

Great Maker vote order

+

Before the next vote, players may use an available order change from their own hand. Votes already cast stay finished.

+ {view.canPass ? :

{view.waiting ? 'Waiting for the other players to continue.' : 'Your response has been recorded.'}

} +
; +} diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md index ec35adfa..fcd4314d 100644 --- a/docs/CURRENT_STATUS.md +++ b/docs/CURRENT_STATUS.md @@ -17,6 +17,15 @@ open mode gates. ## Current checkpoint and work +**Sapho and Great Maker votes — 16 November. Prototyped / Partial.** Fresh +supported Discovery games with seated Richese allow a neutral public order +opportunity before each Great Maker vote. An actual Sapho moves an unanswered +voter first/last without changing earlier votes or the majority; supported Semuta +claim/pass retains the original vote. Timing is provisional; other Semuta +variants, full combinations, complete games and deployment remain open. +Twelve related unit files pass 62 cases. +[Scope](JUICE_OF_SAPHO_RUNTIME.md#great-maker-voting--16-november-2026). + **No-Field phase-module windows and CHOAM canceled-Traitor income — 16 November. Prototyped / Partial.** Supported voluntary No-Field reveal interruptions retain valid Tech and Advanced Stronghold components and their diff --git a/docs/JUICE_OF_SAPHO_RUNTIME.md b/docs/JUICE_OF_SAPHO_RUNTIME.md index f0cc019a..9376d9d0 100644 --- a/docs/JUICE_OF_SAPHO_RUNTIME.md +++ b/docs/JUICE_OF_SAPHO_RUNTIME.md @@ -1,5 +1,28 @@ # Juice of Sapho: finite ordering implementation +## Great Maker voting — 16 November 2026 + +**Prototyped / Partial.** Fresh supported Discovery encounters with seated +Richese and the CHOAM deck create a public neutral order opportunity for each +still-pending voter before the next Great Maker vote. A holder may spend the +physical Juice of Sapho to take the first or last remaining vote; already-cast +votes, physical storm order and the strict-majority threshold remain. Every +remaining player can continue without exposing card custody. Each reorder and +vote boundary has a new event; a completed voter cannot vote again. When the +supported Semuta protocol applies, its claim/pass reaction finishes before the +reordered vote and may recover the physical Sapho for another reorder. + +The printed card permits first or last in an ordered action; the neutral online +priority and handling of previously cast votes are provisional implementation +choices, not publisher clarification. Previously opened unstamped encounters +retain their original vote protocol and completed frames retain their original +storm order. Other Semuta preview variants, combinations, complete games and +deployed acceptance remain open. [Native Basic and Advanced journeys](../tests/sapho-great-maker-runtime.test.ts) +use public starts with conserved staged card swaps and unopened Spice order; +[ordering quotes](../tests/sapho-great-maker-quote.test.ts) and +[controls](../tests/sapho-great-maker-priority-controls.test.tsx) cover the +visible opportunity and event-bound actions. + ## Truthtrance order in Advanced Black Market — 16 November 2026 **Prototyped / Partial.** The shared opportunity to reorder simultaneous diff --git a/docs/RULE_DECISIONS.md b/docs/RULE_DECISIONS.md index d0623204..450cb169 100644 --- a/docs/RULE_DECISIONS.md +++ b/docs/RULE_DECISIONS.md @@ -1,5 +1,12 @@ # Rule decision index +## Sapho and Great Maker voting — 16 November 2026 + +The printed first/last ordered-action effect extends to unanswered Great Maker +votes. A neutral public opportunity, preserving completed votes and supporting +the existing Semuta discard response, is a provisional online interpretation. +[Scope](JUICE_OF_SAPHO_RUNTIME.md#great-maker-voting--16-november-2026). + ## No-Field phase modules and CHOAM's canceled Traitor — 16 November 2026 The existing provisional before-Battle No-Field interruption order extends to diff --git a/game/bots.ts b/game/bots.ts index 325fab16..a4614ffb 100644 --- a/game/bots.ts +++ b/game/bots.ts @@ -4382,6 +4382,12 @@ function botAdvisorMatchingAllowed(g:GameView,action:Action) { } catch(error) { if(error instanceof AdvisorMatchingError) return false; throw error; } } export function botActions(g: GameView): Action[] { + if (g.saphoGreatMakerPriority) { + const own = g.players.find(player => player.id === g.me), priority = g.saphoGreatMakerPriority; + return (own?.bot || own?.autopilot) && g.status === 'playing' && priority.canPass && + !g.roomControl?.paused && !g.roomControl?.closed && !g.automaticContinuationPending + ? [{type:'saphoGreatMakerPass', event:priority.event}] : []; + } if (g.emperorGuildRatePriority) { const me = g.players.find(player => player.id === g.me); return (me?.bot || me?.autopilot) && g.emperorGuildRatePriority.canContinue && diff --git a/game/engine.ts b/game/engine.ts index 7b301dd3..be19df85 100644 --- a/game/engine.ts +++ b/game/engine.ts @@ -162,6 +162,7 @@ import { advanceDiscoveryEntry, beginDiscoveryEntryArrival, createDiscoveryEntry import { createDiscoveryState, validateDiscoveryState, placeDiscovery, rememberDiscoveryFace, revealDiscoveryToken, isDiscoverySpiceCardId, isDiscoveryTokenId, DISCOVERY_SPICE_CARDS, DISCOVERY_CARD_PLACEMENTS, DISCOVERY_TOKEN_BY_ID, JACURUTU_SIETCH, type DiscoveryState } from './discoveries'; import { quoteJacurutuBattleIncome, jacurutuDialSelection, type JacurutuDialOffer } from './discovery-battle'; import { greatMakerSignature, greatMakerMajority, validateGreatMaker, type GreatMaker } from './great-maker'; +import { initialSaphoGreatMakerOrder, validateSaphoGreatMaker, saphoGreatMakerEvent, reorderSaphoGreatMaker, SaphoGreatMakerError } from './sapho-great-maker'; import { quoteNexusChoamTrade, validateNexusChoamTrade, nexusChoamTradeSignature, type NexusChoamTrade } from './nexus-choam-trade'; import { quoteNexusChoamInspection, sampleNexusChoamInspection, nexusChoamInspectionSignature, type NexusChoamInspectionReceipt } from './nexus-choam-inspection'; import { quoteNexusMoritaniRetention, nexusMoritaniRetentionSignature, type NexusMoritaniRetentionReceipt } from './nexus-moritani-retention'; @@ -1688,6 +1689,8 @@ export type Game = { ecologicalStorm?: DiscoveryStorm; /** Neutral opportunity before either of two Station occupants chooses. */ saphoStationPriority?: { event: string; passed: string[] }; + /** Public card-independent ordering opportunity before a Great Maker vote. */ + saphoGreatMakerPriority?: { event: string; passed: string[] }; discoveryEnabled?: boolean; discoveries?: DiscoveryState; discoveryStash?: DiscoveryStash; @@ -1836,6 +1839,15 @@ export type Game = { resume: NonNullable['resume']; stateSignature: string; } + | { + kind: 'saphoGreatMakerDiscard'; + player: string; + card: string; + event: string; + mode: 'first' | 'last'; + resume: NonNullable['resume']; + stateSignature: string; + } | { kind: 'saphoAuctionDiscard'; cyclic?: 'normal' | 'blackMarket'; @@ -6703,6 +6715,16 @@ type SaphoStationDiscardContinuation = Extract< NonNullable['continuation'], { kind: 'saphoStationDiscard' } >; +type SaphoGreatMakerDiscardContinuation = Extract< + NonNullable['continuation'], + { kind: 'saphoGreatMakerDiscard' } +>; +function saphoGreatMakerDiscardSignature(g: Game, c: SaphoGreatMakerDiscardContinuation) { + return JSON.stringify({player:c.player,card:c.card,event:c.event,mode:c.mode, + parent:nullentropyParentSignature(g,c.resume,c.event),turn:g.turn,phase:g.phase, + order:g.order,maker:g.greatMaker,spiceSequence:g.spiceSequence,spiceDiscard:g.spiceDiscard, + priority:g.saphoGreatMakerPriority}); +} function saphoStationDiscardSignature(g: Game, c: SaphoStationDiscardContinuation) { return JSON.stringify({player:c.player, card:c.card, event:c.event, mode:c.mode, ...(c.stationReplayPriority ? {stationReplayPriority:true} : {}), @@ -8749,6 +8771,11 @@ function treacheryDiscardIntegrity(g: Game) { semutaOfferSupported(g, c, batch.entries) && c.stateSignature === saphoStationDiscardSignature(g, c), 'The used Juice of Sapho no longer matches its Testing Station choice.'); + } else if (continuation?.kind === 'saphoGreatMakerDiscard') { + const c = continuation; + requireRule(batch.cause === 'sapho:greatMaker' && semutaOfferSupported(g,c,batch.entries) && + c.stateSignature === saphoGreatMakerDiscardSignature(g,c), + 'The used Juice of Sapho no longer matches its Great Maker vote.'); } else if (continuation?.kind === 'saphoMovementDiscard') { const c = continuation, entry = batch.entries[0]; requireRule( @@ -10061,6 +10088,20 @@ function semutaOfferSupported( continuation: NonNullable['continuation'], entries: FreshDiscardBatch['entries'], ) { + if (continuation.kind === 'saphoGreatMakerDiscard') { + const frame = g.greatMaker, decision = continuation.resume.decision; + const use = frame?.saphoOrder?.uses.at(-1); + return g.semutaPreview === true && g.discoveryEnabled === true && !!g.discoveries && + discoveryModeSupported(g) && g.status === 'playing' && g.phase === 1 && + frame?.stage === 'vote' && use?.event === continuation.event && + use.player === continuation.player && use.mode === continuation.mode && + decision?.kind === 'greatMakerVote' && decision.player === frame.order[frame.votes.length] && + decision.event === frame.event && !g.decision && !g.saphoGreatMakerPriority && + !g.response && !g.pendingKarama && !g.phaseOpening && !continuation.resume.response && + !continuation.resume.pendingKarama && !continuation.resume.phaseOpening && + entries.length === 1 && entries[0].publicFace && entries[0].discardedBy === continuation.player && + entries[0].card.id === continuation.card && entries[0].card.effect === 'juiceOfSapho'; + } if (continuation.kind === 'saphoStationDiscard') { const frame = g.ecologicalStorm, decision = continuation.resume.decision, receipt = frame?.sapho; return g.semutaPreview === true && g.discoveryEnabled === true && !!g.discoveries && @@ -10921,6 +10962,12 @@ function finishTreacheryDiscard(g: Game, claim?: { player: string; card: string if (next.stationReplayPriority && g.ecologicalStorm?.stage === 'choose' && g.ecologicalStorm.queue?.choices.length === 0) g.saphoStationPriority = {event:g.ecologicalStorm.event,passed:[]}; + } else if (next.kind === 'saphoGreatMakerDiscard') { + g.response = next.resume.response; + g.decision = next.resume.decision; + g.pendingKarama = next.resume.pendingKarama; + g.phaseOpening = next.resume.phaseOpening; + openSaphoGreatMakerPriority(g); } else if (next.kind === 'saphoMovementDiscard') { g.response = next.resume.response; g.decision = next.resume.decision; @@ -15439,6 +15486,26 @@ function greatMakerRideOptions(g: Game, owner: string) { function stampGreatMaker(g: Game) { g.greatMaker!.signature = greatMakerSignature(g.greatMaker!); } +function saphoGreatMakerRule(run: () => T): T { + try { return run(); } + catch (error) { + if (error instanceof SaphoGreatMakerError) throw new RuleError(error.message); + throw error; + } +} +function saphoGreatMakerContext(g: Game) { + const frame = g.greatMaker!; + // Completed encounters can outlive their turn and its later storm order. + const stormOrder = frame.stage === 'complete' ? frame.saphoOrder?.original ?? frame.order : g.order; + return {encounter:frame.event,turn:frame.turn,stormOrder,queue:frame.order, + cursor:frame.votes.length,...(frame.saphoOrder ? {order:frame.saphoOrder} : {})}; +} +function openSaphoGreatMakerPriority(g: Game) { + const frame = g.greatMaker!; + if (frame.saphoOrder && frame.order.length - frame.votes.length > 1) + g.saphoGreatMakerPriority = {event:saphoGreatMakerRule(() => saphoGreatMakerEvent(saphoGreatMakerContext(g))),passed:[]}; + else delete g.saphoGreatMakerPriority; +} function greatMakerIntegrity(g: Game) { sneakWormIntegrity(g); const frame = g.greatMaker, continuation = g.pendingTreacheryDiscard?.continuation; @@ -15447,11 +15514,21 @@ function greatMakerIntegrity(g: Game) { g.nexusFremenRideBetrayal?.stage === 'choose' ? { decision: g.nexusFremenRideBetrayal.source, response: null } : null]; const owned = controls.filter(control => control?.decision?.kind === 'greatMakerVote' || control?.decision?.kind === 'greatMakerRide'); if (!frame) { - requireRule(owned.length === 0, 'The Great Maker has lost its original encounter.'); + requireRule(owned.length === 0 && !g.saphoGreatMakerPriority, 'The Great Maker has lost its original encounter.'); return; } requireRule(g.discoveryEnabled && g.discoveries, 'The Great Maker requires its physical Discovery module.'); nexusRule(() => validateGreatMaker(frame, g.turn, g.players)); + saphoGreatMakerRule(() => validateSaphoGreatMaker(saphoGreatMakerContext(g))); + if (g.saphoGreatMakerPriority) { + const priority = g.saphoGreatMakerPriority, remaining = frame.order.slice(frame.votes.length); + requireRule(frame.stage === 'vote' && !!frame.saphoOrder && remaining.length > 1 && + priority.event === saphoGreatMakerRule(() => saphoGreatMakerEvent(saphoGreatMakerContext(g))) && + Array.isArray(priority.passed) && priority.passed.length < remaining.length && + new Set(priority.passed).size === priority.passed.length && + priority.passed.every(id => remaining.includes(id)), + 'The Great Maker order opportunity lost its pending voters.'); + } if (frame.stage === 'complete') { requireRule(owned.length === 0, 'The completed Great Maker cannot retain another vote or reserve ride.'); return; @@ -15459,8 +15536,8 @@ function greatMakerIntegrity(g: Game) { if (frame.arrival) requireRule(validGameLocation(g,frame.arrival.territory,frame.arrival.sector), 'The Great Maker has lost its declared reserve destination.'); const card = g.spiceDiscard[frame.pile][frame.index]; requireRule(g.phase === 1 && frame.turn === g.turn && g.spiceSequence?.pile === frame.pile && - card && 'worm' in card && card.greatMaker && !card.suppressed && - frame.order.join('|') === g.order.join('|'), 'The Great Maker has lost its current spice encounter.'); + card && 'worm' in card && card.greatMaker && !card.suppressed, + 'The Great Maker has lost its current spice encounter.'); if (frame.stage === 'vote' || frame.stage === 'ride') { const kind = frame.stage === 'vote' ? 'greatMakerVote' : 'greatMakerRide'; const owner = frame.stage === 'vote' ? frame.order[frame.votes.length] : byFaction(g, 'fremen')?.id; @@ -15500,6 +15577,7 @@ function openGreatMakerVote(g: Game) { const frame = g.greatMaker!; frame.stage = 'vote'; stampGreatMaker(g); g.decision = {kind:'greatMakerVote', player:frame.order[frame.votes.length], event:frame.event}; + openSaphoGreatMakerPriority(g); } function completeGreatMaker(g: Game) { g.greatMaker!.stage = 'complete'; stampGreatMaker(g); @@ -15611,7 +15689,10 @@ function continueSpice(g: Game, injected?: SpiceCard) { g.greatMaker = {arrival:null,event:crypto.randomUUID(),turn:g.turn,pile:sequence.pile, index:g.spiceDiscard[sequence.pile].length-1, territory:previous && 'territory' in previous ? previous.territory : null, - stage:'worm',order:[...g.order],votes:[],ridesBefore:[...g.wormRides],signature:''}; + stage:'worm',order:[...g.order],votes:[],ridesBefore:[...g.wormRides], + ...(g.expansions.includes('choam') && byFaction(g,'richese') && + !g.semutaAdvancedOrdinaryPreview && !g.semutaRecruitsPreview + ? {saphoOrder:initialSaphoGreatMakerOrder(g.order)} : {}),signature:''}; stampGreatMaker(g); if (g.greatMaker.territory) beginWorm(g,g.greatMaker.territory); else openGreatMakerVote(g); @@ -30900,7 +30981,7 @@ function offerMoritaniDuke(g: Game) { return true; } type SaphoOption = { - scope: 'onceAround' | 'cyclicAuction' | 'movement' | 'battleOrder' | 'extortion' | 'revival' | 'charity' | 'testingStation'; + scope: 'onceAround' | 'cyclicAuction' | 'movement' | 'battleOrder' | 'extortion' | 'revival' | 'charity' | 'testingStation' | 'greatMakerVote'; event: string; mode: 'first' | 'last'; /** Display only; action submission keeps scope/event/mode. */ @@ -31148,7 +31229,7 @@ function saphoCleanWindow(g: Game) { !g.truthtrance && !g.phaseOpening && !g.response && - (!g.decision || saphoExtortionDecision(g) || saphoTestingStationDecision(g)) && + (!g.decision || saphoExtortionDecision(g) || saphoTestingStationDecision(g) || !!g.saphoGreatMakerPriority) && !g.pendingNullentropy && !g.pendingRicheseGift && !g.pendingExchange && @@ -31244,6 +31325,17 @@ function saphoOptions(g: Game, p: Player): SaphoOption[] { ) return []; const options: SaphoOption[] = []; + if (g.saphoGreatMakerPriority) { + const frame = g.greatMaker!, priority = g.saphoGreatMakerPriority; + if (!frame.order.slice(frame.votes.length).includes(p.id) || priority.passed.includes(p.id)) return options; + for (const mode of ['first','last'] as const) { + try { + reorderSaphoGreatMaker(saphoGreatMakerContext(g), {event:priority.event,player:p.id,mode}); + options.push({scope:'greatMakerVote',event:priority.event,mode}); + } catch (error) { if (!(error instanceof SaphoGreatMakerError)) throw error; } + } + return options; + } if (saphoTestingStationDecision(g)) { const frame = g.ecologicalStorm!; if (g.saphoStationPriority && @@ -31358,7 +31450,31 @@ function playSapho(g: Game, p: Player, action: Action) { 'This Juice of Sapho opportunity is unavailable, already completed or expired.', ); recordNativePrintedCardPlay(g, p.id, 'juiceOfSapho'); - if (option.scope === 'testingStation') { + if (option.scope === 'greatMakerVote') { + const frame = g.greatMaker!; + const next = saphoGreatMakerRule(() => reorderSaphoGreatMaker(saphoGreatMakerContext(g), + {event:option.event,player:p.id,mode:option.mode})); + frame.order = next.queue; + frame.saphoOrder = next.order; + stampGreatMaker(g); + g.decision = {kind:'greatMakerVote',player:frame.order[frame.votes.length],event:frame.event}; + delete g.saphoGreatMakerPriority; + const used = discard(g,p,'richese-juice-of-sapho'); + log(g, `${p.name} discarded Juice of Sapho to vote ${option.mode} among the remaining Great Maker voters. Earlier votes and the majority rule remain.`, + {faction:p.faction,name:'Juice of Sapho'}); + if (g.semutaPreview) { + const continuation: SaphoGreatMakerDiscardContinuation = {kind:'saphoGreatMakerDiscard', + player:p.id,card:used.id,event:option.event,mode:option.mode, + resume:{response:g.response,decision:g.decision,pendingKarama:g.pendingKarama,phaseOpening:g.phaseOpening}, + stateSignature:''}; + const entries = [{card:used,discardedBy:p.id,publicFace:true}]; + g.decision = null; + requireRule(semutaOfferSupported(g,continuation,entries), + 'This Great Maker vote cannot safely resume its Semuta reaction.'); + continuation.stateSignature = saphoGreatMakerDiscardSignature(g,continuation); + stageTreacheryDiscard(g,'sapho:greatMaker',entries,continuation); + } else openSaphoGreatMakerPriority(g); + } else if (option.scope === 'testingStation') { requireRule(saphoTestingStationDecision(g) && g.ecologicalStorm, 'The original Testing Station choice is no longer open.'); const frame = nexusRule(() => reorderDiscoveryStorm(g, g.ecologicalStorm!, { @@ -45120,6 +45236,26 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi action.scope === 'testingStation' && action.event === priority.event, 'Finish the Testing Station priority before choosing storm movement.'); } + if (state.saphoGreatMakerPriority) { + const priority = state.saphoGreatMakerPriority, frame = state.greatMaker; + greatMakerIntegrity(state); + getPlayer(state, id); + if (action?.type === 'advanceBots') return state; + requireRule(frame?.stage === 'vote' && frame.order.slice(frame.votes.length).includes(id) && + !priority.passed.includes(id), 'This Great Maker ordering opportunity is not available to you.'); + if (action.type === 'saphoGreatMakerPass') { + requireRule(Object.keys(action).sort().join(',') === 'event,type' && action.event === priority.event, + 'Continue only the current Great Maker ordering opportunity.'); + const game = structuredClone(state); + game.saphoGreatMakerPriority!.passed.push(id); + if (game.saphoGreatMakerPriority!.passed.length === frame.order.length - frame.votes.length) + delete game.saphoGreatMakerPriority; + return game; + } + requireRule(action.type === 'card' && action.card === 'richese-juice-of-sapho' && + action.scope === 'greatMakerVote' && action.event === priority.event, + 'Finish the Great Maker ordering opportunity before voting.'); + } if (action.alliancePromiseEvent !== undefined) { const guide = projectedAlliancePromiseGuide(state, id); requireRule(guide && Object.keys(action).sort().join(',') === Object.keys(guide.action).sort().join(',') && @@ -51148,6 +51284,9 @@ export function viewGame(state: Game, id: string, now?: number) { saphoStationPriority: g.saphoStationPriority ? {event:g.saphoStationPriority.event, canPass:!!g.ecologicalStorm?.queue?.order.includes(id) && !g.saphoStationPriority.passed.includes(id), waiting:g.saphoStationPriority.passed.includes(id) || !g.ecologicalStorm?.queue?.order.includes(id)} : null, + saphoGreatMakerPriority: g.saphoGreatMakerPriority ? {event:g.saphoGreatMakerPriority.event, + canPass:!!g.greatMaker?.order.slice(g.greatMaker.votes.length).includes(id) && !g.saphoGreatMakerPriority.passed.includes(id), + waiting:g.saphoGreatMakerPriority.passed.includes(id) || !g.greatMaker?.order.slice(g.greatMaker.votes.length).includes(id)} : null, discoveryEntry: g.discoveryEntry?.stage === 'choose' && g.decision?.kind === 'discoveryEntry' && g.decision.player === id ? {...nexusRule(() => quoteDiscoveryEntry({...g,discoveries:g.discoveries!},g.discoveryEntry!,id)),event:g.decision.event} : null, greatMaker: g.greatMaker ? { event:g.greatMaker.event, turn:g.greatMaker.turn, stage:g.greatMaker.stage, votes:structuredClone(g.greatMaker.votes), order:[...g.greatMaker.order], ride:greatMakerRideOptions(g,id) } : null, diff --git a/game/great-maker-options.ts b/game/great-maker-options.ts index a122c59a..d95ab33e 100644 --- a/game/great-maker-options.ts +++ b/game/great-maker-options.ts @@ -37,7 +37,7 @@ export function greatMakerRideAction( } export function greatMakerBotActions(game: GameView): Action[] { const d = game.decision; - if (!d || d.player !== game.me || game.truthtrance) return []; + if (!d || d.player !== game.me || game.truthtrance || game.saphoGreatMakerPriority) return []; if (d.kind === 'greatMakerVote') return [ { diff --git a/game/great-maker.ts b/game/great-maker.ts index 85f494d2..d8275b14 100644 --- a/game/great-maker.ts +++ b/game/great-maker.ts @@ -1,3 +1,5 @@ +import type { SaphoGreatMakerOrder } from './sapho-great-maker'; + export type GreatMaker = { arrival: { territory: string; @@ -14,10 +16,12 @@ export type GreatMaker = { order: string[]; votes: { player: string; yes: boolean }[]; ridesBefore: string[]; + /** Present only on fresh vote-order-capable encounters. */ + saphoOrder?: SaphoGreatMakerOrder; signature: string; }; export function greatMakerSignature(frame: GreatMaker): string { - return JSON.stringify([ + const values: unknown[] = [ frame.event, frame.turn, frame.pile, @@ -28,7 +32,9 @@ export function greatMakerSignature(frame: GreatMaker): string { frame.votes, frame.ridesBefore, frame.arrival, - ]); + ]; + if (frame.saphoOrder) values.push(frame.saphoOrder); + return JSON.stringify(values); } export function validateGreatMaker( frame: GreatMaker, @@ -38,8 +44,9 @@ export function validateGreatMaker( const ids = players.map((player) => player.id); if ( !frame || - Object.keys(frame).sort().join(',') !== - 'arrival,event,index,order,pile,ridesBefore,signature,stage,territory,turn,votes' || + Object.keys(frame).sort().join(',') !== (frame.saphoOrder + ? 'arrival,event,index,order,pile,ridesBefore,saphoOrder,signature,stage,territory,turn,votes' + : 'arrival,event,index,order,pile,ridesBefore,signature,stage,territory,turn,votes') || typeof frame.event !== 'string' || !frame.event || !Number.isSafeInteger(frame.turn) || diff --git a/game/reference.ts b/game/reference.ts index 9e5064f7..7c28bbb4 100644 --- a/game/reference.ts +++ b/game/reference.ts @@ -516,6 +516,7 @@ export const RULE_TOPICS: RuleTopic[] = [ 'In a fresh Richese battle, use unreserved Sapho at a clean boundary before both combatants finish final battle actions, including after sealed plans and revealed declarations. Habbanya still precedes ordinary aggressor tie priority. Participants, plans, promises, weapon choices and votes do not swap or replay. Older battles retain their pre-plan opportunity.', 'When two or more players declared Truthtrance in a supported clean parent, each queued holder may continue or use their held Sapho to move their entire pending question group first or last. Physical storm order and each holder’s card order stay unchanged. Supported Semuta claim/pass restores the same question queue, including the selected Homeworld, Leader Skills and Discovery profiles. Clean ordinary auction lots also preserve their standing bid and remaining clock. Richese cache Once Around and Silent lots and Advanced Black Market lots preserve their original bidding and funding. Fresh Advanced CHOAM-only Richese games offer Semuta on this Sapho discard and supported definite factual or bid-question Truthtrance discards in those auctions. Other question families and combinations remain unfinished.', 'During a clean native Extortion payer decision, use Sapho to take your optional choice first/last among unanswered non-Moritani players. Earlier declines, collected bank5 and the one-payment3 limit remain. The next payer event changes even when that player stays next. You may decline instead of paying.', + 'During a supported Great Maker vote, a shared public opportunity before each vote lets any remaining voter use Sapho to go first or last, or continue without changing order. Earlier votes and the majority threshold stay unchanged. In supported Semuta games the physical discard response finishes first; a player who recovers Sapho can use it again. The online priority is provisional.', 'Before either of two Ecological Testing Station occupants chooses, use Sapho to take your adjustment first or last if that changes the order. Fresh choices with Richese seated give both occupants a shared opportunity to use an available order change or continue; an automated occupant cannot advance the station choice while another player is deciding. Each occupant still adjusts the cumulative storm distance once. Physical storm order and its original source stay unchanged. In supported Semuta games, claim or pass reopens the shared opportunity; an occupant may use a recovered Sapho again before either choice. This online priority is provisional.', 'During ordered Advanced Charity, take your remaining turn first or last, then discard Sapho. An accepted current claim provisionally protects that actor while another holder reorders only later unstarted turns. At a clean boundary, the holder may pause its own claimed turn and resume last without repeating the claim or payment. Completed turns stay closed and physical First Player order is unchanged. Basic and older concurrent phases have no ordered scope.', 'During ordered Advanced Revival, take your unfinished opportunity first or last, then discard Sapho. If another player has started, provisional queued timing lets that player finish unchanged. At a clean boundary, you may instead pause your own started turn and resume last, retaining used allowances. Pending requests must finish first. Completed turns and already-held positions cannot be repeated. Basic and older concurrent Revival phases have no ordered scope.', diff --git a/game/sapho-great-maker.ts b/game/sapho-great-maker.ts new file mode 100644 index 00000000..9811264e --- /dev/null +++ b/game/sapho-great-maker.ts @@ -0,0 +1,128 @@ +import { reorderOrderedOpportunity } from './ordered-opportunity'; + +/** Public ordering history for the original Great Maker voting encounter. */ +export type SaphoGreatMakerUse = { + event: string; + player: string; + mode: 'first' | 'last'; + cursor: number; +}; +export type SaphoGreatMakerOrder = { + version: 1; + original: string[]; + uses: SaphoGreatMakerUse[]; +}; +export type SaphoGreatMakerContext = { + encounter: string; + turn: number; + stormOrder: readonly string[]; + queue: readonly string[]; + cursor: number; + order?: SaphoGreatMakerOrder; +}; +export type SaphoGreatMakerRequest = { + event: string; + player: string; + mode: 'first' | 'last'; +}; + +export class SaphoGreatMakerError extends Error { + constructor(message: string) { + super(message); + this.name = 'SaphoGreatMakerError'; + } +} +function requireMaker(value: unknown, message: string): asserts value { + if (!value) throw new SaphoGreatMakerError(message); +} +const identifier = (value: unknown): value is string => + typeof value === 'string' && value.trim().length > 0; +const count = (value: unknown): value is number => + typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; +const ids = (value: unknown): value is readonly string[] => + Array.isArray(value) && value.every(identifier) && new Set(value).size === value.length; +const exact = (value: unknown, keys: string): value is Record => + !!value && typeof value === 'object' && !Array.isArray(value) && + [Object.prototype, null].includes(Object.getPrototypeOf(value)) && + Object.keys(value).sort().join(',') === keys; +const same = (left: unknown, right: unknown): boolean => JSON.stringify(left) === JSON.stringify(right); +const eventFor = (encounter: string, turn: number, cursor: number, revision: number): string => + `saphoGreatMaker:${JSON.stringify([encounter, turn, cursor, revision])}`; + +/** Construct only when a new recorded ordering is needed; unmodified older + * encounters need no added field or changed Great Maker signature. */ +export function initialSaphoGreatMakerOrder(stormOrder: readonly string[]): SaphoGreatMakerOrder { + requireMaker(ids(stormOrder) && stormOrder.length >= 2 && stormOrder.length <= 6, + 'Great Maker needs its original unique two-to-six-player storm order.'); + return {version: 1, original: [...stormOrder], uses: []}; +} + +function applyUse(original: readonly string[], queue: readonly string[], use: SaphoGreatMakerUse): string[] { + const remaining = queue.slice(use.cursor); + requireMaker(use.mode === 'first' || use.mode === 'last', 'Choose first or last.'); + requireMaker(identifier(use.player) && remaining.includes(use.player), + 'Only a player who has not yet voted may change position.'); + requireMaker(use.mode === 'first' ? remaining[0] !== use.player : remaining.at(-1) !== use.player, + 'This voter already holds that position.'); + try { + const next = reorderOrderedOpportunity({ + event: use.event, eligible: original, completed: queue.slice(0, use.cursor), + remaining, current: remaining[0] ?? null, currentStarted: false, + }, {event: use.event, player: use.player, position: use.mode}); + return [...next.completed, ...next.remaining]; + } catch (error) { + throw new SaphoGreatMakerError(error instanceof Error ? error.message : 'Invalid Great Maker voter order.'); + } +} + +function validate(context: SaphoGreatMakerContext): string[] { + requireMaker(context && typeof context === 'object' && identifier(context.encounter) && + count(context.turn) && context.turn > 0 && ids(context.stormOrder) && + context.stormOrder.length >= 2 && context.stormOrder.length <= 6, + 'Great Maker needs its original encounter, turn and unique storm order.'); + const original = [...context.stormOrder]; + requireMaker(ids(context.queue) && context.queue.length === original.length && + context.queue.every(player => original.includes(player)) && + count(context.cursor) && context.cursor <= context.queue.length, + 'Great Maker needs its complete voter queue and current vote cursor.'); + if (context.order === undefined) { + requireMaker(same(context.queue, original), + 'A Great Maker queue without a Sapho record must retain its original storm order.'); + return original; + } + const order = context.order; + requireMaker(exact(order, 'original,uses,version') && order.version === 1 && + ids(order.original) && same(order.original, original) && Array.isArray(order.uses), + 'The Sapho vote record must retain its exact original voter order.'); + let queue = [...original], previousCursor = 0; + for (const [revision, use] of order.uses.entries()) { + requireMaker(exact(use, 'cursor,event,mode,player') && count(use.cursor) && + use.cursor >= previousCursor && use.cursor <= context.cursor && + use.event === eventFor(context.encounter, context.turn, use.cursor, revision), + 'Sapho vote history has a stale event, revision or completed voter cursor.'); + queue = applyUse(original, queue, use); + previousCursor = use.cursor; + } + requireMaker(same(context.queue, queue), + 'The Great Maker voter queue does not match its original Sapho history.'); + return original; +} + +export function validateSaphoGreatMaker(context: SaphoGreatMakerContext): void { + validate(context); +} +export function saphoGreatMakerEvent(context: SaphoGreatMakerContext): string { + validate(context); + return eventFor(context.encounter, context.turn, context.cursor, context.order?.uses.length ?? 0); +} +export function reorderSaphoGreatMaker( + context: SaphoGreatMakerContext, + request: SaphoGreatMakerRequest, +): {queue: string[]; order: SaphoGreatMakerOrder} { + const original = validate(context), event = saphoGreatMakerEvent(context); + requireMaker(request && typeof request === 'object' && request.event === event, + 'This Sapho Great Maker opportunity has expired.'); + const use: SaphoGreatMakerUse = {event, player: request.player, mode: request.mode, cursor: context.cursor}; + return {queue: applyUse(original, context.queue, use), + order: {version: 1, original, uses: [...(context.order?.uses ?? []).map(old => ({...old})), use]}}; +} diff --git a/game/table-turn.ts b/game/table-turn.ts index 2fbd2113..405ae6b0 100644 --- a/game/table-turn.ts +++ b/game/table-turn.ts @@ -12,13 +12,13 @@ type TurnView = Pick< | 'phaseOpening' | 'automaticContinuationPending' > & - Partial>; + Partial>; /** The single current decision owner for the table banner and seat highlight. * Shared response windows have no single acting seat. Only public view fields * participate; this does not decide which gameplay actions are legal. */ export function tableActionOwner(g: TurnView): string | null { - if (g.saphoStationPriority || g.emperorExtortionPriority) return null; + if (g.saphoStationPriority || g.saphoGreatMakerPriority || g.emperorExtortionPriority) return null; if (g.richeseBetrayalReaction || g.guildBetrayalReaction) return null; if (g.kullReaction && g.status === 'playing') return g.players.some(p => p.id === g.kullReaction!.player) diff --git a/tests/sapho-great-maker-priority-controls.test.tsx b/tests/sapho-great-maker-priority-controls.test.tsx new file mode 100644 index 00000000..b88e3ac3 --- /dev/null +++ b/tests/sapho-great-maker-priority-controls.test.tsx @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { Children, createElement, isValidElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import type { Action, GameView } from '../game/engine'; +import { SaphoGreatMakerPriority, type SaphoGreatMakerPriorityProps } from '../components/sapho-great-maker-priority'; +import { SaphoOrderButton } from '../components/juice-of-sapho'; + +function props(): SaphoGreatMakerPriorityProps & { sent: Action[] } { + const sent: Action[] = []; + return {game: {saphoGreatMakerPriority: {event:'vote-event', canPass:true, waiting:false}}, + busy:false, sent, act(action) { sent.push(action); }}; +} +const render = (input: SaphoGreatMakerPriorityProps) => + renderToStaticMarkup(createElement(SaphoGreatMakerPriority, input)); + +function pass(input: SaphoGreatMakerPriorityProps) { + const section = SaphoGreatMakerPriority(input); assert.ok(section); + const button = Children.toArray(section.props.children).find(child => + isValidElement(child) && (child.props as {'data-testid'?: string})['data-testid'] === 'sapho-great-maker-priority-pass'); + assert.ok(isValidElement<{onClick: () => void; disabled: boolean}>(button)); + return button; +} + +void test('the public Great Maker order opportunity passes only its exact event', () => { + const input = props(), html = render(input); + assert.match(html, /Great Maker vote order/); + assert.match(html, /Votes already cast stay finished/); + assert.match(html, /Continue without changing vote order/); + assert.equal(pass(input).props.disabled, false); + pass(input).props.onClick(); + assert.deepEqual(input.sent, [{type:'saphoGreatMakerPass', event:'vote-event'}]); +}); + +void test('busy, waiting and completed viewers cannot pass or disclose hidden custody', () => { + for (const waiting of [true, false]) { + const input = props(); + input.game.saphoGreatMakerPriority = {event:'vote-event', canPass:false, waiting}; + Object.assign(input.game, {hiddenCard:'private-card-identity'}); + const html = render(input); + assert.doesNotMatch(html, /sapho-great-maker-priority-pass|private-card-identity/); + assert.match(html, waiting ? /Waiting for the other players/ : /Your response has been recorded/); + } + const input = props(); input.busy = true; + const button = pass(input); assert.equal(button.props.disabled, true); + button.props.onClick(); assert.deepEqual(input.sent, []); + input.game.saphoGreatMakerPriority = null; + assert.equal(render(input), ''); +}); + +void test('stale event, consumed response, replaced priority and empty event cannot send', () => { + for (const change of ['event', 'pass', 'replace', 'close', 'empty'] as const) { + const input = props(), button = pass(input), view = input.game.saphoGreatMakerPriority!; + if (change === 'event') view.event = 'new-event'; + else if (change === 'pass') view.canPass = false; + else if (change === 'replace') input.game.saphoGreatMakerPriority = {...view}; + else if (change === 'close') input.game.saphoGreatMakerPriority = null; + else view.event = ''; + button.props.onClick(); assert.deepEqual(input.sent, []); + } +}); + +void test('own-card order controls submit the quoted Great Maker event and position', () => { + const sent: Action[] = [], act = (action: Action) => { sent.push(action); }; + for (const mode of ['first', 'last'] as const) { + const option = {scope:'greatMakerVote',event:'quoted-event',mode} as NonNullable[number]; + const button = SaphoOrderButton({card:'private-sapho',option,act,busy:false}); + const html = renderToStaticMarkup(button); + assert.match(html, new RegExp(`Cast your Great Maker vote ${mode}`)); + assert.doesNotMatch(html, /private-sapho/); + button.props.onClick(); + const disabled = SaphoOrderButton({card:'private-sapho',option,act,busy:true}); + disabled.props.onClick(); + } + assert.deepEqual(sent, ['first', 'last'].map(mode => ({type:'card',card:'private-sapho', + scope:'greatMakerVote',event:'quoted-event',mode}))); +}); diff --git a/tests/sapho-great-maker-quote.test.ts b/tests/sapho-great-maker-quote.test.ts new file mode 100644 index 00000000..810be885 --- /dev/null +++ b/tests/sapho-great-maker-quote.test.ts @@ -0,0 +1,79 @@ +import assert from 'node:assert/strict'; +import {test} from 'node:test'; +import { + initialSaphoGreatMakerOrder, reorderSaphoGreatMaker, saphoGreatMakerEvent, + SaphoGreatMakerError, validateSaphoGreatMaker, type SaphoGreatMakerContext, +} from '../game/sapho-great-maker'; + +function source(cursor = 0): SaphoGreatMakerContext { + return {encounter:'great-maker-1',turn:2,stormOrder:['a','b','c','d'], + queue:['a','b','c','d'],cursor}; +} +const use = (context: SaphoGreatMakerContext, player: string, mode: 'first' | 'last') => + reorderSaphoGreatMaker(context, {event:saphoGreatMakerEvent(context),player,mode}); + +void test('legacy votes retain physical order without any added history', () => { + const context = source(2), before = structuredClone(context); + validateSaphoGreatMaker(context); + assert.equal(context.order, undefined); + assert.deepEqual(context, before); + assert.deepEqual(initialSaphoGreatMakerOrder(context.stormOrder), + {version:1,original:['a','b','c','d'],uses:[]}); + assert.throws(() => validateSaphoGreatMaker({...context,queue:['a','c','b','d']}), SaphoGreatMakerError); +}); + +void test('first and last change only unanswered voters, preserving their completed prefix', () => { + const first = source(1), firstBefore = structuredClone(first); + const changed = use(first, 'd', 'first'); + assert.deepEqual(changed.queue, ['a','d','b','c']); + assert.deepEqual(changed.order.original, first.stormOrder); + assert.equal(changed.order.uses[0].cursor, 1); + assert.deepEqual(first, firstBefore); + const later = {...first, queue:changed.queue, order:changed.order, cursor:2}; + validateSaphoGreatMaker(later); + const last = use(later, 'b', 'last'); + assert.deepEqual(last.queue, ['a','d','c','b']); + assert.deepEqual(last.queue.slice(0,2), ['a','d']); + validateSaphoGreatMaker({...later,queue:last.queue,order:last.order}); +}); + +void test('recovered Sapho can reorder again with a new event and retained earlier use', () => { + const initial = source(), first = use(initial, 'd', 'first'); + const replay = {...initial,queue:first.queue,order:first.order}; + assert.notEqual(saphoGreatMakerEvent(replay), saphoGreatMakerEvent(initial)); + const second = use(replay, 'd', 'last'); + assert.deepEqual(second.queue, ['a','b','c','d']); + assert.equal(second.order.uses.length, 2); + validateSaphoGreatMaker({...replay,queue:second.queue,order:second.order}); +}); + +void test('stale events, completed voters, no-op choices and malformed scopes reject unchanged', () => { + const context = source(1), before = structuredClone(context), event = saphoGreatMakerEvent(context); + for (const request of [ + {event:'stale',player:'d',mode:'first'}, + {event,player:'a',mode:'last'}, + {event,player:'outsider',mode:'first'}, + {event,player:'b',mode:'first'}, + {event,player:'d',mode:'last'}, + ] as const) assert.throws(() => reorderSaphoGreatMaker(context,request), SaphoGreatMakerError); + assert.deepEqual(context, before); + assert.throws(() => validateSaphoGreatMaker({...context,cursor:5}), SaphoGreatMakerError); + assert.throws(() => validateSaphoGreatMaker({...context,stormOrder:['a','a','c','d']}), SaphoGreatMakerError); + assert.throws(() => initialSaphoGreatMakerOrder(['a']), SaphoGreatMakerError); +}); + +void test('history binds original encounter, revision, cursor and actual resulting queue', () => { + const initial = source(), first = use(initial,'d','first'); + const next = {...initial,queue:first.queue,order:first.order,cursor:1}; + for (const mutate of [ + (c: SaphoGreatMakerContext) => {c.encounter='another';}, + (c: SaphoGreatMakerContext) => {c.turn++;}, + (c: SaphoGreatMakerContext) => {c.queue=['d','b','a','c'];}, + (c: SaphoGreatMakerContext) => {c.order!.uses[0].cursor=1;}, + (c: SaphoGreatMakerContext) => {c.order!.uses[0].player='a';}, + (c: SaphoGreatMakerContext) => {c.order!.original.reverse();}, + ]) { + const broken = structuredClone(next); mutate(broken); + assert.throws(() => validateSaphoGreatMaker(broken), SaphoGreatMakerError); + } +}); diff --git a/tests/sapho-great-maker-runtime.test.ts b/tests/sapho-great-maker-runtime.test.ts new file mode 100644 index 00000000..5ff6587a --- /dev/null +++ b/tests/sapho-great-maker-runtime.test.ts @@ -0,0 +1,250 @@ +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 { botActions } from '../game/bots'; +import { DIFFICULTIES } from '../game/bot-profiles'; +import { nextDiscoveryNoFieldBlow } from './fixture-discovery-no-field-blow'; + +const SAPHO = 'richese-juice-of-sapho'; +const SEMUTA = 'richese-semuta-drug'; +const seat = (game: Game, id: string) => { + const player = game.players.find(row => row.id === id); assert.ok(player); return player; +}; +const act = (game: Game, player: string, action: Action) => applyAction(game, player, action); +const physical = (game: Game) => [ + ...game.deck, ...game.discard, ...(game.richeseCache ?? []), ...(game.richeseRemoved ?? []), + ...(game.removedTreachery ?? []), ...(game.auction?.cards.slice(game.auction.index) ?? []), + ...game.players.flatMap(player => player.hand), +].map(card => card.id).sort(); +function step(game: Game): Game { + const next = nextDiscoveryNoFieldBlow(game); + assert.ok(next, `Native setup/phase continuation missing at ${game.status}/${game.turn}/${game.phase}/${game.decision?.kind}`); + return act(game, next.actor, next.action); +} +function advance(game: Game, until: (game: Game) => boolean): Game { + for (let count = 0; count < 1800; count++) { + if (until(game)) return game; + assert.notEqual(game.status, 'finished', 'Game ended before its Great Maker vote'); + game = step(game); + } + throw Error(`The real Great Maker chronology did not reach its target: ${game.turn}/${game.phase}/${game.decision?.kind}`); +} +function front(game: Game, position: number, testCard: (card: Game['spiceDeck'][number]) => boolean) { + const index = game.spiceDeck.findIndex((card, n) => n >= position && testCard(card)); assert.ok(index >= position); + game.spiceDeck.splice(position, 0, game.spiceDeck.splice(index, 1)[0]); +} +/** Swap a physical Richese cache card for one held card; no new card or hand + * slot is created. This is explicitly staged acquisition, not a purchase. */ +function stageHeld(game: Game, player: string, id: string) { + const target = seat(game, player), cache = game.richeseCache!; + if (target.hand.some(card => card.id === id)) return; + const index = cache.findIndex(card => card.id === id); assert.ok(index >= 0, `${id} must remain in the original cache`); + const replacement = target.hand.pop(); assert.ok(replacement, 'The chosen actual seat has a dealt card to exchange'); + const [card] = cache.splice(index, 1); target.hand.push(card); cache.push(replacement); +} +/** Actual public setup, opt-in Discovery, native turn-one phases, turn-two + * Storm and Great Maker. Only original unopened Spice order and physical + * cache/hand swaps are staged. The first fixture selects Ix+CHOAM decks to + * avoid the separate Semuta protocol; single-CHOAM uses its native protocol. */ +function source(advanced: boolean, mode: 'first' | 'last', semuta = false) { + let game = createGame('SAPHOGREATMAKER', newPlayer('richese', 'Richese', 'richese'), advanced, + semuta ? ['choam'] : ['choam', 'ix']); + for (const [id, faction] of [['atreides', 'atreides'], ['emperor', 'emperor'], ['guild', 'guild']] as const) + joinGame(game, newPlayer(id, faction, faction)); + game = act(game, 'richese', {type:'moduleOption', module:'discoveries', enabled:true}); + for (const player of game.players) game = act(game, player.id, {type:'ready'}); + game = act(game, 'richese', advanced ? {type:'start', advancedPreview:true} : {type:'start'}); + game = advance(game, state => state.status === 'playing'); + assert.equal(game.discoveryEnabled, true); + if (!semuta) assert.ok(!game.semutaPreview && !game.semutaAdvancedOrdinaryPreview && !game.semutaRecruitsPreview); + const original = physical(game); + for (let position = 0; position < (advanced ? 2 : 1); position++) + front(game, position, card => 'territory' in card && !card.discovery); + game = advance(game, state => state.turn === 2 && state.phase === 0); + front(game, 0, card => 'worm' in card && card.greatMaker === true); + for (let position = 1; position <= (advanced ? 2 : 1); position++) + front(game, position, card => 'territory' in card && !card.discovery); + // The public storm order is settled before the ordinary Spice Blow begins. + game = advance(game, state => state.turn === 2 && state.phase === 1 && + !state.greatMaker && !state.spiceResolution && !state.spiceSequence && !state.decision && !state.response); + const holder = mode === 'first' ? game.order.at(-1)! : game.order[0]; + const semutaHolder = game.order.find(id => id !== holder)!; + stageHeld(game, holder, SAPHO); + if (semuta) stageHeld(game, semutaHolder, SEMUTA); + assert.deepEqual(physical(game), original); + game = advance(game, state => state.greatMaker?.stage === 'vote'); + assert.equal(game.decision?.kind, 'greatMakerVote'); + assert.ok(game.saphoGreatMakerPriority, 'The actual Great Maker opens neutral ordering priority'); + assert.deepEqual(game.greatMaker!.order, game.order); + return {game, holder, semutaHolder, original}; +} +function passPriority(state: Game): Game { + let game = state; + for (let count = 0; count < 20 && game.saphoGreatMakerPriority; count++) { + const priority = game.saphoGreatMakerPriority; + const player = game.players.find(row => viewGame(game, row.id).saphoGreatMakerPriority?.canPass); + assert.ok(player, 'An unfinished shared priority has a legal pass owner'); + game = act(game, player.id, {type:'saphoGreatMakerPass', event:priority.event}); + } + assert.equal(game.saphoGreatMakerPriority ?? null, null); + return game; +} +function vote(state: Game, yes: boolean): Game { + const game = passPriority(state), decision = game.decision; + assert.ok(decision?.kind === 'greatMakerVote'); + return act(game, decision.player, {type:'decision', event:decision.event, yes}); +} +function reject(state: Game, player: string, action: Action) { + const before = structuredClone(state); assert.throws(() => act(state, player, action)); assert.deepEqual(state, before); +} +function finishVote(state: Game): Game { + let game = state; + for (let count = 0; count < 10 && game.greatMaker?.stage === 'vote'; count++) + game = vote(game, game.greatMaker.votes.length < 3); + assert.ok(game.greatMaker && game.greatMaker.stage !== 'vote', 'Every original voter must finish exactly once'); + return game; +} + +for (const advanced of [false, true]) for (const mode of ['first', 'last'] as const) void test( + `${advanced ? 'Advanced' : 'Basic'} Great Maker Sapho takes ${mode} among unanswered votes`, () => { + const f = source(advanced, mode); let game = f.game; + const originalOrder = [...game.order], before = structuredClone(game.greatMaker!); + const priority = game.saphoGreatMakerPriority!; + const use: Action = {type:'card', card:SAPHO, scope:'greatMakerVote', event:priority.event, mode}; + reject(game, f.holder, {...use, event:'stale'}); + reject(game, game.order.find(id => id !== f.holder)!, use); + reject(game, f.holder, {type:'saphoGreatMakerPass', event:'stale'}); + game = act(game, f.holder, use); + assert.equal(game.discard.filter(card => card.id === SAPHO).length, 1); + assert.ok(!seat(game, f.holder).hand.some(card => card.id === SAPHO)); + assert.deepEqual(game.order, originalOrder); + assert.deepEqual(game.greatMaker!.votes, before.votes); + assert.equal(mode === 'first' ? game.greatMaker!.order[0] : game.greatMaker!.order.at(-1), f.holder); + assert.ok(game.saphoGreatMakerPriority && game.saphoGreatMakerPriority.event !== priority.event); + reject(game, f.holder, use); + game = finishVote(game); + assert.equal(game.greatMaker!.votes.length, originalOrder.length); + assert.equal(new Set(game.greatMaker!.votes.map(row => row.player)).size, originalOrder.length); + assert.equal(game.greatMaker!.votes.filter(row => row.yes).length, 3); + assert.equal(game.nexus, true); + assert.deepEqual(physical(game), f.original); + }); + +void test('a Semuta claimant can use the recovered physical Sapho again at the new Great Maker priority', () => { + const f = source(false, 'first', true); let game = f.game; + const originalVotes = structuredClone(game.greatMaker!.votes); + const originalPriority = game.saphoGreatMakerPriority!; + game = act(game, f.holder, {type:'card', card:SAPHO, scope:'greatMakerVote', event:originalPriority.event, mode:'first'}); + const discard = game.pendingTreacheryDiscard; assert.ok(discard?.reaction?.stage === 'offer'); + game = act(game, f.semutaHolder, {type:'semutaCommit', event:discard.batch.event}); + assert.equal(game.pendingTreacheryDiscard ?? null, null); + assert.ok(seat(game, f.semutaHolder).hand.some(card => card.id === SAPHO)); + assert.deepEqual(game.greatMaker!.votes, originalVotes); + const nextPriority = game.saphoGreatMakerPriority; assert.ok(nextPriority); + assert.notEqual(nextPriority.event, originalPriority.event); + const secondMode = game.greatMaker!.order.at(-1) === f.semutaHolder ? 'first' : 'last'; + reject(game, f.semutaHolder, {type:'card', card:SAPHO, scope:'greatMakerVote', event:originalPriority.event, mode:secondMode}); + game = act(game, f.semutaHolder, {type:'card', card:SAPHO, scope:'greatMakerVote', event:nextPriority.event, mode:secondMode}); + assert.deepEqual(game.greatMaker!.votes, originalVotes); + assert.equal(secondMode === 'first' ? game.greatMaker!.order[0] : game.greatMaker!.order.at(-1), f.semutaHolder); + assert.ok(game.pendingTreacheryDiscard?.reaction?.stage === 'offer'); + for (let count = 0; count < 10 && game.pendingTreacheryDiscard?.reaction?.stage === 'offer'; count++) { + const pending = game.pendingTreacheryDiscard, reaction = pending.reaction; + assert.ok(reaction?.stage === 'offer'); + const player = game.players.find(row => !reaction.passed.includes(row.id)); + assert.ok(player); game = act(game, player.id, {type:'semutaPass', event:pending.batch.event}); + } + assert.equal(game.pendingTreacheryDiscard ?? null, null); + assert.ok(game.saphoGreatMakerPriority && game.saphoGreatMakerPriority.event !== nextPriority.event); + game = finishVote(game); + assert.equal(new Set(game.greatMaker!.votes.map(row => row.player)).size, game.players.length); + assert.deepEqual(physical(game), f.original); +}); + +void test('all four minimal bots legally pass the neutral Great Maker ordering priority', () => { + const f = source(false, 'first'); + const actor = f.game.players.find(player => player.id !== f.holder && + viewGame(f.game, player.id).saphoGreatMakerPriority?.canPass); + assert.ok(actor); + for (const difficulty of DIFFICULTIES) { + const game = structuredClone(f.game), view = viewGame(game, actor.id); + view.players.find(player => player.id === actor.id)!.bot = difficulty; + const action = botActions(view)[0]; assert.ok(action, difficulty); + assert.equal(action.type, 'saphoGreatMakerPass', difficulty); + const after = act(game, actor.id, action); + assert.ok(after.saphoGreatMakerPriority!.passed.includes(actor.id)); + assert.deepEqual(after.greatMaker!.votes, game.greatMaker!.votes); + assert.deepEqual(physical(after), f.original); + } +}); + +void test('the completed Great Maker order remains valid when the next real storm changes player order', () => { + const f = source(false, 'first'); let game = f.game; + const priority = game.saphoGreatMakerPriority!; + game = act(game, f.holder, {type:'card', card:SAPHO, scope:'greatMakerVote', event:priority.event, mode:'first'}); + game = finishVote(game); + assert.equal(game.greatMaker!.stage, 'complete'); + const maker = structuredClone(game.greatMaker), oldOrder = [...game.order]; + game = advance(game, state => state.turn === 3 && state.phase === 0); + for (let count = 0; count < 100 && game.turn === 3 && game.phase === 0; count++) { + const next = nextDiscoveryNoFieldBlow(game); assert.ok(next); + // The two real Basic storm dials are independently chosen, not staged as + // a board mutation. A six-sector advance passes occupied player circles. + const action = next.action.type === 'stormDial' ? {...next.action, amount:3} : next.action; + game = act(game, next.actor, action); + } + assert.equal(game.turn, 3); assert.equal(game.phase, 1); + assert.notDeepEqual(game.order, oldOrder, 'The native Storm changed the player priority'); + assert.deepEqual(game.greatMaker, maker, 'The completed signed Maker retains its own historical order'); + for (const player of game.players) assert.doesNotThrow(() => viewGame(game, player.id)); + assert.deepEqual(physical(game), f.original); +}); + +void test('a later Sapho choice preserves the already-cast Great Maker vote', () => { + const f = source(false, 'first'); let game = vote(f.game, false); + const prior = structuredClone(game.greatMaker!.votes), initial = [...game.greatMaker!.order]; + assert.equal(prior.length, 1); assert.notEqual(prior[0].player, f.holder); + const priority = game.saphoGreatMakerPriority!; + game = act(game, f.holder, {type:'card', card:SAPHO, scope:'greatMakerVote', event:priority.event, mode:'first'}); + assert.deepEqual(game.greatMaker!.votes, prior); + assert.deepEqual(game.greatMaker!.order.slice(0, 1), initial.slice(0, 1)); + assert.equal(game.greatMaker!.order[1], f.holder); + game = finishVote(game); + assert.equal(game.greatMaker!.votes[0].yes, false); + assert.equal(new Set(game.greatMaker!.votes.map(row => row.player)).size, game.players.length); + assert.deepEqual(physical(game), f.original); +}); + +for (const advanced of [false, true]) for (const claim of [false, true]) void test( + `${advanced ? 'Advanced' : 'Basic'} Great Maker Sapho resumes its vote after Semuta ${claim ? 'claim' : 'passes'}`, () => { + const f = source(advanced, 'first', true); let game = f.game; + const original = structuredClone(game.greatMaker!), priority = game.saphoGreatMakerPriority!; + assert.equal(game.semutaPreview, true); + game = act(game, f.holder, {type:'card', card:SAPHO, scope:'greatMakerVote', event:priority.event, mode:'first'}); + assert.ok(game.pendingTreacheryDiscard?.reaction); + if (claim) { + const reaction = game.pendingTreacheryDiscard!.reaction!; + game = act(game, f.semutaHolder, {type:'semutaCommit', event:game.pendingTreacheryDiscard!.batch.event}); + assert.ok(reaction.stage === 'offer'); + } + for (let count = 0; count < 10 && game.pendingTreacheryDiscard?.reaction?.stage === 'offer'; count++) { + const pending = game.pendingTreacheryDiscard, reaction = pending.reaction; + assert.ok(reaction?.stage === 'offer'); + const player = game.players.find(row => !reaction.passed.includes(row.id)); + assert.ok(player); game = act(game, player.id, {type:'semutaPass', event:pending.batch.event}); + } + // The native claim control selects the offered discarded card when asked. + if (game.pendingTreacheryDiscard?.reaction?.stage === 'select') { + const pending = game.pendingTreacheryDiscard; + const reaction = pending.reaction; + assert.ok(reaction?.stage === 'select'); + game = act(game, reaction.player, {type:'semutaSelect', event:pending.batch.event, card:SAPHO}); + } + assert.equal(game.pendingTreacheryDiscard ?? null, null); + assert.equal(game.greatMaker!.event, original.event); + assert.deepEqual(game.greatMaker!.votes, original.votes); + assert.ok(game.saphoGreatMakerPriority); + game = finishVote(game); + assert.equal(new Set(game.greatMaker!.votes.map(row => row.player)).size, game.players.length); + assert.deepEqual(physical(game), f.original); + }); diff --git a/tests/sapho-station-priority.test.ts b/tests/sapho-station-priority.test.ts index 46f1cfc6..d6c40b57 100644 --- a/tests/sapho-station-priority.test.ts +++ b/tests/sapho-station-priority.test.ts @@ -63,6 +63,13 @@ for (const advanced of [false, true]) void test( assert.equal(game.ecologicalStorm?.owner, fixture.holder); game = finishDiscard(game); assert.equal(game.discard.filter(card => card.id === SAPHO).length, 1); + // The supported Semuta continuation reopens the shared ordering chance + // before either occupant chooses, even when every reaction passed. + if (game.saphoStationPriority) { + const replay = game.saphoStationPriority.event; + for (const id of game.ecologicalStorm!.queue!.order) + game = applyAction(game, id, {type:'saphoStationPass', event:replay}); + } const choice = discoveryStormActions(viewGame(game, fixture.holder)).find(action => action.delta === 0); assert.ok(choice); game = applyAction(game, fixture.holder, choice);