From bd8377d87bf6a21181af556fffb150f92f2c9dc2 Mon Sep 17 00:00:00 2001 From: Quintine <15965533+Quintine@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:49:48 +1100 Subject: [PATCH] Support current battle choice promises and persistent notices --- app/page.tsx | 52 +++-- components/actionable-notice.tsx | 18 ++ components/turn-action-fields.tsx | 38 +++- components/turn-action-promises.tsx | 9 +- docs/CURRENT_STATUS.md | 10 + docs/RULE_DECISIONS.md | 9 + docs/TRUTHTRANCE_TURN_ACTIONS.md | 16 ++ game/engine.ts | 49 ++++- game/reference.ts | 1 + game/truthtrance.ts | 13 +- game/turn-action-promises.ts | 90 +++++++- lib/actionable-notices.ts | 20 ++ tests/actionable-notice-queue.test.tsx | 49 +++++ ...-turn-action-battle-choice-runtime.test.ts | 193 ++++++++++++++++++ ...urn-action-battle-choice-controls.test.tsx | 75 +++++++ tests/turn-action-battle-choice-quote.test.ts | 74 +++++++ 16 files changed, 684 insertions(+), 32 deletions(-) create mode 100644 components/actionable-notice.tsx create mode 100644 lib/actionable-notices.ts create mode 100644 tests/actionable-notice-queue.test.tsx create mode 100644 tests/truth-turn-action-battle-choice-runtime.test.ts create mode 100644 tests/turn-action-battle-choice-controls.test.tsx create mode 100644 tests/turn-action-battle-choice-quote.test.ts diff --git a/app/page.tsx b/app/page.tsx index f2368be5..50fd9f51 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,6 +1,7 @@ 'use client'; -import { useState, useEffect, useCallback, useRef } from 'react'; +import { useState, useEffect, useCallback, useReducer, useRef } from 'react'; import { TableTalk } from '@/components/table-talk'; +import { ActionableNotice } from '@/components/actionable-notice'; import { RemovedRoomNotice } from '@/components/removed-room-notice'; import { GameTable } from '@/components/game-table'; import { SeatConfirmation, type SeatConfirmationKind } from '@/components/seat-confirmation'; @@ -10,6 +11,7 @@ import { TwoPlayerControls } from '@/components/two-player-controls'; import { FactionAllocation } from '@/components/faction-allocation'; import { FactionSwap } from '@/components/faction-swap'; import { randomId } from '@/lib/random-id'; +import { initialActionableNotices, updateActionableNotices } from '@/lib/actionable-notices'; import { SeatHandoverSetup, SeatHandoverClaim, @@ -87,7 +89,10 @@ export default function Home() { const [expansions, setExpansions] = useState([]); const [name, setName] = useState(''); const [code, setCode] = useState(''); - const [notice, setNotice] = useState(''); + const [noticeQueue, updateNoticeQueue] = useReducer(updateActionableNotices, initialActionableNotices); + const notice = noticeQueue.items[0] ?? null; + const setNotice = useCallback((text: string) => updateNoticeQueue({type:'enqueue',text}), []); + const dismissNotice = useCallback((id: number) => updateNoticeQueue({type:'dismiss',id}), []); const [seatConfirmation, setSeatConfirmation] = useState(null); const [entryConfirmation, setEntryConfirmation] = useState<{ kind: 'create' | 'join'; code: string } | null>(null); const seatClaimUncertain = useRef(false); @@ -113,7 +118,7 @@ export default function Home() { removedRooms.current.add(room); ++epoch.current; recovery.current = null; botAttempt.current = null; - setRemovedRoom(room); setNeedsReconcile(false); setBotRecovery(false); setConnection(''); setNotice(''); + setRemovedRoom(room); setNeedsReconcile(false); setBotRecovery(false); setConnection(''); }, []); useEffect(() => subscribeRoomRemoval(markRoomRemoved), [markRoomRemoved]); // This function is deliberately GET-only, including WebMCP reads and recovery. @@ -352,7 +357,7 @@ export default function Home() { return () => { live = false; }; - }, [refresh]); + }, [refresh, setNotice]); useEffect(() => { if (!roomCode || removedRoom === roomCode) return; @@ -399,7 +404,6 @@ export default function Home() { return; const requestEpoch = ++epoch.current; mutationPending.current = true; - setNotice(''); setBusy(true); try { const data = await requestJson(roomEntryUrl(attempt), { @@ -535,7 +539,6 @@ export default function Home() { setEntryConfirmation(null); setRemovedRoom(null); setRestoreFailed(false); - setNotice(''); window.history.replaceState(null, '', '/'); } @@ -575,7 +578,6 @@ export default function Home() { requestEpoch = epoch.current; mutationPending.current = true; setBusy(true); - setNotice(''); try { const data = await requestJson(`/api/rooms/${room}`, { method: 'POST', @@ -633,7 +635,6 @@ export default function Home() { setGame(null); setRestoring(true); setRestoreFailed(false); - setNotice(''); void refresh(room, true).catch((error: Error) => { if (activeRoom.current === room && activeSeat.current === seat) { setRestoreFailed(true); @@ -649,7 +650,6 @@ export default function Home() { const requestEpoch = epoch.current; mutationPending.current = true; setBusy(true); - setNotice(''); let responseReceived = false; try { const data = await requestJson(`/api/rooms/${attempt.room}`, { @@ -727,7 +727,6 @@ export default function Home() { const data = await refresh(room, true); if (restoreFailed && activeRoom.current === room) { setRestoreFailed(false); - setNotice(''); } if (resumeBots) await advanceBots(data, true); } catch (error) { @@ -799,7 +798,6 @@ export default function Home() { setNeedsReconcile(false); setRestoreFailed(false); setConnection(''); - setNotice(''); return true; } useEffect(() => { @@ -837,6 +835,7 @@ export default function Home() { if (showHandover) return (
+ window.location.reload()} onRestored={(view) => { @@ -930,14 +929,14 @@ export default function Home() { /> - {!roomUnavailable && (notice || connection || needsReconcile || botRecovery) && ( - - {notice && {notice}} - {connection && {connection}} - {needsReconcile && ( + {(notice || (!roomUnavailable && (connection || needsReconcile || botRecovery))) && ( +
+ + {!roomUnavailable && connection && {connection}} + {!roomUnavailable && needsReconcile && ( Actions paused until the current table is confirmed. )} - {(connection || needsReconcile) && ( + {!roomUnavailable && (connection || needsReconcile) && ( )} - - +
)} ); @@ -976,7 +972,7 @@ export default function Home() { DUNEARRAKIS TABLE - {removedRoom ? void reconnect()} onExit={() => { removedRooms.current.delete(removedRoom); activeRoom.current = null; activeSeat.current = null; ++epoch.current; setRestoreFailed(false); setRemovedRoom(null); setConnection(''); setNotice(''); window.history.replaceState(null, '', '/'); }} /> :
+ {removedRoom ? void reconnect()} onExit={() => { removedRooms.current.delete(removedRoom); activeRoom.current = null; activeSeat.current = null; ++epoch.current; setRestoreFailed(false); setRemovedRoom(null); setConnection(''); window.history.replaceState(null, '', '/'); }} /> :

{restoring ? 'Restoring your table' @@ -985,8 +981,9 @@ export default function Home() { {restoring ? 'Checking your saved seat and the latest game state…' - : connection || notice} + : connection} + {restoreFailed && !restoring && ( <>

@@ -1006,7 +1003,6 @@ export default function Home() { activeRoom.current = null; setRestoreFailed(false); setConnection(''); - setNotice(''); }} > Open join form @@ -1014,6 +1010,7 @@ export default function Home() { )}

} + {removedRoom && }
); // A first request is progress, not recovery. Keep the actionable recovery @@ -1027,6 +1024,7 @@ export default function Home() {

{entryAttempt.kind === 'create' ? 'Creating your room…' : 'Joining the room…'}

Please wait. +
); @@ -1063,7 +1061,7 @@ export default function Home() { not start a new attempt. No request is retried automatically.

{entryProblem &&

{entryProblem}

} - {notice && {notice}} + {entryAttempt && ( + ; +} diff --git a/components/turn-action-fields.tsx b/components/turn-action-fields.tsx index a56f913e..3a29e02f 100644 --- a/components/turn-action-fields.tsx +++ b/components/turn-action-fields.tsx @@ -31,6 +31,16 @@ const leaders = (game: GameView, target: string) => { const currentLot = (game: GameView) => game.bidPromiseLot?.turn === game.turn ? game.bidPromiseLot : null; const partners = (game: GameView, target: string) => game.players.some(player => player.id === target) ? game.players.filter(player => player.id !== target) : []; +/** Public unresolved pairs only; the current chooser owns exactly one choice. */ +const currentBattleChoices = (game: GameView, respondent: string) => { + if (game.status !== 'playing' || game.phase !== 6 || game.battle || + game.active !== respondent || !game.battleOrder?.event) return []; + return game.battleChoices.filter(choice => choice.chooser === respondent && + [choice.attacker, choice.defender].includes(respondent)).map(choice => ({ + source: game.battleOrder!.event, territory: choice.territory, + target: choice.attacker === respondent ? choice.defender : choice.attacker, + })); +}; const currentNexus = (game: GameView, target: string) => game.status === 'playing' && game.phase === 1 && game.nexus && !game.spiceWindow && game.alliancePromiseNexus?.turn === game.turn && game.truthMixedAllianceTargets.includes(target) && !game.response && !game.decision && !game.phaseOpening && !game.automaticContinuationPending; @@ -95,6 +105,7 @@ const config: MixedActionConfig = { A remaining alliance condition settles at the actual close; forming an alliance does not fulfill it early. No can allow temporary membership followed by a break before the close. You cannot promise another player's consent. Battle-plan conditions concern one actual native plan in this current battle, including a plan already sealed or revealed. + Battle-choice conditions concern the chooser’s next actual selection from the current unresolved pairs, before either plan. An open plan commitment settles when both plans are revealed, not merely when your own plan is sealed. Traitor conditions concern one original Reveal or decline declaration in the current revealed battle. The declaration counts before a later Karama or betrayal response can prevent its effect. @@ -168,6 +179,9 @@ const config: MixedActionConfig = { throw new Error('Choose a public native leader for the respondent’s faction.'); if (action.kind === 'alliance' && (!currentNexus(game, target) || !partners(game, target).some(partner => partner.id === action.partner))) throw new Error('Choose a public other partner during the current open Nexus.'); + if (action.kind === 'battleChoice' && !currentBattleChoices(game, target).some(choice => + choice.source === action.source && choice.territory === action.territory && choice.target === action.target)) + throw new Error('Choose one of the respondent’s actual current unresolved battles.'); if (action.kind === 'battlePlan' || action.kind === 'traitorCall') { const battle = currentBattle(game, target, action.kind); if (!battle || action.battle !== battle.event || action.territory !== battle.territory) @@ -188,6 +202,7 @@ const config: MixedActionConfig = { }, renderAction: ({ value, id, game, target, disabled, onChange }) => { const choices = recipients(game, target), leaderChoices = leaders(game, target), lot = currentLot(game), partnerChoices = partners(game, target); + const battleChoices = currentBattleChoices(game, target); const currentPower = value.kind === 'battlePower' ? powerOpportunity(game, target, value.claim) : null; const currentWindow = value.kind === 'windowCardPlay' ? windowOpportunity(game, target, value.effect) : null; @@ -212,6 +227,8 @@ const config: MixedActionConfig = { const claim = newPowerClaim(game, target), opportunity = powerOpportunity(game, target, claim); onChange({ kind, battle: opportunity?.event ?? '', territory: opportunity?.territory ?? '', claim }); } + if (kind === 'battleChoice') onChange({kind, source:battleChoices[0]?.source ?? '', + territory:battleChoices[0]?.territory ?? '', target:battleChoices[0]?.target ?? ''}); if (kind === 'battlePlan') onChange({ kind, battle: game.battle?.event ?? '', territory: game.battle?.territory ?? '', claim: { kind: 'dial', compare: 'eq', value: 0 } }); if (kind === 'traitorCall') onChange({ kind, battle: game.battle?.event ?? '', territory: game.battle?.territory ?? '', call: true }); @@ -227,6 +244,7 @@ const config: MixedActionConfig = { + @@ -237,7 +255,25 @@ const config: MixedActionConfig = { - {value.kind === 'stormDial' ? (() => { + {value.kind === 'battleChoice' ? <> + + +

Only this chooser’s actual next selection counts; later battles and another player’s choice do not.

+ : value.kind === 'stormDial' ? (() => { const opportunity = nativeStormDialOpportunity(game, target, value.source); return <>

The respondent’s original current Storm dial counts once. Other dials remain sealed until reveal.

diff --git a/components/turn-action-promises.tsx b/components/turn-action-promises.tsx index 786d0858..d5bf0ae6 100644 --- a/components/turn-action-promises.tsx +++ b/components/turn-action-promises.tsx @@ -57,6 +57,7 @@ export function TurnActionGuideButton(props: TurnActionProps) { if (!guide) return null; const actor = game.me, turn = game.turn, phase = game.phase, event = guide.event, action = guide.action; const act = props.act, fillPlan = props.fillPlan, battle = game.battle; + const chooserSource = action.type === 'chooseBattle' ? game.battleOrder?.event : null; const charity = game.charity; const charityOwner = action.type === 'charity' ? game.players.find(player => player.id === actor) : undefined; const charitySource = (current: GameView) => { @@ -504,6 +505,11 @@ export function TurnActionGuideButton(props: TurnActionProps) { const battlePreparation = genericCard && planWindow; const declaration = action.type === 'traitorCall' && typeof action.call === 'boolean' && !!battle && currentBattle && battle.revealed && battle.traitorVoters.includes(actor) && !battle.traitorSubmitted.includes(actor); + const chooseBattle = action.type === 'chooseBattle' && phase === 6 && !current.battle && + current.active === actor && !!chooserSource && current.battleOrder?.event === chooserSource && + Object.keys(action).every(key => ['type','territory','target','turnActionPromiseEvent','turnActionPromisePhase'].includes(key)) && + current.battleChoices.some(choice => choice.chooser === actor && choice.territory === action.territory && + (choice.attacker === actor ? choice.defender : choice.attacker) === action.target); const charityClaim = action.type === 'charity' && phase === 2 && !!me && me === charityOwner && Object.keys(action).every(key => ['type', 'turnActionPromiseEvent', 'turnActionPromisePhase'].includes(key)) && !current.ready.includes(actor) && me.charityClaimed === false && current.charity === charity && @@ -523,7 +529,7 @@ export function TurnActionGuideButton(props: TurnActionProps) { Object.keys(action).every(key => ['type', 'amount', 'turnActionPromiseEvent', 'turnActionPromisePhase'].includes(key)) && typeof action.amount === 'number' && Number.isSafeInteger(action.amount) && action.amount >= stormDialSource.min && action.amount <= stormDialSource.max; - const opportunity = currentStormDial || nativeSemuta || printedResidual || printedDistrans || printedSapho || printedBox || openingReady || earlyWindowReady || earlyWindowBox || printedWindow || ownedPower || payment || paidBox || printedHajr || printedGhola || plan || battlePreparation || declaration || nexusWindow && (ownedAlliance || action.type === 'ready') || (phase === 2 + const opportunity = currentStormDial || nativeSemuta || printedResidual || printedDistrans || printedSapho || printedBox || openingReady || earlyWindowReady || earlyWindowBox || printedWindow || ownedPower || payment || paidBox || printedHajr || printedGhola || plan || battlePreparation || declaration || chooseBattle || nexusWindow && (ownedAlliance || action.type === 'ready') || (phase === 2 ? charityClaim || !current.ready.includes(actor) && (action.type === 'ready' || genericCard) : phase === 3 ? invoice || nativePass || requiredBid || action.type === 'passBid' && !current.richeseAuction && currentAuction && current.auction?.active === actor @@ -585,6 +591,7 @@ export function TurnActionGuideButton(props: TurnActionProps) { : action.type === 'move' && flightInitial ? `Declare Ornithopter ${action.ornithopter === 'range3' ? 'three-territory' : 'two-group'} flight and move ${amount} physical forces to ${destination}${sector} while honoring your whole answer` : action.type === 'card' && windowEffect ? `Play ${windowRoleNames[windowEffect]} in its original native window${windowEffect === 'weather' ? ` with storm distance ${amount}` : ''} while honoring your whole answer` : action.type === 'battlePlan' ? 'Fill the quoted battle plan for review before sealing' + : action.type === 'chooseBattle' ? `Choose the battle against ${recipient} in ${destination} while honoring your whole answer` : action.type === 'voice' ? `Declare native Voice: opponent ${action.must ? 'must' : 'cannot'} play ${battleCardLabel(String(action.kind))}` : action.type === 'prescience' ? `Request the ${String(action.field)} field with native Prescience while honoring your whole answer` : action.type === 'declineBattlePower' ? `Explicitly decline native ${power === 'voice' ? 'Voice' : 'Prescience'} while honoring your whole answer` diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md index fcd4314d..8417ac7a 100644 --- a/docs/CURRENT_STATUS.md +++ b/docs/CURRENT_STATUS.md @@ -17,6 +17,16 @@ open mode gates. ## Current checkpoint and work +**Current battle-choice Truthtrance and persistent notices — 16 November. +Prototyped / Partial.** Supported combined current-turn questions can bind the +current native battle chooser to a specific legal territory and opponent, with +shared guidance for combined and separate commitments. This online +interpretation is provisional; other profiles, full games and deployment +remain open. [Scope](TRUTHTRANCE_TURN_ACTIONS.md#current-battle-choice--16-november-2026). +In the local client, distinct action notices queue until Continue, including +through room navigation and handover; they are not persisted across a reload. +Browser and deployed acceptance remain open. + **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 diff --git a/docs/RULE_DECISIONS.md b/docs/RULE_DECISIONS.md index 450cb169..98253997 100644 --- a/docs/RULE_DECISIONS.md +++ b/docs/RULE_DECISIONS.md @@ -98,6 +98,15 @@ declarations. Its separate ledger preserves all existing ordinary-only `phaseBid` receipts. Funding forecasts and online timing are provisional. [Scope](TRUTHTRANCE_BID_PROMISES.md#all-auction-phase-bid--16-november-2026). +## Truthtrance and the current battle choice — 16 November 2026 + +The GF9 November 2020 FAQ, p. 8, permits a current-turn commitment and ends it +if compliance becomes impossible. Applying that rule to the currently available +native battle choice, including the original event identity and handling of a +lost opportunity, is a provisional online interpretation. It does not promise +a later battle choice or certify wider interaction coverage. See +[the scoped implementation](TRUTHTRANCE_TURN_ACTIONS.md#current-battle-choice--16-november-2026). + ## Advanced Black Market Truthtrance order — 16 November 2026 The existing provisional Sapho order for simultaneous questions extends to diff --git a/docs/TRUTHTRANCE_TURN_ACTIONS.md b/docs/TRUTHTRANCE_TURN_ACTIONS.md index 6798ad81..9d70fc31 100644 --- a/docs/TRUTHTRANCE_TURN_ACTIONS.md +++ b/docs/TRUTHTRANCE_TURN_ACTIONS.md @@ -1,5 +1,21 @@ # Truthtrance combined current-turn actions +## Current battle choice — 16 November 2026 + +**Prototyped / Partial.** At a supported current battle-choice opportunity, +a combined current-turn question can name the native chooser's actual +territory and opposing player. Yes requires that choice while it remains +possible; No forbids it. AND/OR conditions and separate live commitments share +the existing legal-completion guide. A choice is tied to its original public +event, not to a later battle, and the actual native choice settles it. Human +controls and the minimal bot guide use that same event and legal choices. + +The general current-turn question and impossibility rule come from the GF9 +November 2020 FAQ, p. 8; this online event-specific enforcement and source-loss +handling are provisional interpretations. The runtime smoke uses a Basic +three-army native choice and conserved physical Truthtrance cards. Other +profiles, full interactions, complete games and deployed acceptance remain open. + ## Tleilaxu special Karama during Revival — 29 October 2026 **Prototyped / Partial.** A whole-turn question may name Tleilaxu's diff --git a/game/engine.ts b/game/engine.ts index be19df85..3d1ea535 100644 --- a/game/engine.ts +++ b/game/engine.ts @@ -55,6 +55,7 @@ import { TurnActionError, liveTurnActionPromises, turnActionBranches, recordTurn closeTurnActionRevival, settleTurnActionAlliance, recordTurnActionPlan, recordTurnActionTraitor, closeTurnActionCombat, recordTurnActionBattlePower, closeTurnActionBattlePower, recordTurnActionWindowCardPlay, closeTurnActionWindowCardPlay, + recordTurnActionBattleChoice, closeTurnActionBattleChoice, recordTurnActionStormDial, closeTurnActionStormDial, turnActionStormDialChoices, turnActionPromiseModeSupported, type TurnActionPlanValue, type TurnActionCombat, type TurnActionClaim, type TurnActionPromise, type TurnActionBranchLeaf, type TurnActionPreparation, type TurnActionWindowCards } from './turn-action-promises'; import { TravelPromiseError, liveTravelPromises, travelBranches, recordTravelShipment, recordTravelMovement, @@ -24302,6 +24303,16 @@ function turnActionTargetAvailable(g: Game, actor: string): boolean { !bribeTimingBlock({ ...context, truthtrance: null, response: battleCancel ? null : context.response, inflation: context.inflation?.side === 'double' ? null : context.inflation }); } +/** The current chooser's real unresolved pairs; independent of the private + * Truthtrance window, which may temporarily suspend this public opportunity. */ +function turnActionBattleChoiceOpportunity(g: Game, actor: string) { + if (g.status !== 'playing' || g.phase !== 6 || g.battle || g.active !== actor) return null; + const source = battleChooserEvent(g.turn, battleOrderAfterBattle(g), g.battleOrder?.uses.length ?? 0); + const choices = battleOrderQuote(g).choices.filter(choice => choice.chooser === actor).map(choice => ({ + territory:choice.territory,target:choice.attacker === actor ? choice.defender : choice.attacker, + })); + return choices.length ? {source,choices} : null; +} /** Whole native commitments retain the existing Semuta discard continuation. * This does not expand the separate legacy bribe or Kull/module envelopes. */ function turnActionPromiseTurn(g: Game): boolean { @@ -24542,7 +24553,7 @@ function turnActionAllianceCanClose(g: Game, player: Player): boolean { return !!turnActionCompletion(source, player.id); } catch (error) { if (error instanceof RuleError) return false; throw error; } } -type TurnActionCompletion = MovementCompletion & { stormDial?: Action; payments: Action[]; paymentsAfterPreparations?: boolean; bid?: Action; revival?: RevivalPromisePlan; alliance?: Action[]; battlePlan?: BattleCompletion; traitor?: Action; cardPreparations?: Action[]; battlePower?: Action; freshDiscard?: Action }; +type TurnActionCompletion = MovementCompletion & { stormDial?: Action; payments: Action[]; paymentsAfterPreparations?: boolean; bid?: Action; revival?: RevivalPromisePlan; alliance?: Action[]; battleChoice?: Action; battlePlan?: BattleCompletion; traitor?: Action; cardPreparations?: Action[]; battlePower?: Action; freshDiscard?: Action }; /** Forecast deterministic opening work only. Auction/deck draws and foreign * choices stay at the real table; fixed Mentat receipts arrive after Amal. */ function projectTurnActionOpeningEnd(g: Game) { @@ -24708,6 +24719,7 @@ function turnActionCompletionAfterFreshDiscard(source: Game, actor: string, unkn return null; } const dialLeaves = leaves.filter((leaf): leaf is Extract => leaf.kind === 'stormDial'); + const choiceLeaves = leaves.filter((leaf): leaf is Extract => leaf.kind === 'battleChoice'); const dialOpportunity = dialLeaves.length ? nativeStormDialOpportunity(source, actor) : null; if (dialLeaves.length && (!dialOpportunity || dialLeaves.some(leaf => leaf.source !== dialOpportunity.source))) return null; const dialValues = dialOpportunity ? turnActionStormDialChoices(dialLeaves, dialOpportunity.source) : []; @@ -24840,6 +24852,11 @@ function turnActionCompletionAfterFreshDiscard(source: Game, actor: string, unkn source.phaseOpening ? windowRequirements.filter(required => required.effect !== 'amal') : windowRequirements, prepareAlliance)) { const funded = cardSeed.game, payer = getPlayer(funded, actor); try { + const opportunity = choiceLeaves.length ? turnActionBattleChoiceOpportunity(funded,actor) : null; + if (choiceLeaves.length && (!opportunity || choiceLeaves.some(leaf => leaf.source !== opportunity.source))) continue; + const choice = opportunity?.choices.find(candidate => choiceLeaves.every(leaf => + (candidate.territory === leaf.territory && candidate.target === leaf.target) === leaf.answer)); + if (choiceLeaves.length && !choice) continue; reconcileBattlePromises(funded, voluntary); const battle = funded.battle; const needsPlan = !!battle && !battle.revealed && [battle.attacker, battle.defender].includes(actor) && @@ -24885,6 +24902,7 @@ function turnActionCompletionAfterFreshDiscard(source: Game, actor: string, unkn return { ...completion, ...(dialOpportunity ? { stormDial: { type: 'stormDial', amount: dialValues[0] } } : {}), ...(cardPreparations.length ? { cardPreparations } : {}), ...(cardSeed.cardsFirst ? { paymentsAfterPreparations: true } : {}), ...(bid ? { bid } : {}), ...(revival ? { revival } : {}), + ...(choice ? { battleChoice: {type:'chooseBattle',...choice} } : {}), ...(battlePlan ? { battlePlan } : {}), ...(traitor ? { traitor } : {}), ...(power.action ? { battlePower: power.action } : {}), ...(alliancePlan ? { alliance: alliancePlan.steps.map(step => step.kind === 'groupLeave' @@ -24911,6 +24929,7 @@ function turnActionPromise(g: Game, p: Player, claim: TurnActionClaim, answer: b const powers = new Set(); const windowCards: TurnActionWindowCards = {}; let stormDialSource: string | undefined; + let battleChoiceSource: string | undefined; const visit = (node: TurnActionClaim['mixed']): void => { if (node.kind === 'action') { if (node.action.kind === 'bid') bid = true; @@ -24919,6 +24938,14 @@ function turnActionPromise(g: Game, p: Player, claim: TurnActionClaim, answer: b stormDialSource = node.action.source; } if (node.action.kind === 'alliance') alliance = true; + if (node.action.kind === 'battleChoice') { + const opportunity = turnActionBattleChoiceOpportunity(g,p.id), selection = node.action; + requireRule(opportunity && selection.source === opportunity.source && + (!battleChoiceSource || battleChoiceSource === selection.source) && + opportunity.choices.some(choice => choice.territory === selection.territory && choice.target === selection.target), + 'Retain the current chooser and an actual available battle.'); + battleChoiceSource = selection.source; + } if (node.action.kind === 'battlePlan') plan = true; if (node.action.kind === 'traitorCall') traitor = true; if (node.action.kind === 'battlePower') powers.add(battlePowerOf(node.action.claim)); @@ -24958,6 +24985,7 @@ function turnActionPromise(g: Game, p: Player, claim: TurnActionClaim, answer: b traitor: context ? { beneficiary: context.beneficiary, target: context.target, leader: context.leader, closed: false, call: null } : null } : undefined; let promise: TurnActionPromise = { turn: claim.turn, mixed: structuredClone(claim.mixed), event, player: p.id, asker, answer, compiled, + ...(battleChoiceSource ? { battleChoice: {source:battleChoiceSource,closed:false,selected:null} } : {}), ...(Object.keys(windowCards).length ? { windowCards } : {}), ...(dial ? { stormDial: { source: dial.source, closed: false, actual: null } } : {}), ...(printedCards.size ? { cardPlays: { hajr: printedCards.has('hajr') ? { played: false, closed: !open } : null, @@ -25058,6 +25086,18 @@ function reconcileTurnActionPromises(g: Game, actor?: string, action?: Action, s if (g.pendingKull || suspendedKull) return; reconcileTurnActionCombat(g); reconcileTurnActionWindowCards(g); + for (const row of g.turnActionPromises ?? []) { + if (!row.battleChoice || row.battleChoice.closed || row.fulfilled || row.released || + turnActionBattleChoiceOpportunity(g,row.player)?.source === row.battleChoice.source) continue; + g.turnActionPromises = turnActionRule(() => closeTurnActionBattleChoice(g.turnActionPromises!, + row.player,row.turn,row.battleChoice!.source)); + const closed = g.turnActionPromises.find(promise => promise.event === row.event); + if (closed && !closed.fulfilled && !closed.released && turnActionRule(() => turnActionBranches(closed).next().done)) { + requireRule(actor !== closed.player, 'You cannot voluntarily close your required battle-choice answer.'); + closed.released = true; + log(g, `${getPlayer(g,closed.player).name} can no longer fulfill an accepted Truthtrance commitment; that answer is no longer binding.`); + } + } for (const row of g.turnActionPromises ?? []) { if (!row.stormDial || row.stormDial.closed || row.fulfilled || row.released || nativeStormDialOpportunity(g, row.player, row.stormDial.source)) continue; @@ -25268,6 +25308,8 @@ function projectedTurnActionGuide(g: Game, player: Player): { event: string; act } else if (!action && g.phase === 5 && g.active === player.id && !promise.transportClosed) action = completion.actions[0] ?? { type: 'endMovement' }; } + if (!action && g.phase === 6 && !g.battle && g.active === player.id && completion.battleChoice) + action = completion.battleChoice; if (!action && g.phase === 6 && g.battle) { const battle = g.battle; if (completion.battlePower) action = completion.battlePower; @@ -50056,6 +50098,11 @@ function applyActionInner( (b.attacker === id ? b.defender : b.attacker) === action.target, ); requireRule(choice, 'Choose one of your unresolved battles.'); + if (g.turnActionPromises) { + const source = battleChooserEvent(g.turn,battleOrderAfterBattle(g),g.battleOrder?.uses.length ?? 0); + g.turnActionPromises = turnActionRule(() => recordTurnActionBattleChoice(g.turnActionPromises!,id,g.turn,source, + {territory:choice.territory,target:choice.attacker === id ? choice.defender : choice.attacker})); + } g.auditorInsight = null; retireNexusChoamInsight(g); const ecaz = byFaction(g, 'ecaz'); diff --git a/game/reference.ts b/game/reference.ts index 7c28bbb4..8529daf2 100644 --- a/game/reference.ts +++ b/game/reference.ts @@ -3376,6 +3376,7 @@ export const RULE_TOPICS: RuleTopic[] = [ 'Ordinary force Revival clauses accumulate future total, normal or elite physical returns. Personal native leader clauses include eligible Advanced Atreides Kwisatz. Prior returns, Ghola, foreign leaders and special returns do not count. Original costs, slots, cycles and actual return controls remain.', 'Basic Revival No lasts to phase close; ordered Advanced finishes at the respondent’s actual own turn end. Own Ready must retain a whole completion, including a funded later payment alternative. An owned Karama invoice guide appears only at the actual payment decision, never while another bidder is active.', 'A battle-plan condition names an atomic part of your actual plan in this current battle. An open condition settles when both original plans reveal; a plan already sealed fixes its value at the answer. The human guide fills your existing plan for review before sealing. Native leaders, physical cards, Voice, costs and ordered preparation still apply.', + 'A current battle-choice condition names the actual chooser, territory and opponent at this original battle-order opportunity. Yes requires the choice while possible; No forbids it. Combined and separate commitments share the native legal guide; a later choice is a different opportunity. This online interpretation is provisional.', 'A Traitor condition describes the original eligible voter’s Reveal or Decline declaration in this revealed battle, before any later Karama prevention. A prevented Reveal stays a declared Reveal. No missing battle or declaration is invented as a zero plan or Decline, and an absent matching Traitor never creates one.', 'A future storm-dial condition names a current Basic dialer who has not submitted and asks whether their value will be exactly, at least or at most a chosen threshold. Turn 1 permits 0–20; later Basic turns permit 1–3. Yes and No bind the whole answer; multiple conditions share the same native choice. The other dial remains sealed, and the normal sum is revealed only after both dialers submit.', 'A native-power condition names your original Voice or Prescience opportunity in this battle. Ask about actual use or explicit Decline, an exact Voice category and require/forbid command, or the requested Prescience field. A requested field is not the inspected answer. The declaration counts before later Karama prevention.', diff --git a/game/truthtrance.ts b/game/truthtrance.ts index bbc79ace..64f5edb3 100644 --- a/game/truthtrance.ts +++ b/game/truthtrance.ts @@ -63,7 +63,8 @@ import { } from './battle-promises'; import { gameTerritories } from './board'; import { leaders } from './cards'; -import { combatLocationName } from './combat-location'; +import { combatLocationName, quoteCombatBoard } from './combat-location'; +import { battleChooserEvent, quoteBattleChoosers } from './battle-chooser-order'; import { parseForceCountFact, forceCountFactMatches, forceCountFactText, forceCountCounterError, type ForceCountFact, type ForceCountPlayer } from './truthtrance-force-count'; import type { Action, Game, Player } from './engine'; import { coalitionAllies } from './coalition-alliance'; @@ -536,6 +537,15 @@ function parseQuestion(g: Game, asker: string, value: unknown): TruthQuestion { const respondent = g.players.find(player => player.id === v.target)!; const mixed = parseMixedActionExpression(v.mixed, fact => parseFact(g, fact, respondent), input => { const action = parseTurnActionLeaf(input); + if (action.kind === 'battleChoice') { + const source = battleChooserEvent(g.turn, g.lastBattleContext?.turn === g.turn ? g.lastBattleContext.event : null, + g.battleOrder?.uses.length ?? 0); + const choices = quoteBattleChoosers(quoteCombatBoard(g).battles,g.order,g.battleOrder?.priority).choices; + check(g.phase === 6 && !g.battle && g.active === respondent.id && action.source === source && + choices.some(choice => choice.chooser === respondent.id && choice.territory === action.territory && + (choice.attacker === respondent.id ? choice.defender : choice.attacker) === action.target), + 'Choose the current player’s original available battle and opponent.'); + } if (battleCancel) check(action.kind === 'windowCardPlay' && action.effect === 'karamaBattleCancel' && action.source === battleCancel.source, 'Ask only about the current printed Karama cancellation in this response.'); if (action.kind === 'stormDial') { @@ -991,6 +1001,7 @@ export function truthQuestionText( }; if (q.kind === 'turnActions') return `Is it true that ${mixedActionExpressionText(q.mixed, clause, action => { + if (action.kind === 'battleChoice') return `you choose the battle against ${playerName(action.target)} in ${locationName(action.territory)} at this battle-choice opportunity`; if (action.kind === 'stormDial') return `you submit ${action.compare === 'gte' ? 'at least' : action.compare === 'lte' ? 'at most' : 'exactly'} ${action.value} on your original storm dial this turn`; if (action.kind === 'windowCardPlay') { if (action.effect === 'karamaHarkonnenSpecial') diff --git a/game/turn-action-promises.ts b/game/turn-action-promises.ts index 7f35fe8d..75909b04 100644 --- a/game/turn-action-promises.ts +++ b/game/turn-action-promises.ts @@ -42,6 +42,7 @@ export function turnActionPromiseModeSupported(game: NativePromiseScope & { export type TurnActionLeaf = TravelActionClaim | StormDialClaim | { kind: 'payment'; recipient: string; minimum: number } | { kind: 'bid'; lot: number; minimum: number } | RevivalActionClaim | { kind: 'alliance'; partner: string } | + { kind: 'battleChoice'; source: string; territory: string; target: string } | { kind: 'battlePlan'; battle: string; territory: string; claim: MixedBattleActionClaim } | { kind: 'traitorCall'; battle: string; territory: string; call: boolean } | { kind: 'cardPlay'; effect: PrintedCardEffect } | @@ -56,6 +57,7 @@ export type TurnActionBranchLeaf = TravelBranchLeaf | { kind: 'forces'; counter: 'total' | 'normal' | 'elite'; minimum: number; progress: number; answer: boolean } | { kind: 'leader'; leader: string; answer: boolean } | { kind: 'alliance'; partner: string; source: string; answer: boolean } | + { kind: 'battleChoice'; source: string; territory: string; target: string; answer: boolean } | { kind: 'battlePlan'; battle: string; territory: string; claim: MixedBattleActionClaim; answer: boolean } | { kind: 'traitorCall'; battle: string; territory: string; call: boolean; answer: boolean; beneficiary: string; target: string; leader: string | null } | @@ -114,6 +116,8 @@ export type TurnActionPromise = TurnActionClaim & { windowCards?: TurnActionWindowCards; /** A submitted dial is private to its respondent until the native reveal. */ stormDial?: { source: string; closed: boolean; actual: number | null }; + /** Only the original chooser opportunity and its one actual native choice. */ + battleChoice?: { source: string; closed: boolean; selected: { territory: string; target: string } | null }; }; export class TurnActionError extends Error { @@ -141,6 +145,19 @@ const printedTerritory = (value: unknown): value is string => typeof value === 'string' && TERRITORIES.some(destination => destination.id === value); const windowEffect = (value: unknown): value is WindowCardEffect => WINDOW_CARD_EFFECTS.some(effect => effect === value); +/** Decode the exact existing public battle-chooser event, without inventing + * a competing event grammar or accepting a client-selected turn. */ +function battleChoiceSource(value: unknown): { turn: number } | null { + if (!identifier(value) || !value.startsWith('battleOrder:')) return null; + try { + const tuple: unknown = JSON.parse(value.slice('battleOrder:'.length)); + if (!Array.isArray(tuple) || tuple.length !== 3 || !positive(tuple[0]) || + !(tuple[1] === null || identifier(tuple[1])) || !whole(tuple[2]) || + value !== `battleOrder:${JSON.stringify(tuple)}`) return null; + return {turn:tuple[0]}; + } catch { return null; } +} + /** Identity membership is decoded by Truthtrance; here retain one strict atom. */ function parseCombatClaim(value: unknown): MixedBattleActionClaim { try { @@ -189,6 +206,12 @@ export function parseTurnActionLeaf(value: unknown): TurnActionLeaf { 'Choose only a supported printed-card play after this answer.'); return { kind: 'cardPlay', effect: value.effect as PrintedCardEffect }; } + if (value.kind === 'battleChoice') { + check(keys(value, 'kind,source,target,territory') && !!battleChoiceSource(value.source) && + identifier(value.territory) && identifier(value.target), + 'Choose the original battle-selection opportunity, destination and opponent.'); + return {kind:'battleChoice',source:value.source as string,territory:value.territory,target:value.target}; + } if (value.kind === 'battlePlan' || value.kind === 'traitorCall') { check(keys(value, value.kind === 'battlePlan' ? 'battle,claim,kind,territory' : 'battle,call,kind,territory') && identifier(value.battle) && identifier(value.territory), 'Retain the exact original current battle and native location.'); @@ -235,6 +258,7 @@ function storedFact(value: unknown, depth = 0): TruthFact { } function actionKey(action: TurnActionLeaf): string { + if (action.kind === 'battleChoice') return JSON.stringify([action.kind,action.source,action.territory,action.target]); if (action.kind === 'stormDial') return JSON.stringify(action.compare && action.compare !== 'eq' ? [action.kind, action.source, action.value, action.compare] : [action.kind, action.source, action.value]); if (action.kind === 'windowCardPlay') return JSON.stringify([action.kind, action.effect, action.source]); @@ -300,6 +324,7 @@ function readPromise(promise: TurnActionPromise): CompiledMixedAction(); const windowSources = new Map>(); const stormSources = new Set(); + const choiceSources = new Set(); const visit = (node: MixedActionExpression): void => { if (node.kind === 'action') { originals.add(actionKey(node.action)); @@ -343,6 +369,7 @@ function readPromise(promise: TurnActionPromise): CompiledMixedAction(); @@ -360,6 +387,16 @@ function readPromise(promise: TurnActionPromise): CompiledMixedAction, promise: TurnAction } function actionClosed(action: TurnActionLeaf, promise: TurnActionPromise): boolean { + if (action.kind === 'battleChoice') return promise.battleChoice!.closed; if (action.kind === 'stormDial') return promise.stormDial!.closed; if (action.kind === 'windowCardPlay') return promise.windowCards![action.effect]!.closed; if (action.kind === 'battlePower') return promise.combat!.powers![battlePowerOf(action.claim)]!.closed; @@ -612,6 +653,8 @@ export function liveTurnActionPromises(promises: re function sameAction(left: TurnActionBranchLeaf, right: TurnActionBranchLeaf): boolean { if (left.kind !== right.kind) return false; + if (left.kind === 'battleChoice') return right.kind === 'battleChoice' && left.source === right.source && + left.territory === right.territory && left.target === right.target; if (left.kind === 'stormDial') return right.kind === 'stormDial' && left.source === right.source && left.value === right.value && (left.compare ?? 'eq') === (right.compare ?? 'eq'); if (left.kind === 'windowCardPlay') return right.kind === 'windowCardPlay' && left.effect === right.effect && left.source === right.source; @@ -650,6 +693,14 @@ export function turnActionStormDialChoices(leaves: readonly TurnActionBranchLeaf function mergeBranches(left: TurnActionBranchLeaf[], right: TurnActionBranchLeaf[]): TurnActionBranchLeaf[] | null { const merged = left.map(leaf => ({ ...leaf })); for (const leaf of right) { + if (leaf.kind === 'battleChoice') { + const prior = merged.find(other => sameAction(other,leaf)); + if (prior && prior.answer !== leaf.answer) return null; + if (leaf.answer && merged.some(other => other.kind === 'battleChoice' && other.source === leaf.source && + other.answer && (other.territory !== leaf.territory || other.target !== leaf.target))) return null; + if (!prior) merged.push({...leaf}); + continue; + } if (leaf.kind === 'traitorCall') { const prior = merged.find(other => other.kind === 'traitorCall' && other.battle === leaf.battle && other.territory === leaf.territory && other.beneficiary === leaf.beneficiary && other.target === leaf.target && other.leader === leaf.leader); @@ -747,6 +798,39 @@ function settle(promise: T, update: T): T { ? { ...update, fulfilled: true } : update; } +/** Record exactly the native chooser's accepted territory/opponent once. + * The engine owns candidate legality and reconciles external impossibility. */ +export function recordTurnActionBattleChoice(promises: readonly T[], player: string, + turn: number, source: string, selected: {territory:string; target:string}): T[] { + const identity = battleChoiceSource(source); + check(identity && identity.turn === turn && object(selected) && keys(selected, 'target,territory') && + identifier(selected.territory) && identifier(selected.target) && selected.target !== player, + 'Retain the original chooser opportunity and actual different opponent.'); + const updates = new Map(); + for (const promise of liveTurnActionPromises(promises,player,turn)) { + readPromise(promise); + const stage = promise.battleChoice; + if (!stage || stage.closed || stage.source !== source) continue; + updates.set(promise,settle(promise,{...promise,battleChoice:{...stage,closed:true,selected:{...selected}}})); + } + return promises.map(promise => updates.get(promise) ?? promise); +} + +/** A lost or closed chooser source has no synthetic selected battle. */ +export function closeTurnActionBattleChoice(promises: readonly T[], player: string, + turn: number, source: string): T[] { + const identity = battleChoiceSource(source); + check(identity && identity.turn === turn, 'Retain the original current-turn battle chooser source.'); + const updates = new Map(); + for (const promise of liveTurnActionPromises(promises,player,turn)) { + readPromise(promise); + const stage = promise.battleChoice; + if (!stage || stage.closed || stage.source !== source) continue; + updates.set(promise,settle(promise,{...promise,battleChoice:{...stage,closed:true}})); + } + return promises.map(promise => updates.get(promise) ?? promise); +} + /** Record one actual sealed native dial against its exact original source. * Closing the stage never publishes its private numeric receipt. */ export function recordTurnActionStormDial(promises: readonly T[], player: string, @@ -1169,6 +1253,7 @@ export function finishTurnActionTurn(promises: read .filter(effect => Object.hasOwn(promise.cardPlays!, effect)).map(effect => [effect, promise.cardPlays![effect] ? { ...promise.cardPlays![effect]!, closed: true } : null])) as TurnActionCardPlays } : {}), ...(promise.windowCards ? { windowCards } : {}), + ...(promise.battleChoice ? { battleChoice: { ...promise.battleChoice, closed: true } } : {}), ...(promise.stormDial ? { stormDial: { ...promise.stormDial, closed: true } } : {}) }; const unresolvedCombat = promise.combat && (promise.combat.plan && !promise.combat.plan.closed || promise.combat.traitor && !promise.combat.traitor.closed || promise.combat.powers?.voice && !promise.combat.powers.voice.closed || @@ -1193,15 +1278,18 @@ export function validateTurnActionPromises(promises: readonly TurnActionPromise[ (!promise.combat?.traitor || promise.combat.traitor.closed) && (!promise.combat?.powers?.voice || promise.combat.powers.voice.closed) && (!promise.combat?.powers?.prescience || promise.combat.powers.prescience.closed) && + (!promise.battleChoice || promise.battleChoice.closed) && WINDOW_CARD_EFFECTS.every(effect => promise.windowCards?.[effect]?.closed ?? true) && (!promise.stormDial || promise.stormDial.closed) && PRINTED_CARD_EFFECTS.every(effect => promise.cardPlays?.[effect]?.closed ?? true); const recipientsValid = (node: MixedActionExpression): boolean => node.kind === 'action' - ? node.action.kind === 'alliance' ? players.includes(node.action.partner) && node.action.partner !== promise.player : + ? node.action.kind === 'battleChoice' ? players.includes(node.action.target) && node.action.target !== promise.player : + node.action.kind === 'alliance' ? players.includes(node.action.partner) && node.action.partner !== promise.player : node.action.kind !== 'payment' || players.includes(node.action.recipient) && node.action.recipient !== promise.player : node.kind === 'fact' || node.terms.every(recipientsValid); check(!events.has(promise.event) && players.includes(promise.player) && players.includes(promise.asker) && promise.player !== promise.asker && recipientsValid(promise.mixed) && + (!promise.battleChoice?.selected || players.includes(promise.battleChoice.selected.target)) && (!promise.alliance || promise.alliance.partner === null || players.includes(promise.alliance.partner)) && (!promise.combat?.traitor || players.includes(promise.combat.traitor.beneficiary) && players.includes(promise.combat.traitor.target) && promise.combat.traitor.target !== promise.player) && diff --git a/lib/actionable-notices.ts b/lib/actionable-notices.ts new file mode 100644 index 00000000..3b366da4 --- /dev/null +++ b/lib/actionable-notices.ts @@ -0,0 +1,20 @@ +/** Local presentation state for messages which need a player's acknowledgement. */ +export type ActionableNotice = { id: number; text: string }; +export type ActionableNoticeQueue = { nextId: number; items: ActionableNotice[] }; +export type ActionableNoticeUpdate = + | { type: 'enqueue'; text: string } + | { type: 'dismiss'; id: number }; + +export const initialActionableNotices: ActionableNoticeQueue = { nextId: 1, items: [] }; + +/** Repeated identical messages coalesce while pending; a stale button cannot + * dismiss a later message, including another occurrence of the same text. */ +export function updateActionableNotices( + state: ActionableNoticeQueue, + update: ActionableNoticeUpdate, +): ActionableNoticeQueue { + if (update.type === 'dismiss') return state.items[0]?.id === update.id + ? { ...state, items: state.items.slice(1) } : state; + if (!update.text || state.items.some(item => item.text === update.text)) return state; + return { nextId: state.nextId + 1, items: [...state.items, { id: state.nextId, text: update.text }] }; +} diff --git a/tests/actionable-notice-queue.test.tsx b/tests/actionable-notice-queue.test.tsx new file mode 100644 index 00000000..ab3aec42 --- /dev/null +++ b/tests/actionable-notice-queue.test.tsx @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { Children, isValidElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { ActionableNotice } from '../components/actionable-notice'; +import { Button } from '../components/ui/button'; +import { initialActionableNotices, updateActionableNotices } from '../lib/actionable-notices'; + +void test('distinct actionable messages stay queued until each Continue, while exact retries coalesce', () => { + let queue = initialActionableNotices; + const enqueue = (text: string) => { queue = updateActionableNotices(queue, {type:'enqueue',text}); }; + const dismiss = (id: number) => { queue = updateActionableNotices(queue, {type:'dismiss',id}); }; + enqueue('Your action may have completed. Check the refreshed table.'); + const first = queue.items[0]; + enqueue('Your action may have completed. Check the refreshed table.'); + enqueue('Second faction added. Switch factions to make each ready.'); + assert.deepEqual(queue.items.map(item => item.text), [ + 'Your action may have completed. Check the refreshed table.', + 'Second faction added. Switch factions to make each ready.', + ]); + const firstView = ActionableNotice({notice:first,onDismiss:dismiss}); assert.ok(firstView); + const html = renderToStaticMarkup(firstView); + assert.match(html, /Your action may have completed/); + assert.match(html, /Continue/); + assert.doesNotMatch(html, /Second faction added/); + const button = Children.toArray(firstView.props.children).filter(isValidElement).find(child => child.type === Button); + assert.ok(button); + (button.props as {onClick: () => void}).onClick(); + assert.equal(queue.items[0].text, 'Second faction added. Switch factions to make each ready.'); + (button.props as {onClick: () => void}).onClick(); + assert.equal(queue.items.length, 1, 'A stale prior Continue cannot dismiss the next notice'); + dismiss(queue.items[0].id); + assert.deepEqual(queue.items, []); + assert.equal(ActionableNotice({notice:null,onDismiss:dismiss}), null); +}); + +void test('retrying after explicit acknowledgement creates an independent notice identity', () => { + let queue = updateActionableNotices(initialActionableNotices, {type:'enqueue',text:'Reconnect required.'}); + const old = queue.items[0]; + queue = updateActionableNotices(queue, {type:'dismiss',id:old.id}); + queue = updateActionableNotices(queue, {type:'enqueue',text:'Reconnect required.'}); + assert.notEqual(queue.items[0].id, old.id); + queue = updateActionableNotices(queue, {type:'dismiss',id:old.id}); + assert.equal(queue.items.length, 1); + queue = updateActionableNotices(queue, {type:'dismiss',id:queue.items[0].id}); + const next = updateActionableNotices(queue, {type:'enqueue',text:'Another seat.'}); + assert.ok(next.items[0].id > old.id); + assert.deepEqual(initialActionableNotices.items, [], 'The shared initial state was not mutated'); +}); diff --git a/tests/truth-turn-action-battle-choice-runtime.test.ts b/tests/truth-turn-action-battle-choice-runtime.test.ts new file mode 100644 index 00000000..6903a8fd --- /dev/null +++ b/tests/truth-turn-action-battle-choice-runtime.test.ts @@ -0,0 +1,193 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { applyAction, viewGame, type Action, type Game } from '../game/engine'; +import { botActions } from '../game/bots'; +import { DIFFICULTIES } from '../game/bot-profiles'; +import type { TruthQuestion } from '../game/truthtrance'; +import { createBattleTerritoryExplosionFixture } from './fixture-battle-territory-explosion'; + +const act = (game: Game, actor: string, action: Action) => applyAction(game, actor, action); +function player(game: Game, id: string) { + const seat = game.players.find(candidate => candidate.id === id); assert.ok(seat); return seat; +} +function inventory(game: Game) { + return [...game.deck, ...game.discard, ...game.players.flatMap(seat => seat.hand), + ...(game.auction?.cards.slice(game.auction.index + Number(game.currentAuctionSale?.origin === 'normal')) ?? [])] + .map(card => card.id).sort(); +} +function reject(game: Game, actor: string, action: Action) { + const before = structuredClone(game); + assert.throws(() => act(game, actor, action)); + assert.deepEqual(game, before, 'A forbidden action must not alter its input'); +} +/** A genuine public Basic three-faction setup and native movement yields a + * three-army fight in Imperial Basin. Only the existing physical Truthtrance + * and one already-held card are exchanged between their real zones after that + * native prefix; the closed original auctions and both physical card counts + * remain unchanged. No battle, force, wallet or order state is assigned. */ +function source() { + const game = structuredClone(createBattleTerritoryExplosionFixture({advanced:false}).beforeFirst); + assert.equal(game.phase, 6); assert.ok(!game.battle && game.active); + const chooser = game.active, choices = viewGame(game, chooser).battleChoices.filter(choice => choice.chooser === chooser); + assert.ok(choices.length >= 2, 'The actual current chooser has multiple real battles'); + const [chosen, alternate] = choices; + const target = (choice: typeof chosen) => choice.attacker === chooser ? choice.defender : choice.attacker; + const asker = game.players.find(seat => seat.id !== chooser)!.id; + const initial = inventory(game), hand = player(game, asker).hand; + let truth = hand.find(card => card.effect === 'truthtrance'); + if (!truth) { + const replacement = hand[0]; assert.ok(replacement, 'The original dealt card supplies the conserved exchange'); + const owner = game.players.find(seat => seat.id !== asker && seat.hand.some(card => card.effect === 'truthtrance')); + if (owner) { + const index = owner.hand.findIndex(card => card.effect === 'truthtrance'); + truth = owner.hand[index]; owner.hand[index] = replacement; + } else { + const zone = [game.deck,game.discard].find(cards => cards.some(card => card.effect === 'truthtrance')); + assert.ok(zone, 'The original Truthtrance must be in an actual hand, deck or discard'); + const index = zone.findIndex(card => card.effect === 'truthtrance'); + truth = zone[index]; zone[index] = replacement; + } + hand[0] = truth; + } + assert.deepEqual(inventory(game), initial); + const event = viewGame(game, chooser).battleOrder?.event; assert.ok(event); + const desired: Action = {type:'chooseBattle',territory:chosen.territory,target:target(chosen)}; + const other: Action = {type:'chooseBattle',territory:alternate.territory,target:target(alternate)}; + assert.notDeepEqual(desired, other); + const question: TruthQuestion = {kind:'turnActions',target:chooser,turn:game.turn,mixed:{kind:'action', + action:{kind:'battleChoice',source:event,territory:chosen.territory,target:target(chosen)}}}; + return {game,chooser,asker,truth:truth.id,event,desired,other,question,initial}; +} +function ask(f: ReturnType, question: TruthQuestion = f.question, + input: Game = f.game, asker = f.asker, truth = f.truth): Game { + let game = act(input, asker, {type:'card',card:truth}); + for (let count = 0; count < 8 && game.truthtrance?.stage === 'priority'; count++) { + const seat = game.players.find(candidate => !game.truthtrance!.passed.includes(candidate.id)); assert.ok(seat); + game = act(game, seat.id, {type:'truthPass'}); + } + assert.equal(game.truthtrance?.stage, 'ask'); + game = act(game, asker, {type:'truthAsk',question}); + return game; +} +function choiceQuestion(f: ReturnType, kind: 'and' | 'or'): TruthQuestion { + const term = (action: Action) => ({kind:'action' as const, action:{kind:'battleChoice' as const, + source:f.event,territory:action.territory as string,target:action.target as string}}); + return {kind:'turnActions',target:f.chooser,turn:f.game.turn, + mixed:{kind,terms:[term(f.desired),term(f.other)]}}; +} + +void test('a real Basic chooser Yes rejects another battle and follows its exact private guide', () => { + const f = source(), asked = ask(f); + const game = act(asked, f.chooser, {type:'truthAnswer',answer:'yes'}); + reject(game, f.chooser, f.other); + const guide = viewGame(game, f.chooser).turnActionGuide; assert.ok(guide); + assert.equal(guide.action.type, 'chooseBattle'); + assert.equal(guide.action.territory, f.desired.territory); + assert.equal(guide.action.target, f.desired.target); + assert.equal(guide.action.turnActionPromiseEvent, guide.event); + const chosen = act(game, f.chooser, guide.action); + assert.equal(chosen.battle?.territory, f.desired.territory); + assert.ok([chosen.battle?.attacker, chosen.battle?.defender].includes(f.desired.target as string)); + assert.equal(chosen.turnActionPromises?.[0].fulfilled, true); + assert.deepEqual(inventory(chosen), f.initial); +}); + +void test('a real Basic chooser No forbids the named battle while preserving the other native choice', () => { + const f = source(), game = act(ask(f), f.chooser, {type:'truthAnswer',answer:'no'}); + reject(game, f.chooser, f.desired); + const chosen = act(game, f.chooser, f.other); + assert.equal(chosen.battle?.territory, f.other.territory); + assert.ok([chosen.battle?.attacker, chosen.battle?.defender].includes(f.other.target as string)); + assert.equal(chosen.turnActionPromises?.[0].fulfilled, true); + assert.deepEqual(inventory(chosen), f.initial); +}); + +void test('all four minimal bots answer and execute the real promised battle choice', () => { + const f = source(), asked = ask(f); + for (const difficulty of DIFFICULTIES) { + const answering = viewGame(asked, f.chooser); + answering.players.find(seat => seat.id === f.chooser)!.bot = difficulty; + const answer = botActions(answering).find(action => action.type === 'truthAnswer'); + assert.ok(answer, difficulty); + const game = act(asked, f.chooser, answer); + const view = viewGame(game, f.chooser); + view.players.find(seat => seat.id === f.chooser)!.bot = difficulty; + const options = botActions(view); + assert.ok(options.length, difficulty); + const legal = options.find(action => { + try { act(game, f.chooser, action); return true; } catch { return false; } + }); + assert.ok(legal, `${difficulty} must offer at least one legal continuation`); + const chosen = act(game, f.chooser, legal); + assert.ok(chosen.battle, `${difficulty} must choose an actual battle`); + assert.equal(chosen.turnActionPromises?.[0].fulfilled, true); + assert.deepEqual(inventory(chosen), f.initial); + } +}); + +void test('two different current battle choices cannot both be chosen in one native opportunity', () => { + const f = source(), asked = ask(f,choiceQuestion(f,'and')); + const answers = viewGame(asked, f.chooser).truthTurnActionAnswers; assert.ok(answers); + assert.ok(answers.includes('no')); assert.ok(!answers.includes('yes')); + reject(asked, f.chooser, {type:'truthAnswer',answer:'yes'}); + const bound = act(asked, f.chooser, {type:'truthAnswer',answer:'no'}); + for (const choice of [f.desired,f.other]) { + const chosen = act(bound, f.chooser, choice); + assert.ok(chosen.battle); + assert.equal(chosen.turnActionPromises?.[0].fulfilled, true); + assert.deepEqual(inventory(chosen), f.initial); + } +}); + +void test('either real battle fulfills an OR of the two current choices', () => { + const f = source(), asked = ask(f,choiceQuestion(f,'or')); + const answers = viewGame(asked, f.chooser).truthTurnActionAnswers; assert.ok(answers?.includes('yes')); + const bound = act(asked, f.chooser, {type:'truthAnswer',answer:'yes'}); + const guide = viewGame(bound, f.chooser).turnActionGuide; assert.ok(guide); + assert.equal(guide.action.type, 'chooseBattle'); + assert.ok([f.desired,f.other].some(choice => choice.territory === guide.action.territory && + choice.target === guide.action.target), 'The private guide must use one real qualifying choice'); + for (const choice of [f.desired,f.other]) { + const chosen = act(bound, f.chooser, choice); + assert.ok(chosen.battle); + assert.equal(chosen.turnActionPromises?.[0].fulfilled, true); + assert.deepEqual(inventory(chosen), f.initial); + } +}); + +void test('an earlier accepted Yes excludes a later conflicting Yes while preserving the original choice', () => { + const f = source(), secondAsker = f.game.players.find(seat => seat.id !== f.chooser && seat.id !== f.asker)!; + const targetHand = secondAsker.hand; + let second = targetHand.find(card => card.effect === 'truthtrance' && card.id !== f.truth); + if (!second) { + const replacement = targetHand[0]; assert.ok(replacement); + const owner = f.game.players.find(seat => seat.id !== secondAsker.id && + seat.hand.some(card => card.effect === 'truthtrance' && card.id !== f.truth)); + if (owner) { + const index = owner.hand.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth); + second = owner.hand[index]; owner.hand[index] = replacement; + } else { + const zone = [f.game.deck,f.game.discard].find(cards => + cards.some(card => card.effect === 'truthtrance' && card.id !== f.truth)); + assert.ok(zone); + const index = zone.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth); + second = zone[index]; zone[index] = replacement; + } + targetHand[0] = second; + } + assert.deepEqual(inventory(f.game), f.initial, 'Both actual Truth cards are staged by conserved swaps'); + let game = act(ask(f), f.chooser, {type:'truthAnswer',answer:'yes'}); + const otherQuestion: TruthQuestion = {kind:'turnActions',target:f.chooser,turn:game.turn,mixed:{kind:'action', + action:{kind:'battleChoice',source:f.event,territory:f.other.territory as string,target:f.other.target as string}}}; + game = ask(f,otherQuestion,game,secondAsker.id,second.id); + const answers = viewGame(game,f.chooser).truthTurnActionAnswers; assert.ok(answers); + assert.ok(answers.includes('no')); assert.ok(!answers.includes('yes')); + reject(game,f.chooser,{type:'truthAnswer',answer:'yes'}); + game = act(game,f.chooser,{type:'truthAnswer',answer:'no'}); + reject(game,f.chooser,f.other); + const chosen = act(game,f.chooser,f.desired); + assert.ok(chosen.battle); + assert.equal(chosen.turnActionPromises?.length, 2); + assert.ok(chosen.turnActionPromises?.every(promise => promise.fulfilled)); + assert.deepEqual(inventory(chosen),f.initial); +}); diff --git a/tests/turn-action-battle-choice-controls.test.tsx b/tests/turn-action-battle-choice-controls.test.tsx new file mode 100644 index 00000000..28c357a1 --- /dev/null +++ b/tests/turn-action-battle-choice-controls.test.tsx @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { TurnActionFields, turnActionInputError } from '../components/turn-action-fields'; +import { TurnActionGuideButton } from '../components/turn-action-promises'; +import { createGame, joinGame, newPlayer, viewGame, type Action, type GameView } from '../game/engine'; +import type { MixedActionExpression } from '../game/mixed-action-question'; +import type { TurnActionLeaf } from '../game/turn-action-promises'; +import { battleChooserEvent } from '../game/battle-chooser-order'; + +type Expression = MixedActionExpression; +type Element = ReactElement<{ children?: ReactNode; [key: string]: unknown }>; +const source = battleChooserEvent(1,null,0); +function elements(node: ReactNode): Element[] { + if (Array.isArray(node)) return node.flatMap(elements); + if (!isValidElement<{ children?: ReactNode; [key: string]: unknown }>(node)) return []; + return [node, ...elements(node.props.children)]; +} +/** Controlled public projection: tests the editor and guide, not game setup. */ +function projection(viewer = 'p'): GameView { + const game = createGame('BATTLECHOICECONTROL', newPlayer('p', 'Atreides', 'atreides')); + joinGame(game, newPlayer('a', 'Emperor', 'emperor')); + joinGame(game, newPlayer('g', 'Guild', 'guild')); + const view = viewGame(game, viewer); + view.status = 'playing'; view.turn = 1; view.phase = 6; view.active = 'p'; view.battle = null; + view.battleOrder = {event:source, phaseEvent:'battleOrder:1', remaining:['p','a','g'], current:'p', uses:[]}; + view.battleChoices = [ + {chooser:'p', attacker:'p', defender:'a', territory:'arrakeen'}, + {chooser:'p', attacker:'g', defender:'p', territory:'carthag'}, + ]; + return view; +} +const choice = (territory: string, target: string, event = source): Expression => + ({kind:'action', action:{kind:'battleChoice',source:event,territory,target}}); + +void test('editor selects only the current chooser’s actual public battle pairs', () => { + const game = projection('a'); + // A Truthtrance question itself temporarily suppresses the projected current + // order indicator, but does not change the authoritative active chooser. + game.battleOrder!.current = null; + let value: Expression = {kind:'action',action:{kind:'ship',territory:'carthag',minimum:1}}; + const tree = () => TurnActionFields({game, value, target:'p', disabled:false, onChange(next) {value = next;}}); + const action = elements(tree()).find(element => element.props.id === 'truth-turn-action-1-action'); assert.ok(action); + (action.props.onChange as (event: {currentTarget:{value:string}}) => void)({currentTarget:{value:'battleChoice'}}); + assert.deepEqual(value, choice('arrakeen','a')); + assert.equal(turnActionInputError(value,game,'p'),null); + const html = renderToStaticMarkup(createElement(TurnActionFields,{game,value,target:'p',disabled:false,onChange() {}})); + assert.match(html,/Current unresolved battle/); assert.match(html,/Arrakeen/); assert.match(html,/Emperor/); + const select = elements(tree()).find(element => element.props.id === 'truth-turn-action-1-battle-choice'); assert.ok(select); + (select.props.onChange as (event: {currentTarget:{value:string}}) => void)({currentTarget:{value:JSON.stringify(['carthag','g'])}}); + assert.deepEqual(value,choice('carthag','g')); assert.equal(turnActionInputError(value,game,'p'),null); + assert.notEqual(turnActionInputError(choice('arrakeen','g'),game,'p'),null); + assert.notEqual(turnActionInputError(choice('arrakeen','a','stale'),game,'p'),null); + assert.notEqual(turnActionInputError(choice('arrakeen','a'),game,'g'),null); + game.active = 'g'; assert.notEqual(turnActionInputError(value,game,'p'),null); +}); + +void test('guided native battle choice rejects changed event, chooser or candidate', () => { + for (const mutate of [ + (view:GameView) => {view.battleOrder!.event = 'later-source';}, + (view:GameView) => {view.active = 'g';}, + (view:GameView) => {view.battleChoices = view.battleChoices.filter(row => row.territory !== 'arrakeen');}, + ]) { + const game = projection(), event = 'battle-choice-promise', mixed = choice('arrakeen','a'); + game.turnActionPromises = [{event,player:'p',asker:'a',turn:1,mixed,answer:true,fulfilled:false,released:false}]; + const action: Action = {type:'chooseBattle',territory:'arrakeen',target:'a',turnActionPromiseEvent:event,turnActionPromisePhase:6}; + game.turnActionGuide = {event,action}; + const sent: Action[] = [], props = {game,busy:false,act:(next:Action) => sent.push(next)}; + const button = TurnActionGuideButton(props); assert.ok(button); assert.equal(button.props.disabled,false); + assert.match(renderToStaticMarkup(createElement(TurnActionGuideButton,props)),/Choose the battle against Emperor in Arrakeen/); + button.props.onClick(); assert.deepEqual(sent,[action]); + mutate(game); button.props.onClick(); assert.deepEqual(sent,[action]); + } +}); diff --git a/tests/turn-action-battle-choice-quote.test.ts b/tests/turn-action-battle-choice-quote.test.ts new file mode 100644 index 00000000..c41ae9ce --- /dev/null +++ b/tests/turn-action-battle-choice-quote.test.ts @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { compileMixedActionExpression, type MixedActionExpression } from '../game/mixed-action-question'; +import { + TurnActionError, closeTurnActionBattleChoice, finishTurnActionTurn, parseTurnActionLeaf, + recordTurnActionBattleChoice, turnActionBranches, turnActionValue, validateTurnActionPromises, + type TurnActionLeaf, type TurnActionPromise, +} from '../game/turn-action-promises'; + +const source = 'battleOrder:[2,null,0]'; +const leaf = (territory = 'carthag', target = 'guild'): TurnActionLeaf => + ({kind:'battleChoice',source,territory,target}); +const action = (value: TurnActionLeaf): MixedActionExpression => ({kind:'action',action:value}); +function promise(mixed: MixedActionExpression, answer = true): TurnActionPromise { + return {turn:2,event:'answer-1',player:'atreides',asker:'emperor',answer,mixed, + compiled:compileMixedActionExpression(mixed,() => 'yes',answer), + shipment:{pending:false,event:null},progress:[],payments:[],transportClosed:true,paymentClosed:true, + battleChoice:{source,closed:false,selected:null},fulfilled:false,released:false}; +} +const selected = {territory:'carthag',target:'guild'}; +const seats = ['atreides','emperor','guild','fremen']; + +void test('battle choice accepts only an exact canonical source and original public fields', () => { + assert.deepEqual(parseTurnActionLeaf(leaf()),leaf()); + for (const value of [ + {...leaf(), source:'other'}, {...leaf(), source:'battleOrder:[2,null,-1]'}, + {...leaf(), source:'battleOrder:[ 2,null,0]'}, {...leaf(), source:'battleOrder:[0,null,0]'}, + {...leaf(), target:''}, {...leaf(), territory:''}, {...leaf(), extra:true}, + ]) assert.throws(() => parseTurnActionLeaf(value),TurnActionError); + const p = promise(action(leaf())); validateTurnActionPromises([p],seats); + assert.throws(() => validateTurnActionPromises([{...p,battleChoice:{...p.battleChoice!,source:'battleOrder:[3,null,0]'}}],seats)); + assert.throws(() => validateTurnActionPromises([{...p,battleChoice:{...p.battleChoice!,selected}}],seats)); +}); + +void test('an accepted native choice settles the exact Yes; No rejects the same selection atomically', () => { + const yes = promise(action(leaf())), before = structuredClone(yes); + const [recorded] = recordTurnActionBattleChoice([yes],'atreides',2,source,selected); + assert.deepEqual(yes,before); + assert.equal(recorded.fulfilled,true); assert.equal(turnActionValue(recorded),true); + assert.deepEqual(recorded.battleChoice?.selected,selected); + validateTurnActionPromises([recorded],seats); + assert.equal(recordTurnActionBattleChoice([recorded],'atreides',2,source,selected)[0],recorded); + const no = promise(action(leaf()),false), snapshot = structuredClone(no); + assert.throws(() => recordTurnActionBattleChoice([no],'atreides',2,source,selected),TurnActionError); + assert.deepEqual(no,snapshot); + const [different] = recordTurnActionBattleChoice([no],'atreides',2,source,{territory:'arrakeen',target:'fremen'}); + assert.equal(different.fulfilled,true); assert.equal(turnActionValue(different),false); + validateTurnActionPromises([different],seats); +}); + +void test('one source can satisfy OR alternatives, but never two different positive choices', () => { + const first = action(leaf()), second = action(leaf('arrakeen','fremen')); + const and = promise({kind:'and',terms:[first,second]}); + const or = promise({kind:'or',terms:[first,second]}); + assert.deepEqual([...turnActionBranches(and)],[]); + assert.equal([...turnActionBranches(or)].length,2); + const [chosen] = recordTurnActionBattleChoice([or],'atreides',2,source,selected); + assert.equal(chosen.fulfilled,true); validateTurnActionPromises([chosen],seats); + const noOr = promise({kind:'or',terms:[first,second]},false); + assert.equal([...turnActionBranches(noOr)][0].length,2); + assert.throws(() => recordTurnActionBattleChoice([noOr],'atreides',2,source,selected)); +}); + +void test('closing the original source records no fabricated battle and turn expiry releases an unfulfilled Yes', () => { + const yes = promise(action(leaf())); + const [closed] = closeTurnActionBattleChoice([yes],'atreides',2,source); + assert.equal(closed.battleChoice?.closed,true); assert.equal(closed.battleChoice?.selected,null); + assert.equal(closed.fulfilled,false); + const [expired] = finishTurnActionTurn([closed],'atreides',2); + assert.equal(expired.released,true); validateTurnActionPromises([expired],seats); + const [notChosen] = closeTurnActionBattleChoice([promise(action(leaf()),false)],'atreides',2,source); + assert.equal(notChosen.fulfilled,true); validateTurnActionPromises([notChosen],seats); + assert.throws(() => recordTurnActionBattleChoice([yes],'atreides',3,source,selected)); +});