diff --git a/components/game-table.tsx b/components/game-table.tsx index 47b1bdde..136101b2 100644 --- a/components/game-table.tsx +++ b/components/game-table.tsx @@ -153,6 +153,7 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { BattlePreparation, battlePlanCommitments, battlePlanCardValue, battlePlanCardOptions, bindBattlePlanCommitments, NexusInspectionHistory } from './battle-preparation'; import { HarassWithdrawGuide, harassWithdrawControlState } from './harass-withdraw'; +import { HarassWithdrawChoice } from './harass-withdraw-choice'; import { PrivateBattlePlan } from './private-battle-plan'; import { SpiceBankerControl, spiceBankerControlState } from './spice-banker'; import { canUsePlanetologistBattleSpecial } from '../game/leader-skill-combat'; @@ -2172,6 +2173,8 @@ export function GameTable({ ? g.decision.stage === 'offer' ? 'Rihani Decipherer — optional draw' : 'Choose your Traitor exchange' : g.decision.kind === 'sukRescue' ? 'Save your battle casualties' + : g.decision.kind === 'harassWithdraw' + ? 'Choose undialed forces to return' : g.decision.kind === 'diplomatDefense' ? 'Copy an opposing defense' : g.decision.kind === 'homeworldRevivalDeployment' @@ -2595,6 +2598,11 @@ export function GameTable({ mode: 'ignore', })} + ) : g.decision.kind === 'harassWithdraw' ? ( + <> + + + ) : g.decision.kind === 'diplomatDefense' ? ( <> diff --git a/components/harass-withdraw-choice.tsx b/components/harass-withdraw-choice.tsx new file mode 100644 index 00000000..1833a10b --- /dev/null +++ b/components/harass-withdraw-choice.tsx @@ -0,0 +1,200 @@ +'use client'; + +import { useId, useState } from 'react'; +import { splitLocation, territory } from '@/game/board'; +import type { Action, GameView } from '@/game/engine'; +import { + defaultHarassWithdrawAllocation, + harassWithdrawCommitments, + quoteHarassWithdraw, + type HarassWithdrawContext, + type HarassWithdrawForces, + type HarassWithdrawSelection, +} from '@/game/harass-withdraw'; +import { Button } from './ui/button'; +import { Input } from './ui/input'; + +function compactSelection(selection: HarassWithdrawSelection) { + return Object.fromEntries( + Object.entries(selection) + .filter(([, group]) => group.normal || group.elite) + .map(([key, group]) => [key, { ...group }]), + ); +} + +export function harassWithdrawChoiceState( + context: HarassWithdrawContext, + dial: number, + support: number, + selection: HarassWithdrawSelection, +) { + try { + const quote = quoteHarassWithdraw( + context, + dial, + support, + compactSelection(selection), + ); + return { blocked: null, quote }; + } catch (error) { + return { + blocked: + error instanceof Error + ? error.message + : 'Choose the exact forces that return.', + quote: null, + }; + } +} + +function locationLabel(key: string) { + const location = splitLocation(key); + return `${territory(location.territory).name} · sector ${location.sector}`; +} + +export function HarassWithdrawChoice({ + game: g, + act, + busy, +}: { + game: GameView; + act: (action: Action) => void; + busy: boolean; +}) { + const id = useId(); + const decision = g.decision; + const offer = g.battle?.harassAllocation; + const current = + decision?.kind === 'harassWithdraw' && + decision.player === g.me && + offer?.event === decision.event; + const context = offer?.context; + const commitments = context + ? harassWithdrawCommitments(context, offer.dial, offer.support) + : []; + const initial = context + ? (offer?.selection ?? + defaultHarassWithdrawAllocation( + context, + offer.dial, + offer.support, + commitments[0], + )) + : {}; + const [selection, setSelection] = useState(initial); + if (!current || !offer || !context) return null; + + const state = harassWithdrawChoiceState( + context, + offer.dial, + offer.support, + selection, + ); + const selectedCommitment = state.quote?.remaining; + const commitmentValue = selectedCommitment + ? `${selectedCommitment.normal}:${selectedCommitment.elite}` + : ''; + const update = ( + key: string, + kind: keyof HarassWithdrawForces, + value: number, + ) => + setSelection((previous) => ({ + ...previous, + [key]: { + normal: previous[key]?.normal ?? 0, + elite: previous[key]?.elite ?? 0, + [kind]: value, + }, + })); + + return ( +
+

Choose Harass & Withdraw forces

+

+ Your Battle Plan is revealed. Choose the exact undialed counters that + return to reserves before the Traitor decision. +

+ + + {Object.entries(context.locations) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([key, available]) => ( +
+ {locationLabel(key)} + {(['normal', 'elite'] as const).map((kind) => ( + + ))} +
+ ))} + {state.quote ? ( +

+ Return {state.quote.returned.normal} ordinary and{' '} + {state.quote.returned.elite} elite forces. +

+ ) : ( + {state.blocked} + )} + +
+ ); +} diff --git a/components/harass-withdraw.tsx b/components/harass-withdraw.tsx index 1307346b..12d8c557 100644 --- a/components/harass-withdraw.tsx +++ b/components/harass-withdraw.tsx @@ -1,4 +1,8 @@ -import { quoteHarassWithdraw, type HarassWithdrawPreview } from '@/game/harass-withdraw'; +import { + harassWithdrawNeedsAllocation, + quoteHarassWithdraw, + type HarassWithdrawPreview, +} from '@/game/harass-withdraw'; export function harassWithdrawControlState( preview: HarassWithdrawPreview | null | undefined, @@ -7,28 +11,68 @@ export function harassWithdrawControlState( support: number, ) { if (!selected) return { blocked: null, returned: null }; - if (!preview) return { blocked: 'Harass & Withdraw is not available in this battle.', returned: null }; + if (!preview) + return { + blocked: 'Harass & Withdraw is not available in this battle.', + returned: null, + }; try { - return { blocked: null, returned: quoteHarassWithdraw(preview, dial, support).returned }; + if ( + preview.allowAllocation && + harassWithdrawNeedsAllocation(preview, dial, support) + ) + return { blocked: null, returned: null }; + return { + blocked: null, + returned: quoteHarassWithdraw(preview, dial, support).returned, + }; } catch (error) { - return { blocked: error instanceof Error ? error.message : 'Choose a supported force commitment.', returned: null }; + return { + blocked: + error instanceof Error + ? error.message + : 'Choose a supported force commitment.', + returned: null, + }; } } export function HarassWithdrawGuide({ - preview, state, + preview, + state, }: { preview: HarassWithdrawPreview | null | undefined; state: ReturnType; }) { if (!preview) return null; - return
-

Harass & Withdraw

- {preview.blocked || state.blocked - ? {preview.blocked ?? state.blocked} - : state.returned - ?

Return {state.returned.normal} ordinary and {state.returned.elite} elite undialed forces to reserves when plans resolve.

- :

Select this card in either battle-card slot. Your undialed forces return to reserves.

} -

Your leader can still die. An opponent’s successful traitor call cancels the withdrawal. Discard this card after use.

-
; + return ( +
+

Harass & Withdraw

+ {preview.blocked || state.blocked ? ( + {preview.blocked ?? state.blocked} + ) : state.returned ? ( +

+ Return {state.returned.normal} ordinary and {state.returned.elite}{' '} + elite undialed forces to reserves when plans resolve. +

+ ) : preview.allowAllocation ? ( +

+ After plans are revealed, choose exactly which undialed ordinary and + elite forces return to reserves. +

+ ) : ( +

+ Select this card in either battle-card slot. Your undialed forces + return to reserves. +

+ )} +

+ Your leader can still die. An opponent’s successful traitor call cancels + the withdrawal. Discard this card after use. +

+
+ ); } diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md index 376203bd..33d9db02 100644 --- a/docs/CURRENT_STATUS.md +++ b/docs/CURRENT_STATUS.md @@ -6,19 +6,19 @@ gated.** Prototypes do not open completion or publication gates. ## Current checkpoint and work -Latest verified checkpoint: `368a7a5`, [reusable game samples](VERIFICATION_WORKFLOW.md#reusable-base-and-faction-sample-games). -Types, lint and **4,823 offline tests** passed. Ten genuine base samples and -six expansion samples completed in 6,746 accepted actions with 175 periodic -save/restore checks. Base samples had no rejected candidates; expansion samples -retained 82 guarded arrival candidates before legal alternatives. The tooling -checkpoint changed no application, dependency, HTTP or database code. -All 1,038 opening games and original seat/recovery records were unchanged. +Latest verified checkpoint: `6403425`, [AI arrival preflight](BOT_ARRIVAL_PREFLIGHT.md). +Types, lint and **4,829 offline tests** passed. Eighteen genuine base and expansion +samples completed in 9,470 accepted actions with 247 periodic save/restore checks +and no rejected candidates. Accepted gameplay matched the prior same-seed runs +apart from random event identifiers. All 1,038 opening games and original +seat/recovery records were unchanged; the browser test seat reconnected. Earlier evidence remains in the [implementation history](IMPLEMENTATION_STATUS.md). The connected [Harass & Withdraw prototype](HARASS_WITHDRAW_RUNTIME.md) supports either battle-card slot, private category inspections, exact undialed normal/elite returns, opponent-Traitor cancellation, mandatory disposal, controls and all -four AI profiles. Physical allocation must be unique. Richese card combinations +four AI profiles. New battles also have [revealed physical allocation](HARASS_ALLOCATION.md) for +ordinary/elite mixtures and multi-sector returns. Richese card combinations and additional optional modules stay gated. Withdrawal before explosion and card-specific discard precedence are explicitly labeled inferences. The Stone Burner timing question is pending; no user answer is assumed. Reinforcements @@ -30,12 +30,11 @@ and foreign-key checks passed, and refresh restored the test seat. No restart, database reset or recurring automation was needed. Exact verification, source fingerprints and delivery are recorded in the private report and Git message. -Current work: [AI arrival preflight](BOT_ARRIVAL_PREFLIGHT.md) reuses the engine's -existing reaction quote to avoid repeatedly proposing guarded ordinary entries. -The adapter preserves legal single reactions, faction exemptions, contribution -routing and private information; specialized routes retain their own adapters. -The Moritani Secret Ally audit retains the shared pending hidden-reaction UX -question. No arrival-order ruling or module/publication gate is changed. +Current work: [Harass force allocation](HARASS_ALLOCATION.md) connects the missing +player choice after reveal, with shared legal AI, exact winner losses and saved +continuation. Unique returns stay automatic and sealed plans stay unchanged. +The remaining Leader Skill bands retain their existing pending rulings; this +checkpoint introduces no new arrival-order or hidden-reaction policy. ## Authoritative navigation diff --git a/docs/HARASS_ALLOCATION.md b/docs/HARASS_ALLOCATION.md new file mode 100644 index 00000000..cb1c20f4 --- /dev/null +++ b/docs/HARASS_ALLOCATION.md @@ -0,0 +1,54 @@ +# Harass & Withdraw physical allocation + +14 September 2026. A connected prototype now supports the ordinary/elite and +multi-sector choices previously rejected as ambiguous. The existing card, +mode and combination restrictions remain in force. + +## Timing and information + +The [source contract](ECAZ_TREACHERY_RULES.md) and +[Harass runtime](HARASS_WITHDRAW_RUNTIME.md) place withdrawal when Battle Plans +are revealed. Counter identity and sector allocation are not printed Battle +Plan elements. Before sealing, the engine therefore checks that a legal physical +allocation exists. It does not ask for or reveal a future allocation through +Prescience or complete-plan inspection. + +After both plans are public, a uniquely determined return proceeds automatically. +When multiple physical commitments or sector allocations are legal, the owner +chooses every undialed ordinary and elite counter before Traitor declarations. +There is no decline or partial-return alternative. The selected allocation then +becomes public. Physical transfer still waits for the existing atomic Traitor +settlement, so an opposing successful call cancels the return without rollback. +This applies the printed reveal timing to a digital choice; it does not establish +an order among currently excluded optional-module effects. + +## Connected behavior + +The shared quote validates an exact complement of one legal physical dial/support +commitment, each location's typed supply, integer counters and complete return. +The revealed panel selects a physical commitment and permits editing each sector. +All four AI profiles use the same deterministic legal allocation. Their pre-plan +estimate is not a binding early choice and is not added to the sealed plan. + +New battles carry a version marker. A saved choice binds its battle, owner, +event, revealed plans and force locations. Missing or inconsistent state rejects +before views, normalization or action writes. Refresh restores a pending choice; +concurrent submissions select once through the existing room version check. +Previously valid unversioned battles keep their unique automatic derivation. + +After an executed withdrawal, winner casualties must equal the already chosen +dialed counters. Recalculating a smaller physical commitment could incorrectly +leave an ordinary or elite force behind. The resolution quote now restricts its +casualty options to that exact remaining group. Traitor cancellation retains +ordinary original-force losses. Card disposal and subsequent Face Dancer cleanup +reuse the existing continuation. + +## Evidence and limits + +Pure, real-engine, all-profile, controls and in-memory SQLite cases cover typed +and sector choices, no early disclosure, exact losses, traitor cancellation, +legacy continuation, malformed saves, concurrent selection and restoration. +The final check/build, sample and browser results are recorded in the private +source-bound checkpoint and Git message. Samples are evidence only for their +observed configurations and actions. This is not complete Ecaz card-variant or +combined-expansion certification. diff --git a/docs/HARASS_WITHDRAW_RUNTIME.md b/docs/HARASS_WITHDRAW_RUNTIME.md index 740a52bc..60ff2848 100644 --- a/docs/HARASS_WITHDRAW_RUNTIME.md +++ b/docs/HARASS_WITHDRAW_RUNTIME.md @@ -46,7 +46,7 @@ plan still contains its exact ID. Complete-plan inspection reveals the actual physical plan; Truthtrance's existing literal slot-occupancy promises keep their meaning. An empty-category answer is not a promise that the physical slot is empty. -The shared physical quote derives dialed counters from `casualtyOptions`, then +The shared physical quote validates dialed counters from `casualtyOptions`, then returns the undialed normal and elite counters to their owner's reserves. The leader resolves normally. An opponent's successful Traitor call, including mutual calls, cancels withdrawal. Returned reserves are outside subsequent board losses @@ -54,7 +54,9 @@ and Face Dancer replacement. Harass is discarded once and excluded from ordinary winner retention and Moritani ally retention. Both selectors enforce the complete pair in either selection order. The private -guide shows the exact return and a reason for an unsupported choice. All four AI +guide explains unique returns or the later revealed allocation choice. The +[physical allocation follow-up](HARASS_ALLOCATION.md) connects typed and sector +selection after reveal, with exact committed winner losses. All four AI profiles use the same physical quote and category-aware inspection comparison; the card adds no fictitious weapon or defense value. Stronger profiles value saved forces when expecting defeat and discourage use when expecting to win. @@ -62,10 +64,9 @@ This is a legal strategy path, not strength calibration. ## Current boundaries -- Basic and Advanced physical allocations must identify one normal/elite - commitment and one return allocation among sectors. Zero/all returns and - unique typed allocations are supported. Ambiguous allocations reject before - sealing; explicit private allocation controls remain unfinished. +- Basic and Advanced now support explicit ordinary/elite and sector allocation + after reveal. Unique returns are automatic; previously valid legacy battles + retain unique-only derivation. See the [allocation contract](HARASS_ALLOCATION.md). - Additional optional modules remain gated, including Homeworlds, Nexus, Leader Skills, Tech Tokens, Stronghold Cards and Discoveries. This includes the printed own-Homeworld prohibition without claiming other Homeworld diff --git a/docs/IMPLEMENTATION_STATUS.md b/docs/IMPLEMENTATION_STATUS.md index 609d2609..192f76b8 100644 --- a/docs/IMPLEMENTATION_STATUS.md +++ b/docs/IMPLEMENTATION_STATUS.md @@ -1,5 +1,17 @@ # Dune implementation status +## 14 September 2026 — Harass revealed physical allocation + +Connected ordinary/elite and multi-sector choices after public plan reveal, +before Traitor declarations. Unique returns remain automatic; selected counters +are public but stay on board until atomic Traitor settlement. The shared quote, +player controls, four AI profiles and versioned saved decision preserve exact +custody and existing mode gates. Winner casualties cannot choose a smaller +physical commitment after its undialed complement has returned. See +[the allocation contract](HARASS_ALLOCATION.md) for source timing and limits; +source-bound final evidence and delivery remain in the private report/Git message. + + ## 14 September — AI ordinary arrival preflight diff --git a/game/battle-resolution-quote.ts b/game/battle-resolution-quote.ts index 3e2f98a8..bcd3188c 100644 --- a/game/battle-resolution-quote.ts +++ b/game/battle-resolution-quote.ts @@ -28,7 +28,7 @@ import { type StoneBurnerComparison, } from './stone-burner'; import { matchingTraitor } from './traitors'; -import { HARASS_WITHDRAW_CARD, isHarassWithdraw, quoteHarassWithdraw, type HarassWithdrawContext, type HarassWithdrawQuote } from './harass-withdraw'; +import { HARASS_WITHDRAW_CARD, isHarassWithdraw, quoteHarassWithdraw, type HarassWithdrawContext, type HarassWithdrawQuote, type HarassWithdrawSelection } from './harass-withdraw'; import { auditCount } from './choam-auditor'; import { sukGraduateSkill, type SukGraduateSkill } from './suk-graduate'; import { validateSpiceBankerSpend } from './spice-banker'; @@ -75,6 +75,7 @@ export type ResolutionParticipant = { }; export type ResolutionCombatant = ResolutionParticipant & { harassWithdraw?: HarassWithdrawContext; + harassSelection?: HarassWithdrawSelection; diplomatDefense?: Pick & { card: string }; spice: number; hand: readonly Card[]; @@ -371,7 +372,7 @@ function calculate(input: BattleResolutionInput): BattleResolutionQuote { requireQuote(!slots.some(c => c?.id === 'ecaz-reinforcements'), 'Reinforcements battle effects are still being implemented.'); const harass = slots.some(isHarassWithdraw); - requireQuote(!side.harassWithdraw || harass, 'The withdrawal context requires the physical Harass & Withdraw card.'); + requireQuote((!side.harassWithdraw && side.harassSelection === undefined) || harass, 'The withdrawal context requires the physical Harass & Withdraw card.'); if (harass) { requireQuote(validBattleSlotPair(slots[0], slots[1]), 'The Harass & Withdraw plan has an invalid weapon and defense pair.'); @@ -379,7 +380,7 @@ function calculate(input: BattleResolutionInput): BattleResolutionQuote { 'Harass & Withdraw needs its supported physical context; Homeworld and Stone Burner combinations remain unfinished.'); requireQuote(JSON.stringify(side.harassWithdraw.forces) === JSON.stringify(side.forces), 'The withdrawal context must match the current battle force roles.'); - withdrawals.set(side.id, quoteHarassWithdraw(side.harassWithdraw, side.plan.dial, side.plan.support)); + withdrawals.set(side.id, quoteHarassWithdraw(side.harassWithdraw, side.plan.dial, side.plan.support, side.harassSelection)); } } const tie = @@ -662,11 +663,15 @@ function calculate(input: BattleResolutionInput): BattleResolutionQuote { homeworld || winner.faction === 'ixians' ) { + const withdrawal = harassWithdraw.find(entry => entry.player === winner.id); + // Withdrawal already identifies every undialed counter. Do not choose a + // smaller physical commitment a second time after returning its complement. const options = casualtyOptions( - harassWithdraw.find(entry => entry.player === winner.id)?.remaining ?? winner.forces, + withdrawal?.remaining ?? winner.forces, winner.plan.dial, winner.plan.support, - ); + ).filter(option => !withdrawal || + option.normal === withdrawal.remaining.normal && option.elite === withdrawal.remaining.elite); requireQuote( options.length > 0, 'No valid casualty choice remains for this battle.', diff --git a/game/bots.ts b/game/bots.ts index ac38520a..7cf68581 100644 --- a/game/bots.ts +++ b/game/bots.ts @@ -3,7 +3,7 @@ import { recruitsPlayAction } from './recruits'; import type { Card } from './cards'; import { bureaucratBattlePenalty, canUsePlanetologistBattleSpecial, leaderSkillBattleBonus } from './leader-skill-combat'; import { battleCardSlotEligible, battleCategoryInspectionValue, fixedBattleInspectionMatches, validBattleSlotPair, type BattlePlanInspectionField } from './battle-card-slots'; -import { quoteHarassWithdraw } from './harass-withdraw'; +import { defaultHarassWithdrawAllocation, quoteHarassWithdraw } from './harass-withdraw'; import { leaderSkillStrongholdCount } from './leader-skill-battle-board'; import { discoveryFlightBotActions } from './discovery-flight-options'; import { discoveryEntryBotActions } from './discovery-entry-options'; @@ -936,7 +936,10 @@ function plans(g: GameView): Action[] { if (harass) { if (!b.harassWithdraw) continue; try { - const quote = quoteHarassWithdraw(b.harassWithdraw, Number(action.dial), Number(action.support ?? 0)); + const allocation = b.harassWithdraw.allowAllocation + ? defaultHarassWithdrawAllocation(b.harassWithdraw, Number(action.dial), Number(action.support ?? 0)) + : undefined; + const quote = quoteHarassWithdraw(b.harassWithdraw, Number(action.dial), Number(action.support ?? 0), allocation); withdrawn = quote.returned.normal + quote.returned.elite; } catch { continue; } } @@ -1465,6 +1468,12 @@ function policyActions(g: GameView): Action[] { if (g.decision.player !== me.id) return []; const d = g.decision; if (d.kind === 'leaderSkillVisibility' || d.kind === 'leaderSkillRevival' || d.kind === 'mentatQuestion' || d.kind === 'bureaucratPayment') return []; + if (d.kind === 'harassWithdraw') { + const offer = g.battle?.harassAllocation; + if (!offer || offer.event !== d.event) return []; + return [{ type: 'decision', event: d.event, + returns: offer.selection ?? defaultHarassWithdrawAllocation(offer.context, offer.dial, offer.support) }]; + } if (d.kind === 'choamAudit') return [{ type: 'decision', event: d.event, audit: true }]; if (d.kind === 'choamAuditPayment') { diff --git a/game/engine.ts b/game/engine.ts index 8171cec5..0876a795 100644 --- a/game/engine.ts +++ b/game/engine.ts @@ -17,7 +17,7 @@ import { spiceBankerModeSupported, validateSpiceBankerSpend } from './spice-bank import { quoteDiplomatDefense, diplomatDefenseModeSupported, type DiplomatDefenseQuote } from './diplomat-defense'; import { ECAZ_START_FORCES, quoteEcazStartingForces } from './ecaz-setup'; import { battleCardSlotEligible, battleCategoryInspectionValue, fixedBattleInspectionMatches, validBattleSlotPair } from './battle-card-slots'; -import { HARASS_WITHDRAW_CARD, HarassWithdrawError, isHarassWithdraw, quoteHarassWithdraw, type HarassWithdrawContext, type HarassWithdrawPreview } from './harass-withdraw'; +import { HARASS_WITHDRAW_CARD, HarassWithdrawError, isHarassWithdraw, quoteHarassWithdraw, defaultHarassWithdrawAllocation, harassWithdrawNeedsAllocation, type HarassWithdrawSelection, type HarassWithdrawContext, type HarassWithdrawPreview } from './harass-withdraw'; import { discoveryChoices, discoveryStashSignature, type DiscoveryStash } from './discovery-actions'; import { createStormSource, validateStormSource, discoveryStormOffer, createDiscoveryStorm, chooseDiscoveryStorm, validateDiscoveryStorm, finishDiscoveryStorm, type StormMovementSource, type DiscoveryStorm } from './discovery-storm'; import { completeDiscoveryFlight, discoveryFlightOffer, quoteDiscoveryFlight, validateDiscoveryFlight, type DiscoveryFlightReceipt } from './discovery-flight'; @@ -606,7 +606,15 @@ export type DiplomatDefenseReceipt = DiplomatDefenseQuote & { card: string | null; signature: string; }; +export type HarassAllocationReceipt = { + player: string; event: string; battle: string; turn: number; frame: string; + stage: 'offered' | 'selected'; selection: HarassWithdrawSelection | null; signature: string; +}; export type Battle = { + /** New battles allow physical withdrawal choice after reveal, never in the sealed plan. */ + harassAllocationVersion?: 1; + harassAllocationEvent?: string; + harassAllocation?: HarassAllocationReceipt; /** Scheduling owner; physical combat slots and aggressor remain independent. */ chooser?: string; chooserEvent?: string; @@ -678,6 +686,7 @@ export type Auction = { allyPayment?: number; }; export type Decision = + | { kind: 'harassWithdraw'; player: string; event: string } | { kind: 'diplomatDefense'; player: string; event: string; cards: string[]; source: string } | { kind: 'leaderSkillVisibility'; player: string; event: string; resumePowers?: boolean } | { kind: 'leaderSkillRevival'; player: string; event: string } @@ -5250,6 +5259,7 @@ function leaderSkillsIntegrity(g: Game) { bureaucratPaymentIntegrity(g); mentatQuestionIntegrity(g); diplomatDefenseIntegrity(g); + harassAllocationIntegrity(g); const noFieldShipment = leaderSkillNoFieldIntegrity(g); sandmasterIntegrity(g); sukRescueIntegrity(g); @@ -13550,7 +13560,11 @@ function harassWithdrawContext(g: Game, p: Player): HarassWithdrawContext { } function currentHarassWithdrawQuote(g: Game, p: Player, plan: Pick) { try { - const quote = quoteHarassWithdraw(harassWithdrawContext(g, p), plan.dial, plan.support); + const context = harassWithdrawContext(g, p); + const receipt = g.battle?.harassAllocation; + const selection = receipt?.player === p.id && receipt.stage === 'selected' ? receipt.selection! : + g.battle?.harassAllocationVersion === 1 ? defaultHarassWithdrawAllocation(context, plan.dial, plan.support) : undefined; + const quote = quoteHarassWithdraw(context, plan.dial, plan.support, selection); validateHarassReturnCounters(p, quote.returned); return quote; } @@ -13567,7 +13581,7 @@ function harassWithdrawPreview(g: Game, p: Player): HarassWithdrawPreview | null const b = g.battle; if (!b || ![b.attacker, b.defender].includes(p.id) || !p.hand.some(isHarassWithdraw)) return null; const context = harassWithdrawContext(g, p); - return { ...context, card: HARASS_WITHDRAW_CARD, + return { ...context, card: HARASS_WITHDRAW_CARD, allowAllocation: b.harassAllocationVersion === 1, blocked: context.blocked ?? (b.revealed || b.plans[p.id] ? 'Your Battle Plan is already sealed.' : null) }; } function validateResidualPoison( @@ -15267,8 +15281,76 @@ function offerDiplomatDefense(g: Game): boolean { { faction: getPlayer(g, offer.player).faction, name: 'Diplomat defense' }); return true; } +function harassAllocationOffer(g: Game) { + const b = g.battle; + if (!b?.revealed || b.harassAllocationVersion !== 1) return null; + for (const id of [b.attacker, b.defender]) { + const p = getPlayer(g, id), plan = b.plans[id]; + if (![plan.weapon, plan.defense].includes(HARASS_WITHDRAW_CARD)) continue; + const context = harassWithdrawContext(g, p); + try { + if (harassWithdrawNeedsAllocation(context, plan.dial, plan.support)) + return { player: id, context, dial: plan.dial, support: plan.support }; + } catch (error) { if (error instanceof HarassWithdrawError) throw new RuleError(error.message); throw error; } + } + return null; +} +function harassAllocationFrame(g: Game): string { + const b = g.battle!; + return JSON.stringify({ battle: b.event, turn: g.turn, territory: b.territory, + attacker: b.attacker, defender: b.defender, plans: b.plans, offer: harassAllocationOffer(g) }); +} +function harassAllocationSignature(receipt: HarassAllocationReceipt): string { + return JSON.stringify({ ...receipt, signature: undefined }); +} +function harassAllocationIntegrity(g: Game) { + const b = g.battle, decisions = homeworldSavedDecisions(g).filter(d => d.kind === 'harassWithdraw'); + if (b?.harassAllocationVersion === undefined && b?.harassAllocation === undefined && + b?.harassAllocationEvent === undefined && !decisions.length) return; + requireRule(b && b.harassAllocationVersion === 1, 'The saved withdrawal choice lost its original battle version.'); + const receipt = b.harassAllocation, offer = harassAllocationOffer(g); + if (!receipt) { + requireRule(receipt === undefined && b.harassAllocationEvent === undefined && !decisions.length && !offer, + 'The revealed Harass & Withdraw plan lost its physical allocation choice.'); + return; + } + requireRule(g.status === 'playing' && g.phase === 6 && b.revealed && offer && + receipt.player === offer.player && receipt.battle === b.event && receipt.turn === g.turn && + typeof receipt.event === 'string' && receipt.event.length > 0 && receipt.event === b.harassAllocationEvent && + receipt.frame === harassAllocationFrame(g) && receipt.signature === harassAllocationSignature(receipt) && + ['offered', 'selected'].includes(receipt.stage), + 'The saved withdrawal choice changed its revealed plan, force locations or event.'); + requireRule(decisions.length === (receipt.stage === 'offered' ? 1 : 0), + 'The saved withdrawal choice lost or reopened its unique decision.'); + if (receipt.stage === 'offered') requireRule(receipt.selection === null && !Object.keys(b.traitorCalls).length, + 'Choose undialed forces before any traitor declarations.'); + else { + requireRule(receipt.selection !== null, 'The saved withdrawal choice lost its selected counters.'); + try { quoteHarassWithdraw(offer.context, offer.dial, offer.support, receipt.selection); } + catch (error) { if (error instanceof HarassWithdrawError) throw new RuleError(error.message); throw error; } + } + for (const decision of decisions) requireRule(decision.player === receipt.player && decision.event === receipt.event && + Object.keys(decision).every(key => ['kind', 'player', 'event'].includes(key)), + 'The withdrawal decision no longer matches its original owner and event.'); +} +function offerHarassAllocation(g: Game): boolean { + const b = g.battle!; + if (b.harassAllocation || b.harassAllocationVersion !== 1) return false; + const offer = harassAllocationOffer(g); + if (!offer) return false; + requireRule(b.event && !Object.keys(b.traitorCalls).length, 'Choose withdrawal counters immediately after reveal.'); + const event = crypto.randomUUID(); + const receipt: HarassAllocationReceipt = { player: offer.player, event, battle: b.event, turn: g.turn, + frame: harassAllocationFrame(g), stage: 'offered', selection: null, signature: '' }; + receipt.signature = harassAllocationSignature(receipt); + b.harassAllocation = receipt; b.harassAllocationEvent = event; + g.decision = { kind: 'harassWithdraw', player: offer.player, event }; + log(g, `${getPlayer(g, offer.player).name} must identify all undialed forces returned by Harass & Withdraw before traitor declarations.`); + return true; +} function nextRevealedDecision(g: Game) { const b = g.battle!; + if (offerHarassAllocation(g)) return; if (offerDiplomatDefense(g)) return; const stoneOwner = [b.attacker, b.defender].find( (id) => @@ -15345,7 +15427,9 @@ function currentBattleResolutionQuote(g: Game, canceledVoter?: string) { occupiedStrongholds: leaderSkillStrongholdCount(g, p), forces: combatForces(g, p, b.territory, opponent), ...([cardOf(p, plan.weapon), cardOf(p, plan.defense)].some(isHarassWithdraw) - ? { harassWithdraw: harassWithdrawContext(g, p) } : {}), + ? { harassWithdraw: harassWithdrawContext(g, p), + ...(b.harassAllocation?.player === p.id && b.harassAllocation.stage === 'selected' + ? { harassSelection: b.harassAllocation.selection! } : {}) } : {}), stronghold: strongholdEffect(g, p.id), lateDefense: b.lateDefense?.[p.id], ...(b.diplomatDefense?.stage === 'copied' && b.diplomatDefense.player === p.id @@ -21643,6 +21727,20 @@ function applyActionInner( if (harkonnen) returnCaptives(g, harkonnen); settleAdvisors(g); finishBattle(g); + } else if (decision.kind === 'harassWithdraw') { + const receipt = g.battle?.harassAllocation, offer = harassAllocationOffer(g); + requireRule(Object.keys(action).every(key => ['type', 'event', 'returns'].includes(key)) && + action.event === decision.event && receipt?.event === decision.event && receipt.player === id && + receipt.stage === 'offered' && offer && action.returns !== undefined, + 'Choose all undialed forces for this exact revealed Harass & Withdraw plan.'); + let quote; + try { quote = quoteHarassWithdraw(offer.context, offer.dial, offer.support, action.returns as HarassWithdrawSelection); } + catch (error) { if (error instanceof HarassWithdrawError) throw new RuleError(error.message); throw error; } + validateHarassReturnCounters(p, quote.returned); + receipt.selection = structuredClone(quote.locations); receipt.stage = 'selected'; + receipt.signature = harassAllocationSignature(receipt); + log(g, `${p.name} selected ${quote.returned.normal} ordinary and ${quote.returned.elite} elite undialed forces for Harass & Withdraw: ${Object.entries(quote.locations).map(([key, group]) => `${key} (${group.normal} ordinary, ${group.elite} elite)`).join('; ')}. The return waits for traitor declarations; an opposing successful call cancels it.`); + nextRevealedDecision(g); } else if (decision.kind === 'diplomatDefense') { const receipt = g.battle?.diplomatDefense; requireRule(Object.keys(action).every(key => ['type', 'event', 'card'].includes(key)) && @@ -23690,6 +23788,7 @@ function applyActionInner( event: battleEvent, ...(g.mentatQuestionPreview === true && g.leaderSkills && mentatQuestionModeSupported(g) ? { mentatQuestionVersion: 1 as const } : {}), ...(g.leaderSkills && diplomatDefenseModeSupported(g) ? { diplomatDefenseVersion: 1 as const } : {}), + ...(g.ecazTreachery ? { harassAllocationVersion: 1 as const } : {}), ...(byFaction(g, 'richese') ? { preLeader: { event: battleEvent, ready: [], closed: false } } : {}), @@ -25000,6 +25099,12 @@ export function viewGame(state: Game, id: string) { source: b.diplomatDefense.source, kind: b.diplomatDefense.kind, stage: b.diplomatDefense.stage, card: b.diplomatDefense.card } : null, + harassAllocation: b.revealed && b.harassAllocation && + (b.harassAllocation.player === id || b.harassAllocation.stage === 'selected') + ? { event: b.harassAllocation.event, context: harassWithdrawContext(g, getPlayer(g, b.harassAllocation.player)), + dial: b.plans[b.harassAllocation.player].dial, support: b.plans[b.harassAllocation.player].support, + selection: b.harassAllocation.selection ? structuredClone(b.harassAllocation.selection) : null } + : null, fullPlan: b.fullPlan ?? null, fullPlanInsight: b.fullPlan?.owner === id && diff --git a/game/harass-withdraw.ts b/game/harass-withdraw.ts index d2928a5b..e4f22676 100644 --- a/game/harass-withdraw.ts +++ b/game/harass-withdraw.ts @@ -8,6 +8,9 @@ import { ecazTreacheryDefinition } from './ecaz-cards'; export const HARASS_WITHDRAW_CARD = 'ecaz-harass-withdraw' as const; export type HarassWithdrawForces = Readonly<{ normal: number; elite: number }>; +export type HarassWithdrawSelection = Readonly< + Record +>; export type HarassWithdrawContext = Readonly<{ blocked: string | null; forces: CombatForces; @@ -16,6 +19,8 @@ export type HarassWithdrawContext = Readonly<{ export type HarassWithdrawPreview = HarassWithdrawContext & Readonly<{ card: typeof HARASS_WITHDRAW_CARD; + /** New battle protocol allows the physical return to be chosen after reveal. */ + allowAllocation?: boolean; }>; export type HarassWithdrawQuote = { returned: { normal: number; elite: number }; @@ -39,12 +44,29 @@ export function isHarassWithdraw(card: Card | undefined): boolean { function requireHarass(condition: unknown, message: string): asserts condition { if (!condition) throw new HarassWithdrawError(message); } -/** Resolve only the user's physical counters. Neither opposing plans nor outcomes are inputs. */ -export function quoteHarassWithdraw( - context: HarassWithdrawContext, - dial: number, - support: number, -): HarassWithdrawQuote { +function record(value: unknown): value is Record { + return ( + !!value && + typeof value === 'object' && + !Array.isArray(value) && + [Object.prototype, null].includes(Object.getPrototypeOf(value)) + ); +} +function physicalGroup(value: unknown): value is HarassWithdrawForces { + return ( + record(value) && + Object.keys(value).sort().join(',') === 'elite,normal' && + [value.normal, value.elite].every( + (n) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0, + ) + ); +} +function validateContext(context: HarassWithdrawContext) { + requireHarass( + record(context) && + (context.blocked === null || typeof context.blocked === 'string'), + 'Harass & Withdraw needs a valid physical battle context.', + ); requireHarass( !context.blocked, context.blocked ?? 'Harass & Withdraw is unavailable.', @@ -54,32 +76,158 @@ export function quoteHarassWithdraw( validCombatForces(forces) && !forces.temporaryElite, 'Harass & Withdraw needs ordinary physical force roles.', ); + requireHarass( + record(context.locations), + 'Harass & Withdraw needs named physical force locations.', + ); const locations = Object.entries(context.locations); requireHarass( - locations.every( - ([key, group]) => - key.length > 0 && - group && - Object.keys(group).sort().join(',') === 'elite,normal' && - [group.normal, group.elite].every( - (n) => Number.isSafeInteger(n) && n >= 0, - ), - ) && + locations.every(([key, group]) => key.length > 0 && physicalGroup(group)) && locations.reduce((n, [, group]) => n + group.normal, 0) === forces.normal && locations.reduce((n, [, group]) => n + group.elite, 0) === forces.elite, 'Harass & Withdraw must match the user’s physical forces in this battle.', ); - const choices = casualtyOptions(forces, dial, support); + return locations; +} +/** Distinct physical dial commitments; equivalent support allocations are not extra choices. */ +export function harassWithdrawCommitments( + context: HarassWithdrawContext, + dial: number, + support: number, +): { normal: number; elite: number }[] { + validateContext(context); + const choices = casualtyOptions(context.forces, dial, support); requireHarass( choices.length > 0, 'Dial and spice must match a legal physical force commitment.', ); - const physical = [ + return [ ...new Map( - choices.map((choice) => [`${choice.normal}:${choice.elite}`, choice]), + choices.map(({ normal, elite }) => [ + `${normal}:${elite}`, + { normal, elite }, + ]), ).values(), ]; +} +function ambiguousAllocation( + context: HarassWithdrawContext, + physical: readonly HarassWithdrawForces[], +) { + if (physical.length !== 1) return true; + return (['normal', 'elite'] as const).some((type) => { + const returned = context.forces[type] - physical[0][type]; + return ( + returned !== 0 && + returned !== context.forces[type] && + Object.values(context.locations).filter((group) => group[type] > 0) + .length > 1 + ); + }); +} +/** Invalid plans still throw; true means only a legal physical/sector choice remains. */ +export function harassWithdrawNeedsAllocation( + context: HarassWithdrawContext, + dial: number, + support: number, +): boolean { + return ambiguousAllocation( + context, + harassWithdrawCommitments(context, dial, support), + ); +} +/** Stable fallback policy only: the selected (or first legal) commitment, then sorted locations. */ +export function defaultHarassWithdrawAllocation( + context: HarassWithdrawContext, + dial: number, + support: number, + selected?: HarassWithdrawForces, +): Record { + const choices = harassWithdrawCommitments(context, dial, support); + requireHarass( + selected === undefined || + (physicalGroup(selected) && + choices.some( + (choice) => + choice.normal === selected.normal && + choice.elite === selected.elite, + )), + 'Choose one legal physical dial commitment before allocating its return.', + ); + const commitment = selected ?? choices[0]; + const remaining = { + normal: context.forces.normal - commitment.normal, + elite: context.forces.elite - commitment.elite, + }; + return Object.fromEntries( + Object.entries(context.locations) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .flatMap(([key, group]) => { + const returned = { + normal: Math.min(remaining.normal, group.normal), + elite: Math.min(remaining.elite, group.elite), + }; + remaining.normal -= returned.normal; + remaining.elite -= returned.elite; + return returned.normal || returned.elite ? [[key, returned]] : []; + }), + ); +} +/** Resolve only the user's physical counters. Neither opposing plans nor outcomes are inputs. */ +export function quoteHarassWithdraw( + context: HarassWithdrawContext, + dial: number, + support: number, + selection?: HarassWithdrawSelection, +): HarassWithdrawQuote { + const physical = harassWithdrawCommitments(context, dial, support); + const forces = context.forces; + if (selection !== undefined) { + requireHarass( + record(selection), + 'Choose the returned physical forces by location.', + ); + const entries = Object.entries(selection); + requireHarass( + entries.every( + ([key, group]) => + Object.hasOwn(context.locations, key) && + physicalGroup(group) && + group.normal <= context.locations[key].normal && + group.elite <= context.locations[key].elite, + ), + 'Returned forces must be whole available normal and elite counters at known battle locations.', + ); + const returned = entries.reduce( + (sum, [, group]) => ({ + normal: sum.normal + group.normal, + elite: sum.elite + group.elite, + }), + { normal: 0, elite: 0 }, + ); + const committed = physical.find( + (choice) => + choice.normal === forces.normal - returned.normal && + choice.elite === forces.elite - returned.elite, + ); + requireHarass( + committed, + 'The returned counters must be the exact undialed complement of a legal physical commitment.', + ); + return { + returned, + remaining: { ...forces, ...committed }, + locations: Object.fromEntries( + entries + .filter(([, group]) => group.normal || group.elite) + .map(([key, group]) => [ + key, + { normal: group.normal, elite: group.elite }, + ]), + ), + }; + } requireHarass( physical.length === 1, 'Harass & Withdraw with an ambiguous regular/elite commitment is still being implemented. Choose a uniquely determined physical commitment.', @@ -89,7 +237,8 @@ export function quoteHarassWithdraw( normal: forces.normal - committed.normal, elite: forces.elite - committed.elite, }; - const allocation: HarassWithdrawQuote['locations'] = {}; + const locations = Object.entries(context.locations); + const allocation = new Map(); for (const type of ['normal', 'elite'] as const) { const amount = returned[type], occupied = locations.filter(([, group]) => group[type] > 0); @@ -97,6 +246,7 @@ export function quoteHarassWithdraw( amount === 0 || amount === forces[type] || occupied.length === 1, 'Harass & Withdraw with an ambiguous allocation among sectors is still being implemented. Choose a uniquely determined physical commitment.', ); + // Preserve legacy insertion order as well as the uniquely determined counts. for (const [key, group] of occupied) { const count = amount === forces[type] @@ -104,12 +254,16 @@ export function quoteHarassWithdraw( : occupied.length === 1 ? amount : 0; - if (count) (allocation[key] ??= { normal: 0, elite: 0 })[type] = count; + if (count) { + const selected = allocation.get(key) ?? { normal: 0, elite: 0 }; + selected[type] = count; + allocation.set(key, selected); + } } } return { returned, remaining: { ...forces, normal: committed.normal, elite: committed.elite }, - locations: allocation, + locations: Object.fromEntries(allocation), }; } diff --git a/game/reference.ts b/game/reference.ts index e14b442f..58c13b3a 100644 --- a/game/reference.ts +++ b/game/reference.ts @@ -3713,16 +3713,16 @@ export const RULE_TOPICS: RuleTopic[] = [ 'When Atreides asks for that weapon or defense category, answer None without exposing Harass & Withdraw. The category is fixed, while the special card may occupy its physical slot. A literal Truthtrance promise that a slot is empty still means no physical card.', 'Return your undialed ordinary and elite forces to reserves. Your leader can still be killed. An opponent’s successful Traitor call cancels withdrawal, including mutual calls. A Face Dancer cannot replace the forces already returned.', 'Discard Harass after use, including a win by your own Traitor call. Reveal-before-explosion return and card-specific discard precedence are explicit implementation inferences; neither is a dedicated combined FAQ ruling.', - 'The battle controls show the exact return. Basic and Advanced commitments need a unique physical allocation. Ambiguous regular/elite or sector choices, Richese card combinations and additional optional modules are still being integrated. The printed card forbids use on your own Homeworld.', + 'For multiple legal physical allocations, choose all undialed ordinary and elite counters by sector after both plans reveal and before traitor declarations. Unique returns are automatic. The selected return is public; it is not an extra sealed plan element. Richese card combinations and additional optional modules remain guarded. The printed card forbids use on your own Homeworld.', 'With Ecaz and an ally together, only the card user’s undialed forces return. Combined army attribution remains unfinished. Public variant starts and complete rules acceptance remain gated.', ], related: ['battle-cards', 'battle', 'card-recruits', 'ecaz-modules', 'implementation-checklist'], checklist: [ - { area: 'Implementation', status: 'Partial', detail: 'Physical slot commitment, category inspection, unique typed return before losses, opponent-Traitor cancellation, mandatory disposal and saved continuation are connected. Richese and optional-module combinations remain gated.', evidence: ['game/harass-withdraw.ts', 'game/battle-card-slots.ts', 'game/battle-resolution-quote.ts', 'game/engine.ts'] }, - { area: 'Player controls', status: 'Partial', detail: 'Either slot, compatible pair selection, category-null commitment, exact private return guide and card inspection are usable. Ambiguous allocation controls remain unfinished.', evidence: ['components/battle-preparation.tsx', 'components/harass-withdraw.tsx', 'components/game-table.tsx'] }, + { area: 'Implementation', status: 'Partial', detail: 'Physical slot commitment, category inspection, revealed typed/sector return selection, exact committed losses, opponent-Traitor cancellation, mandatory disposal and saved continuation are connected. Richese and optional-module combinations remain gated.', evidence: ['game/harass-withdraw.ts', 'game/battle-card-slots.ts', 'game/battle-resolution-quote.ts', 'game/engine.ts'] }, + { area: 'Player controls', status: 'Partial', detail: 'Either slot, compatible pair selection, category-null commitment and card inspection are usable. Multiple legal typed or sector returns have an owner choice after plans reveal and before traitor declarations; unique returns are automatic.', evidence: ['components/battle-preparation.tsx', 'components/harass-withdraw.tsx', 'components/game-table.tsx'] }, { area: 'AI', status: 'Partial', detail: 'All four profiles have a legal shared-quote path and preserve inspection secrecy. Retreat strategy and combined-game strength remain uncalibrated.', evidence: ['game/bots.ts', 'tests/ecaz-battle-bots.test.ts'] }, { area: 'Documentation', status: 'Implemented', detail: 'The card guide distinguishes printed effects, explicit inference and unfinished physical allocation/Stone Burner combinations.', evidence: ['docs/HARASS_WITHDRAW_RUNTIME.md', 'docs/ECAZ_TREACHERY_RULES.md'] }, - { area: 'Verification', status: 'Partial', detail: 'Focused rules, controls, AI and authenticated recovery checks cover the prototype; final sample and browser evidence remains bounded, with full combination acceptance open.', evidence: ['tests/harass-withdraw.test.ts', 'tests/ecaz-battle-controls.test.tsx', 'tests/ecaz-battle-bots.test.ts', 'tests/ecaz-battle-recovery.test.ts'] }, + { area: 'Verification', status: 'Partial', detail: 'Focused rules, controls, AI and authenticated recovery checks cover the prototype; final sample and browser evidence remains bounded, with full combination acceptance open.', evidence: ['tests/harass-allocation-engine.test.ts', 'tests/harass-allocation-recovery.test.ts', 'tests/harass-withdraw-choice-controls.test.tsx', 'tests/harass-withdraw.test.ts', 'tests/ecaz-battle-controls.test.tsx', 'tests/ecaz-battle-bots.test.ts', 'tests/ecaz-battle-recovery.test.ts'] }, ], }, { diff --git a/game/richese-cancellation.ts b/game/richese-cancellation.ts index b10d229e..e9f01f8c 100644 --- a/game/richese-cancellation.ts +++ b/game/richese-cancellation.ts @@ -12,6 +12,7 @@ const DECISIONS = { sukRescue: true, rihani: true, diplomatDefense: true, + harassWithdraw: true, choamAudit: true, choamAuditPayment: true, strongholdCopy: true, diff --git a/tests/harass-allocation-engine.test.ts b/tests/harass-allocation-engine.test.ts new file mode 100644 index 00000000..08fa259a --- /dev/null +++ b/tests/harass-allocation-engine.test.ts @@ -0,0 +1,282 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + applyAction, + normalizeAutomaticGame, + viewGame, + type Action, + type Game, +} from '../game/engine'; +import { botActions } from '../game/bots'; +import { defaultHarassWithdrawAllocation } from '../game/harass-withdraw'; +import { harassWithdrawGame, harassCustody } from './fixture-harass-withdraw'; + +function sealed(advanced = true, sector = false) { + let g = harassWithdrawGame( + advanced + ? { advanced, normal: 3, elite: 1 } + : { territory: 'imperial_basin', sector: 9 }, + ); + if (sector) + g.players[0].forces = { 'imperial_basin:9': 2, 'imperial_basin:10': 3 }; + g = applyAction(g, 'a', { + type: 'battlePlan', + dial: 2, + support: advanced ? 1 : 0, + leader: 'emperor-0', + defense: 'ecaz-harass-withdraw', + }); + return g; +} +function reveal(g: Game) { + return applyAction(g, 'd', { + type: 'battlePlan', + dial: 0, + support: 0, + leader: 'atreides-0', + }); +} +function selection(g: Game, returns: unknown): Action { + return { type: 'decision', event: g.battle!.harassAllocation!.event, returns }; +} +function reject(g: Game, id: string, action: Action, re: RegExp) { + const before = JSON.stringify(g); + assert.throws(() => applyAction(g, id, action), re); + assert.equal(JSON.stringify(g), before); +} +function finish(g: Game) { + g = applyAction(g, 'a', { type: 'traitorCall', call: false }); + return applyAction(g, 'd', { type: 'traitorCall', call: false }); +} + +void test('ambiguous Harass stays out of sealed plans and opens only after public reveal', () => { + const s = sealed(); + assert.equal(s.battle!.harassAllocation, undefined); + assert.equal(s.decision, null); + assert.equal(viewGame(s, 'd').battle!.plans.a, undefined); + assert.equal(viewGame(s, 'a').battle!.harassAllocation, null); + const g = reveal(s); + assert.equal(g.decision!.kind, 'harassWithdraw'); + assert.equal(g.battle!.revealed, true); + assert.equal(viewGame(g, 'd').battle!.harassAllocation, null); + assert.ok(viewGame(g, 'a').battle!.harassAllocation); + assert.deepEqual(g.battle!.plans.a, s.battle!.plans.a); + for (const p of g.players) + assert.deepEqual( + viewGame(JSON.parse(JSON.stringify(g)), p.id), + viewGame(g, p.id), + ); + reject( + g, + 'd', + { type: 'traitorCall', call: false }, + /decision|waiting|choose|resolve|not available/i, + ); +}); +void test('every legal Advanced typed choice preserves the selected elite custody through resolution', () => { + for (const returns of [ + { 'arrakeen:10': { normal: 0, elite: 1 } }, + { 'arrakeen:10': { normal: 2, elite: 0 } }, + { 'arrakeen:10': { normal: 3, elite: 0 } }, + ]) { + const g = reveal(sealed()); + const chosen = applyAction(g, 'a', selection(g, returns)); + assert.equal(chosen.decision, null); + assert.deepEqual(chosen.players[0].forces, g.players[0].forces); + assert.deepEqual( + viewGame(chosen, 'd').battle!.harassAllocation!.selection, + returns, + ); + const done = finish(chosen); + const total = returns['arrakeen:10'].normal + returns['arrakeen:10'].elite; + assert.equal(done.players[0].reserves, 16 + total); + assert.equal( + done.players[0].elites!.reserves, + 4 + returns['arrakeen:10'].elite, + ); + harassCustody(done); + assert.equal(done.players[0].tanks, 4 - total); + assert.deepEqual(done.players[0].forces, {}); + assert.equal( + done.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length, + 1, + ); + } +}); +void test('Basic multi-sector selection withdraws the chosen exact locations without forced early allocation', () => { + const g = reveal(sealed(false, true)); + const returns = { + 'imperial_basin:9': { normal: 1, elite: 0 }, + 'imperial_basin:10': { normal: 2, elite: 0 }, + }; + const chosen = applyAction(g, 'a', selection(g, returns)); + assert.deepEqual(chosen.battle!.harassAllocation!.selection, returns); + const done = finish(chosen); + assert.equal(done.players[0].reserves, 18); + assert.equal(done.players[0].tanks, 2); + harassCustody(done); +}); +void test('stale, other-owner, partial, overdrawn and forged choices reject without mutation', () => { + const g = reveal(sealed()); + const valid = { 'arrakeen:10': { normal: 2, elite: 0 } }; + reject( + g, + 'd', + selection(g, valid), + /decision|waiting|choose|resolve|not available/i, + ); + reject(g, 'a', { ...selection(g, valid), event: 'stale' }, /exact revealed/); + for (const returns of [ + null, + {}, + { 'arrakeen:10': { normal: 1, elite: 0 } }, + { 'arrakeen:10': { normal: 5, elite: 0 } }, + { 'carthag:11': { normal: 2, elite: 0 } }, + ]) + reject( + g, + 'a', + selection(g, returns), + /selection|return|location|undialed|physical|force/i, + ); + const done = applyAction(g, 'a', selection(g, valid)); + reject( + done, + 'a', + selection(g, valid), + /decision|waiting|choose|resolve|not available/i, + ); +}); +void test('corrupt saved pending/selected allocations reject reads, normalization and actions', () => { + const pending = reveal(sealed()); + const chosen = applyAction( + pending, + 'a', + selection(pending, { 'arrakeen:10': { normal: 2, elite: 0 } }), + ); + for (const [base, edit] of [ + [ + pending, + (g: Game) => { + delete g.battle!.harassAllocation; + }, + ], + [ + pending, + (g: Game) => { + g.decision = null; + }, + ], + [ + pending, + (g: Game) => { + g.battle!.plans.a.support = 0; + }, + ], + [ + pending, + (g: Game) => { + g.battle!.harassAllocation!.player = 'd'; + }, + ], + [ + chosen, + (g: Game) => { + g.battle!.harassAllocation!.selection = {}; + }, + ], + [ + chosen, + (g: Game) => { + delete g.battle!.harassAllocationEvent; + }, + ], + ] as const) { + const g = structuredClone(base); + edit(g); + const before = JSON.stringify(g); + for (const p of g.players) + assert.throws( + () => viewGame(g, p.id), + /withdraw|Harass|returned counters/i, + ); + assert.throws( + () => normalizeAutomaticGame(g), + /withdraw|Harass|returned counters/i, + ); + assert.throws( + () => applyAction(g, 'a', { type: 'setAutopilot', difficulty: 'Easy' }), + /withdraw|Harass|returned counters/i, + ); + assert.equal(JSON.stringify(g), before); + } +}); +void test('four AI profiles select real after-reveal allocations using only the owner projection', () => { + const g = reveal(sealed()); + for (const difficulty of ['Easy', 'Medium', 'Hard', 'Brutal'] as const) { + const v = viewGame(g, 'a'); + v.players[0].bot = difficulty; + const before = JSON.stringify(v), + action = botActions(v)[0]; + assert.equal(action?.type, 'decision'); + const done = applyAction(g, 'a', action); + assert.equal(done.decision, null); + assert.equal(JSON.stringify(v), before); + const offer = v.battle!.harassAllocation!; + assert.deepEqual( + action.returns, + defaultHarassWithdrawAllocation(offer.context, offer.dial, offer.support), + ); + } +}); + +void test('opposing traitor cancellation ignores the selected return and loses every original board counter', () => { + let g = sealed(); + const traitor = g.battle!.plans.a.leader!, + old = g.players[1].traitors[0]; + let replaced = false; + for (const p of g.players) { + const at = p.traitors.indexOf(traitor); + if (at >= 0) { + p.traitors[at] = old; + replaced = true; + } + const dancer = p.faceDancers?.find((c) => c.leader === traitor); + if (dancer) { + dancer.leader = old; + replaced = true; + } + } + const at = g.traitorReserve!.indexOf(traitor); + if (at >= 0) { + g.traitorReserve![at] = old; + replaced = true; + } + assert.ok(replaced); + g.players[1].traitors[0] = traitor; + harassCustody(g); + g = reveal(g); + g = applyAction( + g, + 'a', + selection(g, { 'arrakeen:10': { normal: 2, elite: 0 } }), + ); + g = applyAction(g, 'a', { type: 'traitorCall', call: false }); + g = applyAction(g, 'd', { type: 'traitorCall', call: true }); + assert.equal(g.players[0].reserves, 16); + assert.equal(g.players[0].tanks, 4); + assert.equal(g.players[0].elites!.reserves, 4); + assert.equal(g.players[0].elites!.tanks, 1); + harassCustody(g); + assert.equal( + g.discard.filter((card) => card.id === 'ecaz-harass-withdraw').length, + 1, + ); + assert.notEqual(g.decision?.kind, 'battleLosses'); + assert.equal(g.players[1].tanks, 0); + assert.equal( + g.log.filter((e) => e.text.includes('used Harass & Withdraw to return')) + .length, + 0, + ); +}); diff --git a/tests/harass-allocation-recovery.test.ts b/tests/harass-allocation-recovery.test.ts new file mode 100644 index 00000000..a22268b9 --- /dev/null +++ b/tests/harass-allocation-recovery.test.ts @@ -0,0 +1,194 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import type { DatabaseSync } from 'node:sqlite'; +import { applyAction, viewGame, type Game } from '../game/engine'; +import { unitStore } from './fixture-nexus-room-store'; +import { harassWithdrawGame, harassCustody } from './fixture-harass-withdraw'; +const clock = { now: () => 84000, sleep: async () => {} }; +const rows = (sqlite: DatabaseSync) => + sqlite.prepare('SELECT * FROM rooms').all(); +async function fixture(t: test.TestContext) { + const f = unitStore(); + t.after(() => f.sqlite.close()); + const made = await f.rooms.createRoom('Harass allocation', 'emperor', true, [ + 'ix', + ]); + const code = made.view.code; + const tokens = [ + made.token, + (await f.rooms.joinRoom(code, 'Atreides', 'atreides')).token!, + (await f.rooms.joinRoom(code, 'Tleilaxu', 'tleilaxu')).token!, + ]; + const auths = await Promise.all( + tokens.map((token) => f.rooms.authenticate(code, token)), + ); + const ids = auths.map((a) => a.playerId) as [string, string, string]; + let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1, ids }); + g.code = code; + g.version = (await f.rooms.readRoom(code)).version; + g = applyAction(g, ids[0], { + type: 'battlePlan', + dial: 2, + support: 1, + leader: 'emperor-0', + defense: 'ecaz-harass-withdraw', + }); + g = applyAction(g, ids[1], { + type: 'battlePlan', + dial: 0, + leader: 'atreides-0', + }); + harassCustody(g); + f.sqlite + .prepare('UPDATE rooms SET state=?, version=? WHERE code=?') + .run(JSON.stringify(g), g.version, code); + return { ...f, code, tokens, ids, auths, game: g }; +} +void test('revealed allocation survives seat restoration; concurrent legal choices select once, with exact winner losses', async (t) => { + const f = await fixture(t), + beforeRows = rows(f.sqlite); + for (const [index, token] of f.tokens.entries()) { + const r = f.restart(), + auth = await r.authenticate(f.code, token); + assert.deepEqual( + await r.readSeatView(f.code, auth), + viewGame(f.game, f.ids[index]), + ); + } + assert.deepEqual(rows(f.sqlite), beforeRows); + const rooms = f.restart(), + auth = await rooms.authenticate(f.code, f.tokens[0]); + let entered = 0, + release!: () => void; + const both = new Promise((resolve) => { + release = resolve; + }); + f.hooks.beforeWrite = async () => { + if (++entered === 2) release(); + await both; + }; + const choices = [ + { 'arrakeen:10': { normal: 0, elite: 1 } }, + { 'arrakeen:10': { normal: 2, elite: 0 } }, + ]; + const outcomes = await Promise.allSettled( + choices.map((returns) => + rooms.act( + f.code, + auth, + f.game.version, + { type: 'decision', event: f.game.battle!.harassAllocation!.event, returns }, + clock, + ), + ), + ); + f.hooks.beforeWrite = undefined; + assert.equal(outcomes.filter((r) => r.status === 'fulfilled').length, 1); + let g = await f.restart().readRoom(f.code); + assert.equal(g.version, f.game.version + 1); + const selected = g.battle!.harassAllocation!.selection!['arrakeen:10']; + assert.equal(g.players[0].reserves, 16); + assert.equal(g.decision, null); + for (const [index, token] of f.tokens.entries()) { + const r = f.restart(), + a = await r.authenticate(f.code, token); + assert.deepEqual( + (await r.readSeatView(f.code, a)).battle!.harassAllocation!.selection, + g.battle!.harassAllocation!.selection, + ); + assert.deepEqual( + await r.readSeatView(f.code, a), + viewGame(g, f.ids[index]), + ); + } + const staleRows = rows(f.sqlite); + await assert.rejects(() => + f + .restart() + .act( + f.code, + auth, + f.game.version, + { + type: 'decision', + event: f.game.battle!.harassAllocation!.event, + returns: choices[0], + }, + clock, + ), + ); + assert.deepEqual(rows(f.sqlite), staleRows); + for (const index of [0, 1]) { + const r = f.restart(), + a = await r.authenticate(f.code, f.tokens[index]); + await r.act( + f.code, + a, + g.version, + { type: 'traitorCall', call: false }, + clock, + ); + g = await r.readRoom(f.code); + } + assert.equal(g.battle, null); + assert.equal(g.players[0].reserves, 16 + selected.normal + selected.elite); + assert.equal(g.players[0].tanks, 4 - selected.normal - selected.elite); + assert.deepEqual(g.players[0].forces, {}); + assert.equal(g.players[0].elites!.reserves, 4 + selected.elite); + harassCustody(g); + assert.equal( + g.log.filter( + (e) => + e.text.includes('selected') && + e.text.includes('undialed forces for Harass'), + ).length, + 1, + ); + assert.equal( + g.log.filter((e) => e.text.includes('used Harass & Withdraw to return')) + .length, + 1, + ); +}); +void test('lost or edited saved physical choice cannot normalize or write through authenticated room recovery', async (t) => { + const f = await fixture(t); + for (const edit of [ + (g: Game) => { + g.decision = null; + }, + (g: Game) => { + delete g.battle!.harassAllocationEvent; + }, + (g: Game) => { + g.battle!.harassAllocation!.frame += 'changed'; + }, + ]) { + const bad = structuredClone(f.game); + edit(bad); + f.sqlite + .prepare('UPDATE rooms SET state=? WHERE code=?') + .run(JSON.stringify(bad), f.code); + const before = rows(f.sqlite); + const r = f.restart(); + await assert.rejects( + () => r.readSeatView(f.code, f.auths[0]), + /withdraw|Harass/i, + ); + await assert.rejects( + () => + r.act( + f.code, + f.auths[0], + bad.version, + { + type: 'decision', + event: f.game.battle!.harassAllocation!.event, + returns: { 'arrakeen:10': { normal: 2, elite: 0 } }, + }, + clock, + ), + /withdraw|Harass/i, + ); + assert.deepEqual(rows(f.sqlite), before); + } +}); diff --git a/tests/harass-withdraw-allocation.test.ts b/tests/harass-withdraw-allocation.test.ts new file mode 100644 index 00000000..e2e3228e --- /dev/null +++ b/tests/harass-withdraw-allocation.test.ts @@ -0,0 +1,330 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { casualtyOptions } from '../game/combat'; +import { + defaultHarassWithdrawAllocation, + harassWithdrawCommitments, + harassWithdrawNeedsAllocation, + quoteHarassWithdraw, + HarassWithdrawError, + type HarassWithdrawContext, + type HarassWithdrawSelection, +} from '../game/harass-withdraw'; + +const mixed = (): HarassWithdrawContext => ({ + blocked: null, + forces: { normal: 3, elite: 2, eliteStrength: 1, freeSupport: true }, + locations: { + 'imperial_basin:9': { normal: 2, elite: 1 }, + 'imperial_basin:10': { normal: 1, elite: 1 }, + }, +}); +const ordinary = (): HarassWithdrawContext => ({ + blocked: null, + forces: { normal: 5, elite: 0, eliteStrength: 1, freeSupport: false }, + locations: { + 'imperial_basin:9': { normal: 2, elite: 0 }, + 'imperial_basin:10': { normal: 3, elite: 0 }, + }, +}); +function reject( + context: HarassWithdrawContext, + dial: number, + support: number, + selection: unknown, +) { + const before = structuredClone({ context, selection }); + assert.throws( + () => + quoteHarassWithdraw( + context, + dial, + support, + selection as HarassWithdrawSelection, + ), + HarassWithdrawError, + ); + assert.deepEqual({ context, selection }, before); +} + +void test('mixed regular/elite commitments are physical choices; explicit returns select one without mutating custody', () => { + const context = mixed(); + const before = structuredClone(context); + assert.deepEqual(harassWithdrawCommitments(context, 2, 0), [ + { normal: 2, elite: 0 }, + { normal: 1, elite: 1 }, + { normal: 0, elite: 2 }, + ]); + assert.equal(harassWithdrawNeedsAllocation(context, 2, 0), true); + assert.throws( + () => quoteHarassWithdraw(context, 2, 0), + /ambiguous regular\/elite/, + ); + const selection = { + 'imperial_basin:9': { normal: 1, elite: 1 }, + 'imperial_basin:10': { normal: 1, elite: 0 }, + }; + const quote = quoteHarassWithdraw(context, 2, 0, selection); + assert.deepEqual(quote.returned, { normal: 2, elite: 1 }); + assert.deepEqual(quote.remaining, { ...context.forces, normal: 1, elite: 1 }); + assert.deepEqual(quote.locations, selection); + assert.notEqual(quote.locations, selection); + assert.notEqual( + quote.locations['imperial_basin:9'], + selection['imperial_basin:9'], + ); + assert.deepEqual(context, before); +}); + +void test('multiple sectors may explicitly divide a uniquely typed return while legacy callers retain the sector guard', () => { + const context = ordinary(); + assert.deepEqual(harassWithdrawCommitments(context, 2, 2), [ + { normal: 2, elite: 0 }, + ]); + assert.equal(harassWithdrawNeedsAllocation(context, 2, 2), true); + assert.throws( + () => quoteHarassWithdraw(context, 2, 2), + /ambiguous allocation among sectors/, + ); + for (const [a, b] of [ + [0, 3], + [1, 2], + [2, 1], + ]) { + const quote = quoteHarassWithdraw(context, 2, 2, { + 'imperial_basin:9': { normal: a, elite: 0 }, + 'imperial_basin:10': { normal: b, elite: 0 }, + }); + assert.deepEqual(quote.returned, { normal: 3, elite: 0 }); + assert.deepEqual(quote.remaining, { ...context.forces, normal: 2 }); + assert.ok( + Object.values(quote.locations).every( + (group) => group.normal + group.elite > 0, + ), + ); + } +}); + +void test('Advanced paid/unpaid and Ixian half-strength commitments retain exact regular/elite complements', () => { + for (const forces of [ + { normal: 3, elite: 2, eliteStrength: 2 as const, freeSupport: false }, + { + normal: 3, + elite: 2, + eliteStrength: 2 as const, + freeSupport: false, + normalFixedHalf: true, + }, + { + normal: 3, + elite: 2, + eliteStrength: 1 as const, + freeSupport: false, + eliteFreeSupport: true, + }, + ]) { + const context: HarassWithdrawContext = { ...mixed(), forces }; + for (const [dial, support] of [ + [0.5, 0], + [2, 0], + [2, 1], + [3, 2], + ]) { + const choices = casualtyOptions(forces, dial, support); + if (!choices.length) continue; + const physical = harassWithdrawCommitments(context, dial, support); + assert.equal( + new Set(physical.map((choice) => JSON.stringify(choice))).size, + physical.length, + ); + assert.ok( + physical.every( + (choice) => Object.keys(choice).sort().join(',') === 'elite,normal', + ), + ); + for (const choice of physical) { + let normal = forces.normal - choice.normal, + elite = forces.elite - choice.elite; + const selection = Object.fromEntries( + Object.entries(context.locations).map(([key, group]) => { + const selected = { + normal: Math.min(normal, group.normal), + elite: Math.min(elite, group.elite), + }; + normal -= selected.normal; + elite -= selected.elite; + return [key, selected]; + }), + ); + const quote = quoteHarassWithdraw(context, dial, support, selection); + assert.deepEqual( + { normal: quote.remaining.normal, elite: quote.remaining.elite }, + choice, + ); + } + } + } +}); + +void test('default physical returns are deterministic across location insertion order and are always legal', () => { + const context = mixed(), + before = structuredClone(context); + const reversed = { + ...context, + locations: Object.fromEntries(Object.entries(context.locations).reverse()), + }; + for (const dial of [0, 1, 2, 5]) { + const allocation = defaultHarassWithdrawAllocation(context, dial, 0); + assert.deepEqual( + allocation, + defaultHarassWithdrawAllocation(reversed, dial, 0), + ); + const quote = quoteHarassWithdraw(context, dial, 0, allocation); + assert.deepEqual(quote.locations, allocation); + assert.deepEqual( + { normal: quote.remaining.normal, elite: quote.remaining.elite }, + harassWithdrawCommitments(context, dial, 0)[0], + ); + } + assert.deepEqual(context, before); +}); + +void test('a chosen physical commitment gets a shared legal default, while invented or malformed commitments reject', () => { + const context = mixed(), + before = structuredClone(context); + for (const commitment of harassWithdrawCommitments(context, 2, 0)) { + const selection = defaultHarassWithdrawAllocation( + context, + 2, + 0, + commitment, + ); + const quote = quoteHarassWithdraw(context, 2, 0, selection); + assert.deepEqual( + { normal: quote.remaining.normal, elite: quote.remaining.elite }, + commitment, + ); + } + for (const commitment of [ + { normal: 3, elite: 0 }, + { normal: 1, elite: 0 }, + { normal: 1, elite: 1, paidNormal: 0 }, + { normal: -1, elite: 3 }, + null, + ]) + assert.throws( + () => defaultHarassWithdrawAllocation(context, 2, 0, commitment as never), + HarassWithdrawError, + ); + assert.deepEqual(context, before); +}); + +void test('explicit empty returns require a full physical commitment, while zero dial returns every physical counter', () => { + const context = ordinary(); + assert.deepEqual(quoteHarassWithdraw(context, 5, 5, {}).returned, { + normal: 0, + elite: 0, + }); + assert.equal(harassWithdrawNeedsAllocation(context, 5, 5), false); + assert.deepEqual( + quoteHarassWithdraw(context, 5, 5), + quoteHarassWithdraw(context, 5, 5, {}), + ); + reject(context, 2, 2, {}); + assert.equal(harassWithdrawNeedsAllocation(context, 0, 0), false); + assert.deepEqual( + quoteHarassWithdraw(context, 0, 0).locations, + context.locations, + ); + assert.deepEqual( + quoteHarassWithdraw(context, 0, 0, context.locations).remaining, + { ...context.forces, normal: 0, elite: 0 }, + ); +}); + +void test('return selection rejects malformed groups, unknown locations, overdraw and a wrong typed complement immutably', () => { + const context = mixed(); + for (const selection of [ + null, + [], + 2, + 'all', + { 'unknown:0': { normal: 3, elite: 0 } }, + { 'imperial_basin:9': { normal: 3, elite: 0 } }, + { 'imperial_basin:9': { normal: 0, elite: 2 } }, + { 'imperial_basin:9': { normal: 1 } }, + { 'imperial_basin:9': { normal: 1, elite: 1, paidNormal: 1 } }, + { 'imperial_basin:9': { normal: -1, elite: 0 } }, + { 'imperial_basin:9': { normal: 0.5, elite: 0 } }, + { 'imperial_basin:9': { normal: NaN, elite: 0 } }, + { 'imperial_basin:9': { normal: Number.MAX_SAFE_INTEGER + 1, elite: 0 } }, + { 'imperial_basin:9': { normal: '2', elite: 1 } }, + { 'imperial_basin:9': { normal: 1, elite: 0 } }, + ]) + reject(context, 2, 0, selection); + const advanced = { + ...context, + forces: { ...context.forces, eliteStrength: 2 as const }, + }; + // Leaves two regular counters: strength two, not the revealed strength four. + reject(advanced, 4, 0, { + 'imperial_basin:9': { normal: 1, elite: 1 }, + 'imperial_basin:10': { normal: 0, elite: 1 }, + }); +}); + +void test('all allocation helpers validate context and dial before reporting an ambiguous or default choice', () => { + for (const context of [ + { ...mixed(), blocked: 'A combined rule remains guarded.' }, + { ...mixed(), locations: null }, + { ...mixed(), locations: [] }, + { ...mixed(), locations: { 'imperial_basin:9': { normal: 3, elite: 1 } } }, + { + ...mixed(), + locations: { 'imperial_basin:9': { normal: 3, elite: 2, other: 0 } }, + }, + { ...mixed(), forces: { ...mixed().forces, elite: 0, temporaryElite: 1 } }, + ] as unknown as HarassWithdrawContext[]) { + const before = structuredClone(context); + for (const helper of [ + harassWithdrawCommitments, + harassWithdrawNeedsAllocation, + defaultHarassWithdrawAllocation, + ]) + assert.throws(() => helper(context, 2, 0), HarassWithdrawError); + assert.deepEqual(context, before); + } + for (const [dial, support] of [ + [NaN, 0], + [1.25, 0], + [-1, 0], + [2, 0.5], + [2, 6], + ]) + for (const helper of [ + harassWithdrawCommitments, + harassWithdrawNeedsAllocation, + defaultHarassWithdrawAllocation, + ]) + assert.throws( + () => helper(ordinary(), dial, support), + HarassWithdrawError, + ); +}); + +void test('legacy omitted returns retain insertion order and unique allocation JSON shape', () => { + const context: HarassWithdrawContext = { + blocked: null, + forces: { normal: 3, elite: 2, eliteStrength: 2, freeSupport: true }, + locations: { + 'imperial_basin:9': { normal: 0, elite: 2 }, + 'imperial_basin:11': { normal: 3, elite: 0 }, + }, + }; + const quote = quoteHarassWithdraw(context, 0, 0); + assert.equal( + JSON.stringify(quote.locations), + '{"imperial_basin:11":{"normal":3,"elite":0},"imperial_basin:9":{"normal":0,"elite":2}}', + ); + assert.equal(harassWithdrawNeedsAllocation(context, 0, 0), false); +}); diff --git a/tests/harass-withdraw-choice-controls.test.tsx b/tests/harass-withdraw-choice-controls.test.tsx new file mode 100644 index 00000000..8c52d017 --- /dev/null +++ b/tests/harass-withdraw-choice-controls.test.tsx @@ -0,0 +1,182 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { + HarassWithdrawChoice, + harassWithdrawChoiceState, +} from '../components/harass-withdraw-choice'; +import { + HarassWithdrawGuide, + harassWithdrawControlState, +} from '../components/harass-withdraw'; +import { botActions } from '../game/bots'; +import { DIFFICULTIES } from '../game/bot-profiles'; +import { applyAction, viewGame, type Game } from '../game/engine'; +import { + defaultHarassWithdrawAllocation, + harassWithdrawCommitments, +} from '../game/harass-withdraw'; +import { harassWithdrawGame } from './fixture-harass-withdraw'; + +function submitPlans(game: Game) { + const owner = game.players[0]; + const opponent = game.players[1]; + let next = applyAction(game, owner.id, { + type: 'battlePlan', + dial: game.advanced ? 2 : 2, + support: game.advanced ? 1 : 0, + leader: owner.leaders.find((leader) => !leader.dead)!.id, + weapon: 'ecaz-harass-withdraw', + }); + next = applyAction(next, opponent.id, { + type: 'battlePlan', + dial: 0, + support: 0, + leader: opponent.leaders.find((leader) => !leader.dead)!.id, + }); + assert.equal(next.decision?.kind, 'harassWithdraw'); + return next; +} + +function multiSectorGame() { + const game = harassWithdrawGame({ + territory: 'imperial_basin', + sector: 9, + }); + game.players[0].forces = { + 'imperial_basin:9': 2, + 'imperial_basin:10': 3, + }; + return game; +} + +void test('pre-seal guidance permits a supported ambiguous plan and defers its private allocation', () => { + const game = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 }); + const preview = viewGame(game, 'a').battle!.harassWithdraw!; + const state = harassWithdrawControlState(preview, true, 2, 1); + assert.deepEqual(state, { blocked: null, returned: null }); + const html = renderToStaticMarkup( + createElement(HarassWithdrawGuide, { preview, state }), + ); + assert.match(html, /After plans are revealed/); + assert.match(html, /choose exactly which undialed ordinary and elite forces/); + assert.doesNotMatch(html, /ambiguous regular\/elite/); + for (const difficulty of DIFFICULTIES) { + const botView = viewGame(game, 'a'); + botView.players.find((player) => player.id === 'a')!.bot = difficulty; + const candidates = botActions(botView).filter( + (action) => + action.type === 'battlePlan' && + (action.weapon === 'ecaz-harass-withdraw' || + action.defense === 'ecaz-harass-withdraw'), + ); + assert.ok(candidates.length, `${difficulty} omitted legal Harass plans`); + assert.ok( + candidates.every((action) => !Object.hasOwn(action, 'returns')), + `${difficulty} exposed an early return selection`, + ); + } +}); + +void test('the revealed owner gets exact commitment and per-sector controls while rivals get no allocation', () => { + const revealed = submitPlans(multiSectorGame()); + const ownerView = viewGame(revealed, 'a'); + const observerView = viewGame(revealed, 't'); + assert.equal(observerView.battle!.harassAllocation, null); + const offer = ownerView.battle!.harassAllocation!; + assert.equal(offer.selection, null); + const commitments = harassWithdrawCommitments( + offer.context, + offer.dial, + offer.support, + ); + assert.deepEqual(commitments, [{ normal: 2, elite: 0 }]); + + const first = defaultHarassWithdrawAllocation( + offer.context, + offer.dial, + offer.support, + commitments[0], + ); + assert.deepEqual(first, { + 'imperial_basin:10': { normal: 3, elite: 0 }, + }); + assert.equal( + harassWithdrawChoiceState(offer.context, offer.dial, offer.support, first) + .blocked, + null, + ); + assert.match( + harassWithdrawChoiceState(offer.context, offer.dial, offer.support, { + 'imperial_basin:9': { normal: 2, elite: 0 }, + }).blocked!, + /exact undialed complement/, + ); + + const html = renderToStaticMarkup( + createElement(HarassWithdrawChoice, { + game: ownerView, + act() {}, + busy: false, + }), + ); + assert.match(html, /aria-label="Harass and Withdraw force allocation"/); + assert.match(html, /Dialed physical commitment/); + assert.match(html, /2 ordinary · 0 elite/); + assert.match(html, /Imperial Basin · sector 9/); + assert.match(html, /Imperial Basin · sector 10/); + assert.match(html, /Confirm returned forces/); + assert.equal( + renderToStaticMarkup( + createElement(HarassWithdrawChoice, { + game: observerView, + act() {}, + busy: false, + }), + ), + '', + ); + assert.match( + renderToStaticMarkup( + createElement(HarassWithdrawChoice, { + game: ownerView, + act() {}, + busy: true, + }), + ), + /disabled=""/, + ); +}); + +void test('every bot profile submits the shared deterministic allocation only at its revealed decision', () => { + for (const difficulty of DIFFICULTIES) { + const revealed = submitPlans( + harassWithdrawGame({ advanced: true, normal: 3, elite: 1 }), + ); + const view = viewGame(revealed, 'a'); + view.players.find((player) => player.id === 'a')!.bot = difficulty; + const offer = view.battle!.harassAllocation!; + const expected = defaultHarassWithdrawAllocation( + offer.context, + offer.dial, + offer.support, + ); + const action = botActions(view)[0]; + assert.deepEqual(action, { + type: 'decision', + event: + revealed.decision?.kind === 'harassWithdraw' + ? revealed.decision.event + : '', + returns: expected, + }); + const selected = applyAction(revealed, 'a', action); + assert.deepEqual(selected.battle!.harassAllocation!.selection, expected); + assert.notEqual(selected.decision?.kind, 'harassWithdraw'); + assert.deepEqual( + viewGame(selected, 't').battle!.harassAllocation!.selection, + expected, + ); + } +}); diff --git a/tests/harass-withdraw.test.ts b/tests/harass-withdraw.test.ts index a49ee749..2ed6d45c 100644 --- a/tests/harass-withdraw.test.ts +++ b/tests/harass-withdraw.test.ts @@ -445,8 +445,9 @@ void test('co-present reciprocal Ecaz allies are publicly guarded before sealing } }); -void test('ambiguous unit mixes and sector allocations reject before sealing without hidden opponent dependence', () => { +void test('legacy ambiguous unit mixes and sector allocations reject before sealing without hidden opponent dependence', () => { let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 }); + delete g.battle!.harassAllocationVersion; reject( g, 'a', @@ -454,6 +455,7 @@ void test('ambiguous unit mixes and sector allocations reject before sealing wit /ambiguous regular\/elite/, ); g = harassWithdrawGame({ territory: 'imperial_basin', sector: 9 }); + delete g.battle!.harassAllocationVersion; g.players[0].forces = { 'imperial_basin:9': 2, 'imperial_basin:10': 3 }; const preview = viewGame(g, 'a').battle!.harassWithdraw!; assert.throws( @@ -686,6 +688,7 @@ void test('Reinforcements and public Richese/optional-module contexts remain gua void test('malformed sealed withdrawal allocations reject private reads and both ordinary/autopilot actions', () => { let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 }); + delete g.battle!.harassAllocationVersion; g = applyAction(g, 'a', ownPlan(g, { dial: 0, support: 0 })); g.battle!.plans.a.dial = 2; g.battle!.plans.a.support = 1;