poker-flopsolve 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +442 -2
- package/dist/browser.js +2857 -0
- package/dist/browser.js.map +1 -0
- package/dist/index.d.ts +1050 -0
- package/dist/index.js +2869 -0
- package/dist/index.js.map +1 -0
- package/dist/worker.d.ts +2 -0
- package/dist/worker.js +2233 -0
- package/dist/worker.js.map +1 -0
- package/package.json +62 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cards.ts","../src/tree.ts","../src/abstraction.ts","../src/runouts.ts","../src/range.ts","../src/eval7.ts","../src/showdown.ts","../src/pairs.ts","../src/wasm/kernels.ts","../src/kernels.ts","../src/cfr.ts","../src/warm.ts","../src/platform/browser.ts","../src/parallel.ts","../src/index.ts"],"sourcesContent":["/**\n * Card encoding for a standard 52-card deck.\n *\n * Purpose: the one place a card's integer form is decided.\n *\n * A card is `rank * 4 + suit`, with rank 0 = deuce and 12 = ace, and suit\n * ordered `s h d c`. Rank-major means all four cards of a rank are adjacent.\n *\n * The evaluator wants a different shape — four 13-bit rank masks, one per suit\n * — so {@link suitLanes} converts. Keeping the two representations separate is\n * deliberate: the integer index is what ranges, blockers and array offsets use,\n * and the lanes exist only for the duration of an evaluation.\n */\n\n/** Ranks, lowest first, so the character index equals the rank. */\nconst RANK_CHARS = '23456789TJQKA';\n\n/** Suits in index order. */\nconst SUIT_CHARS = 'shdc';\n\nexport const RANKS = 13;\nexport const SUITS = 4;\nexport const DECK = 52;\n\n/** Distinct two-card combinations, `C(52, 2)`. */\nexport const COMBOS = 1326;\n\n/** Rank of a card, 0 = deuce, 12 = ace. */\nexport function rankOf(card: number): number {\n\treturn card >> 2;\n}\n\n/** Suit of a card, 0..3 in `s h d c` order. */\nexport function suitOf(card: number): number {\n\treturn card & 3;\n}\n\n/** Card index from rank and suit. */\nexport function cardOf(rank: number, suit: number): number {\n\treturn (rank << 2) | suit;\n}\n\n/**\n * Name a card, e.g. \"As\".\n * @param card card index\n */\nexport function formatCard(card: number): string {\n\treturn RANK_CHARS[rankOf(card)] + SUIT_CHARS[suitOf(card)];\n}\n\n/** Name a list of cards, space separated. */\nexport function formatCards(cards: Iterable<number>): string {\n\treturn [...cards].map(formatCard).join(' ');\n}\n\n/**\n * Parse a card name such as \"As\" or \"th\".\n * @param name two characters, rank then suit\n * @throws if the name is not a card\n */\nexport function parseCard(name: string): number {\n\tif (name.length !== 2) throw new Error(`Invalid card \"${name}\": expected two characters`);\n\tconst rank = RANK_CHARS.indexOf(name[0].toUpperCase());\n\tconst suit = SUIT_CHARS.indexOf(name[1].toLowerCase());\n\tif (rank < 0) throw new Error(`Invalid rank \"${name[0]}\" in card \"${name}\"`);\n\tif (suit < 0) throw new Error(`Invalid suit \"${name[1]}\" in card \"${name}\"`);\n\treturn cardOf(rank, suit);\n}\n\n/**\n * Parse a board or hand written as \"AsKh7d\", \"As Kh 7d\" or \"as kh 7d\".\n * @param text card names, optionally separated by spaces or commas\n * @throws if any card is malformed or repeated\n */\nexport function parseCards(text: string): number[] {\n\tconst compact = text.replace(/[\\s,]+/g, '');\n\tif (compact.length % 2 !== 0) throw new Error(`\"${text}\" is not a whole number of cards`);\n\n\tconst cards: number[] = [];\n\tconst seen = new Set<number>();\n\tfor (let i = 0; i < compact.length; i += 2) {\n\t\tconst card = parseCard(compact.slice(i, i + 2));\n\t\tif (seen.has(card)) throw new Error(`\"${formatCard(card)}\" appears twice in \"${text}\"`);\n\t\tseen.add(card);\n\t\tcards.push(card);\n\t}\n\treturn cards;\n}\n\n/**\n * Pack cards into the four 13-bit rank masks the evaluator takes.\n *\n * @param cards card indices\n * @param lanes destination of length 4; zeroed by this call\n */\nexport function suitLanes(cards: Iterable<number>, lanes: Int32Array): void {\n\tlanes[0] = 0;\n\tlanes[1] = 0;\n\tlanes[2] = 0;\n\tlanes[3] = 0;\n\tfor (const card of cards) lanes[card & 3] |= 1 << (card >> 2);\n}\n\n/**\n * Index of a two-card combination, in the same colex order the solver uses.\n *\n * For `a < b` this is `a + b(b-1)/2`, a dense bijection onto `0..1325`.\n *\n * @param a one card\n * @param b the other card\n */\nexport function comboIndex(a: number, b: number): number {\n\tconst lo = a < b ? a : b;\n\tconst hi = a < b ? b : a;\n\treturn lo + ((hi * (hi - 1)) >> 1);\n}\n\n/** The two cards of every combination, flat, `COMBOS * 2` entries ascending. */\nexport const COMBO_CARDS: Uint8Array = (() => {\n\tconst cards = new Uint8Array(COMBOS * 2);\n\tlet index = 0;\n\tfor (let b = 1; b < DECK; b++) {\n\t\tfor (let a = 0; a < b; a++, index++) {\n\t\t\tcards[index * 2] = a;\n\t\t\tcards[index * 2 + 1] = b;\n\t\t}\n\t}\n\treturn cards;\n})();\n\n/**\n * Per-suit rank masks for every combination, four entries each.\n *\n * The evaluator takes four masks, so combining a hand with a board is four ORs.\n * Precomputing the hand half once removes it from the inner loop entirely.\n */\nexport const COMBO_LANES: Int32Array = (() => {\n\tconst lanes = new Int32Array(COMBOS * 4);\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tconst a = COMBO_CARDS[combo * 2];\n\t\tconst b = COMBO_CARDS[combo * 2 + 1];\n\t\tlanes[combo * 4 + (a & 3)] |= 1 << (a >> 2);\n\t\tlanes[combo * 4 + (b & 3)] |= 1 << (b >> 2);\n\t}\n\treturn lanes;\n})();\n\n/** Name a combination, e.g. \"AsKh\". */\nexport function formatCombo(combo: number): string {\n\treturn formatCard(COMBO_CARDS[combo * 2 + 1]) + formatCard(COMBO_CARDS[combo * 2]);\n}\n","/**\n * Postflop betting tree.\n *\n * Purpose: the one place betting structure is decided — which actions exist,\n * what they cost, when a street ends, and where the hand terminates.\n *\n * Unlike a from-scratch solver there are no blinds and no preflop: the spot\n * starts with a dead pot and both players even. Each betting round opens with\n * the out-of-position player.\n *\n * Payoffs are measured against a baseline where the dead pot is split, which is\n * what makes the game zero-sum. Winning a showdown in which each player put in\n * `c` is worth `pot / 2 + c`; when someone folds it is `pot / 2 +` whatever the\n * folder had already put in. All amounts are integer units (chips * chipScale).\n */\n\nimport type { Runouts } from './runouts.ts';\n\n/**\n * One available bet size: a fraction of the pot after calling, absolute chips,\n * a multiple of the bet being faced (raises only), or a shove.\n */\nexport type BetSize = number | { chips: number } | { times: number } | 'allin';\n\n/** Sizes offered when facing a bet: one row for every round, or a row per round. */\nexport type RaiseSizes = readonly BetSize[] | readonly (readonly BetSize[])[];\n\n/** Whether raise sizes are given per round rather than once for all of them. */\nexport function raisesPerRound(sizes: RaiseSizes): sizes is readonly (readonly BetSize[])[] {\n\treturn sizes.length > 0 && Array.isArray(sizes[0]);\n}\n\n/**\n * A setting given once or per round, expanded to one entry per round.\n * @throws if a per-round list has the wrong length\n */\nexport function perRound<T>(value: T | readonly T[], listed: boolean, rounds: number, name: string): T[] {\n\tif (!listed) return Array.from({ length: rounds }, () => value as T);\n\tconst list = value as readonly T[];\n\tif (list.length === 1) return Array.from({ length: rounds }, () => list[0]);\n\tif (list.length !== rounds) {\n\t\tthrow new Error(\n\t\t\t`${name} has ${list.length} entries but this board has ${rounds} betting rounds; ` +\n\t\t\t\t'give one per round, or a single value for all of them',\n\t\t);\n\t}\n\treturn [...list];\n}\n\nexport const NodeKind = {\n\tDecision: 0,\n\tChance: 1,\n\tTerminalFold: 2,\n\tTerminalShowdown: 3,\n} as const;\n\nexport const ActionKind = {\n\tFold: 0,\n\tCheck: 1,\n\tCall: 2,\n\tBet: 3,\n\tRaise: 4,\n\tAllIn: 5,\n} as const;\n\nexport const ACTION_LABELS = ['fold', 'check', 'call', 'bet', 'raise', 'allin'] as const;\n\n/** Everything the tree builder needs. */\nexport interface TreeConfig {\n\t/** Dead money already in the middle, in units. */\n\treadonly potUnits: number;\n\t/** Effective stack behind, per player, in units. */\n\treadonly stackUnits: number;\n\t/** Bet sizes offered on each betting round. */\n\treadonly betSizes: readonly (readonly BetSize[])[];\n\t/**\n\t * Sizes offered when facing a bet, on every round or per round. Unset,\n\t * raises use the round's bet sizes.\n\t */\n\treadonly raiseSizes?: RaiseSizes;\n\t/** Maximum aggressive actions per round, the opening bet the first; once or per round. */\n\treadonly maxRaises: number | readonly number[];\n\t/** Offer a shove alongside the configured sizes; once or per round. */\n\treadonly allowAllIn: boolean | readonly boolean[];\n\treadonly chipScale: number;\n\t/** Smallest legal raise increment, in units. */\n\treadonly minRaiseUnits: number;\n\t/**\n\t * A bet or raise committing at least this fraction of the actor's\n\t * remaining stack becomes a shove instead; once or per round. Unset or 0,\n\t * never.\n\t */\n\treadonly allInThreshold?: number | readonly number[];\n\t/**\n\t * Out of position may not lead into the player who made the last\n\t * aggressive action of the round before; it may only check. Once or per\n\t * round.\n\t */\n\treadonly noDonk?: boolean | readonly boolean[];\n\t/**\n\t * Pot-fraction sizes closer together than this collapse into one, their\n\t * mean. Unset or 0, none.\n\t */\n\treadonly mergeSizes?: number;\n}\n\n/**\n * Collapse pot-fraction sizes closer together than `distance` into their mean.\n * Other kinds of size pass through untouched, after the merged ones.\n */\nexport function mergeBetSizes(sizes: readonly BetSize[], distance: number): BetSize[] {\n\tif (!(distance > 0)) return [...sizes];\n\tconst fractions = sizes.filter((size): size is number => typeof size === 'number').sort((a, b) => a - b);\n\tconst others = sizes.filter((size) => typeof size !== 'number');\n\tconst merged: number[] = [];\n\tlet cluster: number[] = [];\n\tconst flush = (): void => {\n\t\tif (cluster.length === 0) return;\n\t\tmerged.push(Math.round((cluster.reduce((a, b) => a + b, 0) / cluster.length) * 1000) / 1000);\n\t\tcluster = [];\n\t};\n\tfor (const size of fractions) {\n\t\tif (cluster.length > 0 && size - cluster[0] >= distance) flush();\n\t\tcluster.push(size);\n\t}\n\tflush();\n\treturn [...merged, ...others];\n}\n\n/** Structure-of-arrays betting tree. */\nexport interface Tree {\n\treadonly nodeCount: number;\n\treadonly edgeCount: number;\n\treadonly kind: Uint8Array;\n\t/** Player to act at a decision node, else -1. 0 is out of position. */\n\treadonly player: Int8Array;\n\treadonly round: Uint8Array;\n\treadonly firstEdge: Int32Array;\n\treadonly numEdges: Uint8Array;\n\t/** Total in the middle at this node, in units, including the dead pot. */\n\treadonly pot: Int32Array;\n\t/**\n\t * TerminalFold: value to player 0, signed, in units.\n\t * TerminalShowdown: what the winner gains, in units.\n\t */\n\treadonly payoff: Int32Array;\n\treadonly edgeAction: Uint8Array;\n\t/** The actor's total investment after acting, in units. */\n\treadonly edgeTarget: Int32Array;\n\treadonly edgeChild: Int32Array;\n\treadonly decisionNodes: Int32Array;\n}\n\ninterface BetState {\n\treadonly round: number;\n\treadonly invested: readonly [number, number];\n\treadonly toAct: 0 | 1;\n\treadonly aggressions: number;\n\treadonly lastRaise: number;\n\treadonly acted: number;\n\t/** What each player had in when this round opened; equal for both. */\n\treadonly base: number;\n\t/** Who last bet or raised this round, or -1. */\n\treadonly aggressor: number;\n\t/** Who last bet or raised the round before, or -1. */\n\treadonly previousAggressor: number;\n}\n\n/**\n * Build the betting tree for a spot.\n *\n * @param config betting structure, in units\n * @param runouts board completions, which fix the number of rounds\n */\nexport function buildTree(config: TreeConfig, runouts: Runouts): Tree {\n\tconst kind: number[] = [];\n\tconst player: number[] = [];\n\tconst round: number[] = [];\n\tconst firstEdge: number[] = [];\n\tconst numEdges: number[] = [];\n\tconst pot: number[] = [];\n\tconst payoff: number[] = [];\n\tconst edgeAction: number[] = [];\n\tconst edgeTarget: number[] = [];\n\tconst edgeChild: number[] = [];\n\n\tconst { potUnits, stackUnits, chipScale, minRaiseUnits } = config;\n\tconst rounds = runouts.rounds;\n\tconst maxRaises = perRound(config.maxRaises, Array.isArray(config.maxRaises), rounds, 'maxRaises');\n\tconst allowAllIn = perRound(config.allowAllIn, Array.isArray(config.allowAllIn), rounds, 'allowAllIn');\n\tconst merge = config.mergeSizes ?? 0;\n\tconst raiseSizes = config.raiseSizes\n\t\t? perRound<readonly BetSize[]>(config.raiseSizes, raisesPerRound(config.raiseSizes), rounds, 'raiseSizes').map(\n\t\t\t\t(row) => mergeBetSizes(row, merge),\n\t\t\t)\n\t\t: null;\n\tconst betSizes = config.betSizes.map((row) => mergeBetSizes(row, merge));\n\tconst threshold = perRound(config.allInThreshold ?? 0, Array.isArray(config.allInThreshold), rounds, 'allInThreshold');\n\tconst noDonk = perRound(config.noDonk ?? false, Array.isArray(config.noDonk), rounds, 'noDonk');\n\tconst half = Math.round(potUnits / 2);\n\n\tconst addNode = (\n\t\tnodeKind: number,\n\t\tnodePlayer: number,\n\t\tnodeRound: number,\n\t\tnodePot: number,\n\t\tnodePayoff: number,\n\t): number => {\n\t\tkind.push(nodeKind);\n\t\tplayer.push(nodePlayer);\n\t\tround.push(nodeRound);\n\t\tfirstEdge.push(-1);\n\t\tnumEdges.push(0);\n\t\tpot.push(nodePot);\n\t\tpayoff.push(nodePayoff);\n\t\treturn kind.length - 1;\n\t};\n\n\t/** What follows once a round's betting has closed. */\n\tconst closeRound = (state: BetState): number => {\n\t\tconst total = potUnits + state.invested[0] + state.invested[1];\n\t\tconst allIn = state.invested[0] >= stackUnits || state.invested[1] >= stackUnits;\n\n\t\tif (state.round + 1 >= runouts.rounds) {\n\t\t\t// Both invested the same, so the winner gains half the dead pot plus\n\t\t\t// the opponent's investment.\n\t\t\treturn addNode(NodeKind.TerminalShowdown, -1, state.round, total, half + state.invested[0]);\n\t\t}\n\n\t\tconst node = addNode(NodeKind.Chance, -1, state.round, total, 0);\n\t\tconst next: BetState = {\n\t\t\tround: state.round + 1,\n\t\t\tinvested: state.invested,\n\t\t\ttoAct: 0,\n\t\t\taggressions: 0,\n\t\t\tlastRaise: minRaiseUnits,\n\t\t\tacted: 0,\n\t\t\tbase: state.invested[0],\n\t\t\taggressor: -1,\n\t\t\tpreviousAggressor: state.aggressor,\n\t\t};\n\t\t// With someone already all in there is nothing left to decide, so the\n\t\t// remaining streets run out straight to showdown.\n\t\tconst child = allIn ? closeRound(next) : buildDecision(next);\n\n\t\tfirstEdge[node] = edgeChild.length;\n\t\tnumEdges[node] = 1;\n\t\tedgeAction.push(ActionKind.Check);\n\t\tedgeTarget.push(0);\n\t\tedgeChild.push(child);\n\t\treturn node;\n\t};\n\n\t/** Resolve one bet size to a total-investment target, or null if illegal. */\n\tconst resolveTarget = (size: BetSize, state: BetState, cap: number): number | null => {\n\t\tconst me = state.toAct;\n\t\tconst opp = (1 - me) as 0 | 1;\n\t\tconst mine = state.invested[me];\n\t\tconst theirs = state.invested[opp];\n\t\tconst owed = Math.max(0, theirs - mine);\n\t\tconst potAfterCall = potUnits + state.invested[0] + state.invested[1] + owed;\n\n\t\tlet target: number;\n\t\tif (size === 'allin') target = cap;\n\t\telse if (typeof size === 'number') target = mine + owed + Math.round(size * potAfterCall);\n\t\telse if ('times' in size) target = state.base + Math.round(size.times * (theirs - state.base));\n\t\telse target = mine + owed + Math.round(size.chips * chipScale);\n\n\t\ttarget = Math.min(target, cap);\n\t\tif (target <= theirs) return null;\n\n\t\tconst raiseSize = target - theirs;\n\t\tconst minimum = Math.max(state.lastRaise, minRaiseUnits);\n\t\tif (raiseSize < minimum) {\n\t\t\tconst bumped = theirs + minimum;\n\t\t\tif (bumped > cap) return null;\n\t\t\ttarget = bumped;\n\t\t}\n\t\treturn target;\n\t};\n\n\tconst buildDecision = (state: BetState): number => {\n\t\tconst me = state.toAct;\n\t\tconst opp = (1 - me) as 0 | 1;\n\t\tconst mine = state.invested[me];\n\t\tconst theirs = state.invested[opp];\n\t\tconst owed = Math.max(0, theirs - mine);\n\t\tconst myRemaining = stackUnits - mine;\n\n\t\tconst total = potUnits + state.invested[0] + state.invested[1];\n\t\tconst node = addNode(NodeKind.Decision, me, state.round, total, 0);\n\n\t\tconst actions: { action: number; target: number }[] = [];\n\t\tif (owed > 0) actions.push({ action: ActionKind.Fold, target: mine });\n\t\tactions.push({\n\t\t\taction: owed > 0 ? ActionKind.Call : ActionKind.Check,\n\t\t\ttarget: mine + Math.min(owed, myRemaining),\n\t\t});\n\n\t\t// Nobody can put in more than the opponent is able to match.\n\t\tconst cap = Math.min(stackUnits, theirs + (stackUnits - theirs));\n\t\t// A donk bet: out of position opening a round into the player who\n\t\t// took the betting lead the round before.\n\t\tconst donk =\n\t\t\tnoDonk[state.round] && me === 0 && owed === 0 && state.aggressions === 0 && state.previousAggressor === 1;\n\t\tif (state.aggressions < maxRaises[state.round] && myRemaining > owed && !donk) {\n\t\t\tconst seen = new Set<number>();\n\t\t\tconst sizes: BetSize[] =\n\t\t\t\towed > 0 && raiseSizes\n\t\t\t\t\t? [...raiseSizes[state.round]]\n\t\t\t\t\t: [...(betSizes[state.round] ?? [])].filter((size) => !(typeof size === 'object' && 'times' in size));\n\t\t\tif (allowAllIn[state.round]) sizes.push('allin');\n\n\t\t\tfor (const size of sizes) {\n\t\t\t\tlet target = resolveTarget(size, state, cap);\n\t\t\t\t// Close enough to everything that the rest is not worth keeping.\n\t\t\t\tif (target !== null && threshold[state.round] > 0 && target - mine >= threshold[state.round] * myRemaining) {\n\t\t\t\t\ttarget = cap;\n\t\t\t\t}\n\t\t\t\tif (target === null || seen.has(target)) continue;\n\t\t\t\tseen.add(target);\n\t\t\t\tconst isShove = target >= stackUnits;\n\t\t\t\tactions.push({\n\t\t\t\t\taction: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet,\n\t\t\t\t\ttarget,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst base = edgeChild.length;\n\t\tfirstEdge[node] = base;\n\t\tnumEdges[node] = actions.length;\n\t\tfor (const entry of actions) {\n\t\t\tedgeAction.push(entry.action);\n\t\t\tedgeTarget.push(entry.target);\n\t\t\tedgeChild.push(-1);\n\t\t}\n\n\t\tactions.forEach((entry, i) => {\n\t\t\tconst invested: [number, number] =\n\t\t\t\tme === 0 ? [entry.target, theirs] : [theirs, entry.target];\n\t\t\tlet child: number;\n\n\t\t\tif (entry.action === ActionKind.Fold) {\n\t\t\t\t// The folder forfeits what they put in, and the dead pot goes\n\t\t\t\t// to the other player.\n\t\t\t\tconst value = me === 0 ? -(half + mine) : half + mine;\n\t\t\t\tchild = addNode(NodeKind.TerminalFold, -1, state.round, total, value);\n\t\t\t} else if (entry.action === ActionKind.Check || entry.action === ActionKind.Call) {\n\t\t\t\tconst closed = invested[0] === invested[1] && state.acted + 1 >= 2;\n\t\t\t\tchild = closed\n\t\t\t\t\t? closeRound({ ...state, invested, acted: state.acted + 1 })\n\t\t\t\t\t: buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 });\n\t\t\t} else {\n\t\t\t\tchild = buildDecision({\n\t\t\t\t\tround: state.round,\n\t\t\t\t\tinvested,\n\t\t\t\t\ttoAct: opp,\n\t\t\t\t\taggressions: state.aggressions + 1,\n\t\t\t\t\tlastRaise: entry.target - theirs,\n\t\t\t\t\tacted: state.acted + 1,\n\t\t\t\t\tbase: state.base,\n\t\t\t\t\taggressor: me,\n\t\t\t\t\tpreviousAggressor: state.previousAggressor,\n\t\t\t\t});\n\t\t\t}\n\t\t\tedgeChild[base + i] = child;\n\t\t});\n\n\t\treturn node;\n\t};\n\n\tbuildDecision({\n\t\tround: 0,\n\t\tinvested: [0, 0],\n\t\ttoAct: 0,\n\t\taggressions: 0,\n\t\tlastRaise: minRaiseUnits,\n\t\tacted: 0,\n\t\tbase: 0,\n\t\taggressor: -1,\n\t\tpreviousAggressor: -1,\n\t});\n\n\tconst decisionNodes: number[] = [];\n\tfor (let i = 0; i < kind.length; i++) if (kind[i] === NodeKind.Decision) decisionNodes.push(i);\n\n\treturn {\n\t\tnodeCount: kind.length,\n\t\tedgeCount: edgeChild.length,\n\t\tkind: Uint8Array.from(kind),\n\t\tplayer: Int8Array.from(player),\n\t\tround: Uint8Array.from(round),\n\t\tfirstEdge: Int32Array.from(firstEdge),\n\t\tnumEdges: Uint8Array.from(numEdges),\n\t\tpot: Int32Array.from(pot),\n\t\tpayoff: Int32Array.from(payoff),\n\t\tedgeAction: Uint8Array.from(edgeAction),\n\t\tedgeTarget: Int32Array.from(edgeTarget),\n\t\tedgeChild: Int32Array.from(edgeChild),\n\t\tdecisionNodes: Int32Array.from(decisionNodes),\n\t};\n}\n","/**\n * Card relabellings, and the symmetries of a spot.\n *\n * Purpose: the one place a runout is identified with another.\n *\n * A map relabels cards — and with them every combination — so that a subgame\n * after one card can stand for the subgame after another. For a suit\n * permutation that fixes the board and both ranges this is exact: the two\n * subgames are mirror images, so solving one solves both. Later abstractions\n * (rank relabellings) reuse the same table and accept an approximation.\n *\n * Map 0 is always the identity.\n */\n\nimport { COMBO_CARDS, COMBOS, comboIndex, DECK } from './cards.ts';\n\n/** Every relabelling in use, each as a card map and the combination map it induces. */\nexport class CardMaps {\n\t/** `card[m][x]`: what map `m` sends card `x` to. */\n\treadonly card: Uint8Array[] = [];\n\t/** `combo[m][h]`: what map `m` sends combination `h` to. */\n\treadonly combo: Uint16Array[] = [];\n\tprivate readonly known = new Map<string, number>();\n\n\tconstructor() {\n\t\tconst identity = new Uint8Array(DECK);\n\t\tfor (let card = 0; card < DECK; card++) identity[card] = card;\n\t\tthis.add(identity);\n\t}\n\n\t/** Register a card map, returning its id; the same map always gets the same id. */\n\tadd(cardMap: Uint8Array): number {\n\t\tconst key = cardMap.join(',');\n\t\tconst existing = this.known.get(key);\n\t\tif (existing !== undefined) return existing;\n\t\tconst combo = new Uint16Array(COMBOS);\n\t\tfor (let h = 0; h < COMBOS; h++) {\n\t\t\tcombo[h] = comboIndex(cardMap[COMBO_CARDS[h * 2]], cardMap[COMBO_CARDS[h * 2 + 1]]);\n\t\t}\n\t\tconst id = this.card.length;\n\t\tthis.card.push(Uint8Array.from(cardMap));\n\t\tthis.combo.push(combo);\n\t\tthis.known.set(key, id);\n\t\treturn id;\n\t}\n\n\t/** The map that applies `first`, then `second`. */\n\tthen(first: number, second: number): number {\n\t\tconst a = this.card[first];\n\t\tconst b = this.card[second];\n\t\tconst out = new Uint8Array(DECK);\n\t\tfor (let card = 0; card < DECK; card++) out[card] = b[a[card]];\n\t\treturn this.add(out);\n\t}\n\n\t/** The inverse of a map, which must be a bijection. */\n\tinverse(id: number): number {\n\t\tconst a = this.card[id];\n\t\tconst out = new Uint8Array(DECK);\n\t\tfor (let card = 0; card < DECK; card++) out[a[card]] = card;\n\t\treturn this.add(out);\n\t}\n}\n\n/** All 24 orderings of the four suits, identity first. */\nfunction suitPermutations(): number[][] {\n\tconst out: number[][] = [];\n\tconst walk = (prefix: number[]): void => {\n\t\tif (prefix.length === 4) {\n\t\t\tout.push(prefix);\n\t\t\treturn;\n\t\t}\n\t\tfor (let s = 0; s < 4; s++) if (!prefix.includes(s)) walk([...prefix, s]);\n\t};\n\twalk([]);\n\treturn out;\n}\n\n/** The card map of a suit permutation; cards are `rank * 4 + suit`. */\nfunction suitMap(perm: readonly number[]): Uint8Array {\n\tconst out = new Uint8Array(DECK);\n\tfor (let card = 0; card < DECK; card++) out[card] = (card & ~3) | perm[card & 3];\n\treturn out;\n}\n\n/**\n * The suit permutations that leave a spot unchanged: they fix the board as a\n * set and map each range onto itself, weight for weight.\n *\n * Returned as card maps, identity first. Ranges are compared exactly, so a\n * range that differs between suits anywhere — an exact combination such as\n * `AsKh`, or a fractional weight on one suit — breaks that symmetry, and the\n * spot is solved as it would be without any.\n *\n * @param board the board as given\n * @param ranges each player's weights, board cards already removed\n */\nexport function suitSymmetries(board: readonly number[], ranges: readonly Float64Array[]): Uint8Array[] {\n\tconst onBoard = new Uint8Array(DECK);\n\tfor (const card of board) onBoard[card] = 1;\n\tconst out: Uint8Array[] = [];\n\tfor (const perm of suitPermutations()) {\n\t\tconst map = suitMap(perm);\n\t\tlet ok = true;\n\t\tfor (const card of board) if (!onBoard[map[card]]) ok = false;\n\t\tfor (let h = 0; ok && h < COMBOS; h++) {\n\t\t\tconst image = comboIndex(map[COMBO_CARDS[h * 2]], map[COMBO_CARDS[h * 2 + 1]]);\n\t\t\tfor (const weights of ranges) {\n\t\t\t\tif (weights[h] !== weights[image]) {\n\t\t\t\t\tok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (ok) out.push(map);\n\t}\n\treturn out;\n}\n","/**\n * Board completions.\n *\n * Purpose: the one place the cards still to come are enumerated and indexed.\n *\n * The board is given, so unlike a from-scratch solver there is nothing to deal\n * before the first betting round. What remains is the turn, the river, or\n * neither. Completions are ORDERED — the turn is known when turn betting\n * happens, so `Kh` then `2c` is a different line from `2c` then `Kh`, even\n * though the final board is the same.\n *\n * Boards at a round are stored densely and grouped by parent, so the children\n * of one board are a contiguous range and a worker can own a contiguous slice.\n *\n * Suit symmetry folds mirror-image deals together: on a two-tone flop a club\n * turn is a diamond turn with the suits swapped, so only one is stored, and it\n * stands for both. `orbitStart` and friends record which real deals each\n * stored board stands for and how to relabel hands onto it.\n */\n\nimport { CardMaps } from './abstraction.ts';\nimport { DECK, formatCards } from './cards.ts';\n\n/** Boards visible at each betting round. */\nexport interface Runouts {\n\t/** Betting rounds: 3 from a flop, 2 from a turn, 1 from a river. */\n\treadonly rounds: number;\n\t/** Cards on the board at each round: 3, 4, 5. */\n\treadonly width: readonly number[];\n\t/** Distinct boards stored at each round; always 1 at round 0. */\n\treadonly counts: readonly number[];\n\t/** Flat board cards per round, `counts[r] * width[r]` entries. */\n\treadonly cards: readonly Uint8Array[];\n\t/**\n\t * Children of each board, as a prefix: the boards at round `r` dealt from\n\t * board `p` of round `r - 1` are `childStart[r][p]` to\n\t * `childStart[r][p + 1]`. Empty at round 0.\n\t */\n\treadonly childStart: readonly Int32Array[];\n\t/** Each board's parent at the round before; -1 at round 0. */\n\treadonly parent: readonly Int32Array[];\n\t/**\n\t * The real deals each stored board stands for, as a prefix into\n\t * `orbitMap`/`orbitCard`: board `b` of round `r` stands for members\n\t * `orbitStart[r][b]` to `orbitStart[r][b + 1]`. Member 0 is the board\n\t * itself under the identity. Another member is a card that could have been\n\t * dealt instead, with the map that sends it — and every combination with\n\t * it — onto this board; the map fixes the parent board. Without symmetry\n\t * every board stands only for itself.\n\t */\n\treadonly orbitStart: readonly Int32Array[];\n\treadonly orbitMap: readonly Int32Array[];\n\treadonly orbitCard: readonly Uint8Array[];\n\t/**\n\t * The symmetries each stored board still has, as a prefix into\n\t * `stabiliserMap`: map ids, identity first. A board with more than the\n\t * identity holds hands that mirror each other on it, whose strategies the\n\t * solver keeps tied together.\n\t */\n\treadonly stabiliserStart: readonly Int32Array[];\n\treadonly stabiliserMap: readonly Int32Array[];\n\t/** The relabellings `orbitMap` refers to. */\n\treadonly maps: CardMaps;\n\t/** Whether any board stands for more than itself. */\n\treadonly symmetric: boolean;\n\t/**\n\t * Whether some board stands for deals that are not its exact mirror\n\t * images — runout buckets — so the stored game approximates the real one.\n\t */\n\treadonly approximate: boolean;\n\t/** The board as given. */\n\treadonly initial: readonly number[];\n}\n\n/**\n * Enumerate every way the given board can complete, one board per orbit.\n *\n * With no symmetry beyond the identity every completion is stored, in\n * ascending order of the dealt card. With a symmetry group, a dealt card is\n * stored only if it is the lowest of the cards the board's own symmetries\n * send it to; the others become members of its orbit. A child's symmetries are\n * its parent's that also fix the card just dealt, so they shrink as cards\n * fall.\n *\n * @param board 3, 4 or 5 distinct cards\n * @param symmetries card maps that fix the board and both ranges, identity\n * first; see `suitSymmetries`. Omitted, none.\n * @throws if the board is not a legal postflop board\n */\nexport function enumerateRunouts(\n\tboard: readonly number[],\n\tsymmetries?: readonly Uint8Array[],\n\tmerge?: RunoutMerge,\n): Runouts {\n\tif (board.length < 3 || board.length > 5) {\n\t\tthrow new Error(`A postflop board has 3, 4 or 5 cards; got ${board.length} (${formatCards(board)})`);\n\t}\n\tif (new Set(board).size !== board.length) {\n\t\tthrow new Error(`Board repeats a card: ${formatCards(board)}`);\n\t}\n\n\tconst maps = new CardMaps();\n\tconst group = (symmetries ?? []).map((map) => maps.add(map));\n\tif (group.length === 0 || group[0] !== 0) group.unshift(0);\n\n\tconst rounds = 5 - board.length + 1;\n\tconst width: number[] = [board.length];\n\tconst counts: number[] = [1];\n\tconst cards: Uint8Array[] = [Uint8Array.from(board)];\n\tconst childStart: Int32Array[] = [new Int32Array(0)];\n\tconst parent: Int32Array[] = [Int32Array.of(-1)];\n\tconst orbitStart: Int32Array[] = [Int32Array.of(0, 1)];\n\tconst orbitMap: Int32Array[] = [Int32Array.of(0)];\n\tconst orbitCard: Uint8Array[] = [new Uint8Array(1)];\n\tlet stabilisers: number[][] = [group];\n\tlet symmetric = false;\n\tlet approximate = false;\n\tconst stabiliserStart: Int32Array[] = [];\n\tconst stabiliserMap: Int32Array[] = [];\n\tconst recordStabilisers = (list: number[][]): void => {\n\t\tconst starts = new Int32Array(list.length + 1);\n\t\tconst flat: number[] = [];\n\t\tfor (let b = 0; b < list.length; b++) {\n\t\t\tstarts[b] = flat.length;\n\t\t\tflat.push(...list[b]);\n\t\t}\n\t\tstarts[list.length] = flat.length;\n\t\tstabiliserStart.push(starts);\n\t\tstabiliserMap.push(Int32Array.from(flat));\n\t};\n\trecordStabilisers(stabilisers);\n\n\tconst used = new Uint8Array(DECK);\n\tconst seen = new Uint8Array(DECK);\n\tfor (let round = 1; round < rounds; round++) {\n\t\tconst previousWidth = width[round - 1];\n\t\tconst previousCount = counts[round - 1];\n\t\tconst previousCards = cards[round - 1];\n\t\tconst thisWidth = previousWidth + 1;\n\n\t\tconst level: number[] = [];\n\t\tconst parents: number[] = [];\n\t\tconst starts = new Int32Array(previousCount + 1);\n\t\tconst memberStart: number[] = [0];\n\t\tconst memberMap: number[] = [];\n\t\tconst memberCard: number[] = [];\n\t\tconst nextStabilisers: number[][] = [];\n\n\t\tfor (let p = 0; p < previousCount; p++) {\n\t\t\tstarts[p] = parents.length;\n\t\t\tused.fill(0);\n\t\t\tseen.fill(0);\n\t\t\tconst base = p * previousWidth;\n\t\t\tfor (let i = 0; i < previousWidth; i++) used[previousCards[base + i]] = 1;\n\t\t\tconst stabiliser = stabilisers[p];\n\n\t\t\t// One stored child per orbit of the board's symmetries.\n\t\t\tconst children: { card: number; maps: number[]; cards: number[]; fixing: number[]; merged: boolean }[] = [];\n\t\t\tfor (let card = 0; card < DECK; card++) {\n\t\t\t\tif (used[card] || seen[card]) continue;\n\t\t\t\t// Ascending, so the first unseen card of an orbit is its lowest.\n\t\t\t\tconst child = { card, maps: [] as number[], cards: [] as number[], fixing: [] as number[], merged: false };\n\t\t\t\tfor (const sigma of stabiliser) {\n\t\t\t\t\tconst image = maps.card[sigma][card];\n\t\t\t\t\tif (image === card) child.fixing.push(sigma);\n\t\t\t\t\tif (seen[image]) continue;\n\t\t\t\t\tseen[image] = 1;\n\t\t\t\t\t// `sigma` sends `card` to `image`, so its inverse sends the\n\t\t\t\t\t// deal of `image` back onto this board.\n\t\t\t\t\tchild.maps.push(image === card ? 0 : maps.inverse(sigma));\n\t\t\t\t\tchild.cards.push(image);\n\t\t\t\t}\n\t\t\t\tchildren.push(child);\n\t\t\t}\n\n\t\t\t// Runout buckets: a child that plays like an earlier one is folded\n\t\t\t// into it, relabelled by swapping the two cards' ranks.\n\t\t\tif (merge) {\n\t\t\t\tconst boardRanks = new Set<number>();\n\t\t\t\tfor (let i = 0; i < previousWidth; i++) boardRanks.add(previousCards[base + i] >> 2);\n\t\t\t\tfor (let j = 0; j < children.length; j++) {\n\t\t\t\t\tconst later = children[j];\n\t\t\t\t\tconst rankJ = later.card >> 2;\n\t\t\t\t\tif (boardRanks.has(rankJ)) continue;\n\t\t\t\t\tfor (let i = 0; i < j; i++) {\n\t\t\t\t\t\tconst earlier = children[i];\n\t\t\t\t\t\tif (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;\n\t\t\t\t\t\tconst rankI = earlier.card >> 2;\n\t\t\t\t\t\tif (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;\n\t\t\t\t\t\tif (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;\n\t\t\t\t\t\tconst swap = maps.add(rankSwap(rankI, rankJ));\n\t\t\t\t\t\tfor (let m = 0; m < later.maps.length; m++) {\n\t\t\t\t\t\t\tearlier.maps.push(maps.then(later.maps[m], swap));\n\t\t\t\t\t\t\tearlier.cards.push(later.cards[m]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlater.merged = true;\n\t\t\t\t\t\tapproximate = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const child of children) {\n\t\t\t\tif (child.merged) continue;\n\t\t\t\tfor (let i = 0; i < previousWidth; i++) level.push(previousCards[base + i]);\n\t\t\t\tlevel.push(child.card);\n\t\t\t\tparents.push(p);\n\t\t\t\tmemberMap.push(...child.maps);\n\t\t\t\tmemberCard.push(...child.cards);\n\t\t\t\tmemberStart.push(memberMap.length);\n\t\t\t\tnextStabilisers.push(child.fixing);\n\t\t\t\tif (child.maps.length > 1) symmetric = true;\n\t\t\t}\n\t\t}\n\t\tstarts[previousCount] = parents.length;\n\n\t\twidth.push(thisWidth);\n\t\tcounts.push(parents.length);\n\t\tcards.push(Uint8Array.from(level));\n\t\tchildStart.push(starts);\n\t\tparent.push(Int32Array.from(parents));\n\t\torbitStart.push(Int32Array.from(memberStart));\n\t\torbitMap.push(Int32Array.from(memberMap));\n\t\torbitCard.push(Uint8Array.from(memberCard));\n\t\tstabilisers = nextStabilisers;\n\t\trecordStabilisers(stabilisers);\n\t}\n\n\treturn {\n\t\trounds, width, counts, cards, childStart, parent, orbitStart, orbitMap, orbitCard,\n\t\tstabiliserStart, stabiliserMap, maps, symmetric, approximate,\n\t\tinitial: [...board],\n\t};\n}\n\n/** Which runouts may be bucketed together; see `enumerateRunouts`. */\nexport interface RunoutMerge {\n\t/**\n\t * Whether swapping these two ranks leaves the game close enough to itself:\n\t * at the least, every hand in either range still maps to a hand in it.\n\t */\n\tranks(a: number, b: number): boolean;\n\t/** Largest distance between two ranks in one bucket, counted from the stored card. */\n\treadonly maxGap: number;\n}\n\n/** The card map swapping two ranks in every suit. */\nexport function rankSwap(a: number, b: number): Uint8Array {\n\tconst out = new Uint8Array(DECK);\n\tfor (let card = 0; card < DECK; card++) {\n\t\tconst rank = card >> 2;\n\t\tout[card] = ((rank === a ? b : rank === b ? a : rank) << 2) | (card & 3);\n\t}\n\treturn out;\n}\n\n/**\n * How far a rank goes toward a straight with the board: the most board ranks\n * sharing one five-rank window with it, the ace counting low as well.\n */\nexport function connectivity(boardRanks: ReadonlySet<number>, rank: number): number {\n\tlet best = 0;\n\t// Windows by their lowest rank; -1 is the wheel, A-2-3-4-5.\n\tfor (let low = -1; low <= 8; low++) {\n\t\tif (rank < low || rank > low + 4) {\n\t\t\tif (!(low === -1 && rank === 12)) continue;\n\t\t}\n\t\tlet count = 0;\n\t\tfor (let r = low; r <= low + 4; r++) {\n\t\t\tconst actual = r === -1 ? 12 : r;\n\t\t\tif (actual !== rank && boardRanks.has(actual)) count++;\n\t\t}\n\t\tif (count > best) best = count;\n\t}\n\treturn best;\n}\n\n/**\n * Map a board index back to its ancestor at an earlier round.\n *\n * @param runouts the enumeration\n * @param board board index at `round`\n * @param round that board's round\n * @param target the earlier round wanted\n */\nexport function boardAtRound(runouts: Runouts, board: number, round: number, target: number): number {\n\tlet index = board;\n\tfor (let r = round; r > target; r--) index = runouts.parent[r][index];\n\treturn index;\n}\n\n/** A real board, as the solver stores it. */\nexport interface ResolvedBoard {\n\treadonly round: number;\n\t/** The stored board standing for it. */\n\treadonly board: number;\n\t/**\n\t * Real combination to stored combination: a hand `h` on the real board\n\t * plays as `combos[h]` on the stored one. The identity without symmetry.\n\t */\n\treadonly combos: Uint16Array;\n}\n\n/**\n * Find the stored board that stands for a real one.\n *\n * @param runouts the enumeration\n * @param board every card, the given board first and then the cards dealt in order\n * @throws if the cards do not extend the given board legally\n */\nexport function resolveBoard(runouts: Runouts, board: readonly number[]): ResolvedBoard {\n\tconst start = runouts.initial.length;\n\tfor (let i = 0; i < start; i++) {\n\t\tif (board[i] !== runouts.initial[i]) {\n\t\t\tthrow new Error(`${formatCards(board)} does not start with the spot's board ${formatCards(runouts.initial)}`);\n\t\t}\n\t}\n\tif (board.length > 5) throw new Error(`A board has at most 5 cards; got ${board.length}`);\n\tlet index = 0;\n\tlet map = 0;\n\tfor (let i = start; i < board.length; i++) {\n\t\tconst round = i - start + 1;\n\t\tconst dealt = runouts.maps.card[map][board[i]];\n\t\tlet found = -1;\n\t\tfor (let child = runouts.childStart[round][index]; child < runouts.childStart[round][index + 1] && found < 0; child++) {\n\t\t\tfor (let m = runouts.orbitStart[round][child]; m < runouts.orbitStart[round][child + 1]; m++) {\n\t\t\t\tif (runouts.orbitCard[round][m] !== dealt) continue;\n\t\t\t\tfound = child;\n\t\t\t\tmap = runouts.maps.then(map, runouts.orbitMap[round][m]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (found < 0) throw new Error(`${formatCards(board)} deals a card already on the board`);\n\t\tindex = found;\n\t}\n\treturn { round: board.length - start, board: index, combos: runouts.maps.combo[map] };\n}\n","/**\n * Weighted range parsing.\n *\n * Purpose: the one place range notation becomes solver input.\n *\n * A range is a dense `Float64Array` of 1326 weights, one per two-card\n * combination, in the same colex order the solver indexes by. Weights rather\n * than membership: a solver range is routinely partial (\"call 40% of these\"),\n * and every downstream reach vector is a weight anyway.\n *\n * The notation follows common usage:\n *\n * AA KK-99 22+ pairs, ranges and \"and better\"\n * AKs A2s+ A5s-A2s suited\n * AKo KTo+ offsuit\n * AK both suited and offsuit\n * AsKh one exact combination\n * Ax AXs AXo any second card, optionally constrained\n * random everything\n * AKo:0.5 any of the above at a partial weight\n *\n * `Xo` forms include the pair, because a pair is not suited; `Xs` forms do not.\n */\n\nimport { cardOf, comboIndex, COMBOS, parseCard, SUITS } from './cards.ts';\n\n/** Rank characters, highest first, as written in notation. */\nconst RANK_CHARS = 'AKQJT98765432';\n\n/** Rank index from its character, 12 = ace down to 0 = deuce. */\nfunction rankOfChar(char: string): number {\n\tconst index = RANK_CHARS.indexOf(char.toUpperCase());\n\tif (index < 0) throw new Error(`Invalid rank \"${char}\"`);\n\treturn 12 - index;\n}\n\n/** Every combination of a pocket pair: `C(4,2)` = 6. */\nfunction pairCombos(rank: number, out: number[]): void {\n\tfor (let a = 0; a < SUITS; a++) {\n\t\tfor (let b = a + 1; b < SUITS; b++) out.push(comboIndex(cardOf(rank, a), cardOf(rank, b)));\n\t}\n}\n\n/** Every suited combination of two ranks: 4. */\nfunction suitedCombos(high: number, low: number, out: number[]): void {\n\tfor (let suit = 0; suit < SUITS; suit++) out.push(comboIndex(cardOf(high, suit), cardOf(low, suit)));\n}\n\n/** Every offsuit combination of two ranks: 12. */\nfunction offsuitCombos(high: number, low: number, out: number[]): void {\n\tfor (let a = 0; a < SUITS; a++) {\n\t\tfor (let b = 0; b < SUITS; b++) {\n\t\t\tif (a !== b) out.push(comboIndex(cardOf(high, a), cardOf(low, b)));\n\t\t}\n\t}\n}\n\n/** Inclusive rank span, in either written order. */\nfunction ranksBetween(a: number, b: number): number[] {\n\tconst lo = Math.min(a, b);\n\tconst hi = Math.max(a, b);\n\tconst ranks: number[] = [];\n\tfor (let r = lo; r <= hi; r++) ranks.push(r);\n\treturn ranks;\n}\n\n/** Expand one notation segment, without its weight, to combination indices. */\nfunction expand(segment: string): number[] {\n\tconst out: number[] = [];\n\tconst text = segment.trim();\n\tif (!text) return out;\n\n\tif (/^(random|any|100%)$/i.test(text)) {\n\t\tfor (let combo = 0; combo < COMBOS; combo++) out.push(combo);\n\t\treturn out;\n\t}\n\n\t// An exact combination, e.g. AsKh.\n\tif (/^([AKQJT2-9][shdc]){2}$/i.test(text)) {\n\t\tconst a = parseCard(text.slice(0, 2));\n\t\tconst b = parseCard(text.slice(2, 4));\n\t\tif (a === b) throw new Error(`\"${text}\" uses the same card twice`);\n\t\tout.push(comboIndex(a, b));\n\t\treturn out;\n\t}\n\n\t// Any second card: Ax, AXs, AXo.\n\tconst wildcard = /^([AKQJT2-9])[xX]([so])?$/.exec(text);\n\tif (wildcard) {\n\t\tconst rank = rankOfChar(wildcard[1]);\n\t\tconst kind = wildcard[2]?.toLowerCase();\n\t\tfor (let other = 0; other < 13; other++) {\n\t\t\tif (other === rank) {\n\t\t\t\t// A pair is not suited, so it belongs to the offsuit and\n\t\t\t\t// unqualified forms only.\n\t\t\t\tif (kind !== 's') pairCombos(rank, out);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst high = Math.max(rank, other);\n\t\t\tconst low = Math.min(rank, other);\n\t\t\tif (kind !== 'o') suitedCombos(high, low, out);\n\t\t\tif (kind !== 's') offsuitCombos(high, low, out);\n\t\t}\n\t\treturn out;\n\t}\n\n\tconst emit = (high: number, low: number, kind: string | undefined): void => {\n\t\tif (high === low) {\n\t\t\tpairCombos(high, out);\n\t\t\treturn;\n\t\t}\n\t\tif (kind !== 'o') suitedCombos(high, low, out);\n\t\tif (kind !== 's') offsuitCombos(high, low, out);\n\t};\n\n\t// A span, e.g. KK-99 or A5s-A2s.\n\tconst span = /^([AKQJT2-9])([AKQJT2-9])([so])?-([AKQJT2-9])([AKQJT2-9])([so])?$/.exec(text);\n\tif (span) {\n\t\tconst [, a1, a2, k1, b1, b2, k2] = span;\n\t\tconst kind = k1 ?? k2;\n\t\tif (k1 && k2 && k1 !== k2) throw new Error(`\"${text}\" mixes suited and offsuit`);\n\n\t\tconst from1 = rankOfChar(a1);\n\t\tconst from2 = rankOfChar(a2);\n\t\tconst to1 = rankOfChar(b1);\n\t\tconst to2 = rankOfChar(b2);\n\n\t\tif (from1 === from2 && to1 === to2) {\n\t\t\tfor (const rank of ranksBetween(from1, to1)) pairCombos(rank, out);\n\t\t\treturn out;\n\t\t}\n\t\tif (from1 !== to1) throw new Error(`\"${text}\" must hold its higher rank fixed, e.g. A5s-A2s`);\n\t\tfor (const low of ranksBetween(from2, to2)) {\n\t\t\tif (low === from1) continue;\n\t\t\temit(Math.max(from1, low), Math.min(from1, low), kind);\n\t\t}\n\t\treturn out;\n\t}\n\n\t// \"And better\", e.g. 22+, A2s+, KTo+.\n\tconst plus = /^([AKQJT2-9])([AKQJT2-9])([so])?\\+$/.exec(text);\n\tif (plus) {\n\t\tconst first = rankOfChar(plus[1]);\n\t\tconst second = rankOfChar(plus[2]);\n\t\tconst kind = plus[3]?.toLowerCase();\n\n\t\tif (first === second) {\n\t\t\t// Pairs climb to aces.\n\t\t\tfor (let rank = first; rank <= 12; rank++) pairCombos(rank, out);\n\t\t\treturn out;\n\t\t}\n\t\t// Non-pairs climb the lower card to just under the higher one.\n\t\tconst high = Math.max(first, second);\n\t\tconst from = Math.min(first, second);\n\t\tfor (let low = from; low < high; low++) emit(high, low, kind);\n\t\treturn out;\n\t}\n\n\t// A single class, e.g. AA, AKs, AKo, AK.\n\tconst single = /^([AKQJT2-9])([AKQJT2-9])([so])?$/.exec(text);\n\tif (single) {\n\t\tconst first = rankOfChar(single[1]);\n\t\tconst second = rankOfChar(single[2]);\n\t\tconst kind = single[3]?.toLowerCase();\n\t\tif (first === second && kind === 's') throw new Error(`\"${text}\" is impossible: a pair cannot be suited`);\n\t\temit(Math.max(first, second), Math.min(first, second), kind);\n\t\treturn out;\n\t}\n\n\tthrow new Error(`Unrecognised range notation: \"${segment.trim()}\"`);\n}\n\n/**\n * Parse range notation into per-combination weights.\n *\n * Repeating a combination keeps the LAST weight given, so a narrowing segment\n * can follow a broad one: `random:0.1, AA:1` is a light range with pure aces.\n *\n * @param notation comma-separated segments, each optionally `:weight`\n * @returns weights indexed by combination, length 1326\n */\nexport function parseRange(notation: string): Float64Array {\n\tconst weights = new Float64Array(COMBOS);\n\tif (!notation || !notation.trim()) return weights;\n\n\tfor (const segment of notation.split(',')) {\n\t\tif (!segment.trim()) continue;\n\t\tconst [body, weightText] = segment.split(':');\n\t\tlet weight = 1;\n\t\tif (weightText !== undefined) {\n\t\t\tweight = Number(weightText.trim().replace('%', '')) / (weightText.includes('%') ? 100 : 1);\n\t\t\tif (!Number.isFinite(weight) || weight < 0 || weight > 1) {\n\t\t\t\tthrow new Error(`Weight in \"${segment.trim()}\" must be between 0 and 1`);\n\t\t\t}\n\t\t}\n\t\tfor (const combo of expand(body)) weights[combo] = weight;\n\t}\n\treturn weights;\n}\n\n/** Combinations carrying any weight. */\nexport function activeCombos(weights: Float64Array): number[] {\n\tconst combos: number[] = [];\n\tfor (let combo = 0; combo < COMBOS; combo++) if (weights[combo] > 0) combos.push(combo);\n\treturn combos;\n}\n\n/** Total weight, i.e. combinations counted with their weight. */\nexport function rangeWeight(weights: Float64Array): number {\n\tlet total = 0;\n\tfor (let combo = 0; combo < COMBOS; combo++) total += weights[combo];\n\treturn total;\n}\n","/**\n * Five-to-seven card hand evaluation.\n *\n * Purpose: turn a set of cards into a single integer whose order is hand\n * strength, with exact equality for chops.\n *\n * Ported from the author's `poker-bitvaljs` (MIT), where the same routine is\n * proven order-equivalent to a BigInt reference over all 2,598,960 five-card\n * and all 133,784,560 seven-card hands. The port is re-verified here against an\n * independent classifier rather than taken on trust — the original's evidence\n * says nothing about whether this transcription is faithful.\n *\n * Input is four 13-bit rank masks, one per suit, which makes combining hole\n * cards with a board four ORs. Output packs a category and five tiebreak\n * nibbles into one int32:\n *\n * value = category * 16^5 + t1 * 16^4 + ... + t5\n *\n * Straight flushes of the same top rank in different suits compare EQUAL, which\n * is correct poker and what a solver needs to score chops.\n */\n\n/** Population count of each 13-bit rank mask. */\nconst POPCOUNT = new Uint8Array(8192);\n\n/** Top rank of the best straight in a mask: 4..12, 3 for the wheel, -1 for none. */\nconst STRAIGHT = new Int8Array(8192);\n\nfor (let mask = 0; mask < 8192; mask++) {\n\tlet bits = 0;\n\tfor (let x = mask; x; x &= x - 1) bits++;\n\tPOPCOUNT[mask] = bits;\n\n\tlet run = 0;\n\tlet top = -1;\n\tfor (let rank = 12; rank >= 0; rank--) {\n\t\tif (mask & (1 << rank)) {\n\t\t\tif (++run >= 5) {\n\t\t\t\ttop = rank + 4;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\trun = 0;\n\t\t}\n\t}\n\t// The wheel is the one straight the descending scan cannot see, because the\n\t// ace sits at the far end of the mask from the four it completes.\n\tif (top < 0 && mask & (1 << 12) && (mask & 0b1111) === 0b1111) top = 3;\n\tSTRAIGHT[mask] = top;\n}\n\n/** Index of the highest set bit. Returns -1 for zero, which callers must avoid. */\nfunction high(mask: number): number {\n\treturn 31 - Math.clz32(mask);\n}\n\n/** Hand categories, weakest first, matching the packed value's high digit. */\nexport const CATEGORY = {\n\thighCard: 0,\n\tpair: 1,\n\ttwoPair: 2,\n\ttrips: 3,\n\tstraight: 4,\n\tflush: 5,\n\tfullHouse: 6,\n\tquads: 7,\n\tstraightFlush: 8,\n} as const;\n\nexport const CATEGORY_NAMES = [\n\t'high card',\n\t'pair',\n\t'two pair',\n\t'three of a kind',\n\t'straight',\n\t'flush',\n\t'full house',\n\t'four of a kind',\n\t'straight flush',\n] as const;\n\n/** Category of a packed value. */\nexport function categoryOf(value: number): number {\n\treturn (value / 1048576) | 0;\n}\n\n/**\n * Evaluate five to seven cards.\n *\n * Higher is stronger; equal values are exact chops. Behaviour is undefined for\n * fewer than five cards — `high(0)` would return -1 and the kicker loops would\n * read past the mask.\n *\n * @param s spade rank mask\n * @param h heart rank mask\n * @param d diamond rank mask\n * @param c club rank mask\n */\nexport function evaluate(s: number, h: number, d: number, c: number): number {\n\tconst all = s | h | d | c;\n\n\t// One suit with five or more cards serves both the straight flush and the\n\t// plain flush; there can only ever be one such suit in seven cards.\n\tlet flush = 0;\n\tif (POPCOUNT[s] >= 5) flush = s;\n\telse if (POPCOUNT[h] >= 5) flush = h;\n\telse if (POPCOUNT[d] >= 5) flush = d;\n\telse if (POPCOUNT[c] >= 5) flush = c;\n\n\tif (flush) {\n\t\tconst top = STRAIGHT[flush];\n\t\tif (top >= 0) return 8 * 1048576 + top * 65536;\n\t}\n\n\t// Exact rank multiplicities, by intersecting suits rather than counting.\n\tconst four = s & h & d & c;\n\tconst threePlus = (s & h & d) | (s & h & c) | (s & d & c) | (h & d & c);\n\tconst twoPlus = (s & h) | (s & d) | (s & c) | (h & d) | (h & c) | (d & c);\n\tconst trips = threePlus & ~four;\n\tconst pairs = twoPlus & ~threePlus;\n\n\tif (four) {\n\t\tconst quad = high(four);\n\t\tconst kicker = high(all & ~(1 << quad));\n\t\treturn 7 * 1048576 + quad * 65536 + kicker * 4096;\n\t}\n\n\tif (trips) {\n\t\tconst top = high(trips);\n\t\tconst otherTrips = trips & ~(1 << top);\n\t\tconst pair = otherTrips ? high(otherTrips) : pairs ? high(pairs) : -1;\n\t\tif (pair >= 0) return 6 * 1048576 + top * 65536 + pair * 4096;\n\t}\n\n\tif (flush) {\n\t\tlet mask = flush;\n\t\tlet value = 5 * 1048576;\n\t\tlet shift = 65536;\n\t\tfor (let i = 0; i < 5; i++) {\n\t\t\tconst rank = high(mask);\n\t\t\tvalue += rank * shift;\n\t\t\tmask &= ~(1 << rank);\n\t\t\tshift >>= 4;\n\t\t}\n\t\treturn value;\n\t}\n\n\t{\n\t\tconst top = STRAIGHT[all];\n\t\tif (top >= 0) return 4 * 1048576 + top * 65536;\n\t}\n\n\tif (trips) {\n\t\tconst top = high(trips);\n\t\tlet rest = all & ~(1 << top);\n\t\tconst k1 = high(rest);\n\t\trest &= ~(1 << k1);\n\t\tconst k2 = high(rest);\n\t\treturn 3 * 1048576 + top * 65536 + k1 * 4096 + k2 * 256;\n\t}\n\n\tif (pairs && pairs & (pairs - 1)) {\n\t\tconst p1 = high(pairs);\n\t\tconst p2 = high(pairs & ~(1 << p1));\n\t\tconst kicker = high(all & ~(1 << p1) & ~(1 << p2));\n\t\treturn 2 * 1048576 + p1 * 65536 + p2 * 4096 + kicker * 256;\n\t}\n\n\tif (pairs) {\n\t\tconst pair = high(pairs);\n\t\tlet rest = all & ~(1 << pair);\n\t\tconst k1 = high(rest);\n\t\trest &= ~(1 << k1);\n\t\tconst k2 = high(rest);\n\t\trest &= ~(1 << k2);\n\t\tconst k3 = high(rest);\n\t\treturn 1 * 1048576 + pair * 65536 + k1 * 4096 + k2 * 256 + k3 * 16;\n\t}\n\n\t{\n\t\tlet mask = all;\n\t\tlet value = 0;\n\t\tlet shift = 65536;\n\t\tfor (let i = 0; i < 5; i++) {\n\t\t\tconst rank = high(mask);\n\t\t\tvalue += rank * shift;\n\t\t\tmask &= ~(1 << rank);\n\t\t\tshift >>= 4;\n\t\t}\n\t\treturn value;\n\t}\n}\n\n/**\n * Evaluate a list of cards, for tests and one-off calls.\n *\n * The solver never uses this — it keeps lanes around and ORs them — but it\n * makes the evaluator usable without knowing the lane encoding.\n *\n * @param cards five to seven card indices\n */\nexport function evaluateCards(cards: ArrayLike<number>): number {\n\tlet s = 0;\n\tlet h = 0;\n\tlet d = 0;\n\tlet c = 0;\n\tfor (let i = 0; i < cards.length; i++) {\n\t\tconst card = cards[i];\n\t\tconst bit = 1 << (card >> 2);\n\t\tswitch (card & 3) {\n\t\t\tcase 0:\n\t\t\t\ts |= bit;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\th |= bit;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\td |= bit;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tc |= bit;\n\t\t}\n\t}\n\treturn evaluate(s, h, d, c);\n}\n","/**\n * Terminal-node value kernels.\n *\n * Purpose: the one place showdowns and folds become per-hand counterfactual\n * values, with exact card removal.\n *\n * Card removal is what makes this hard: two players cannot hold the same card,\n * so summing an opponent's range naively over-counts. Inclusion-exclusion over\n * the subsets of a hand's own cards fixes it exactly. With two hole cards there\n * are three subsets — each card alone, and the pair — so\n *\n * blocked(hand) = S[a] + S[b] - S[{a,b}]\n *\n * where S[T] is the reach summed over hands containing every card of T. The\n * two-card term is indexed at `52 + combo`, because a combination IS its own\n * two-card subset.\n *\n * Showdown is two passes over strength-ordered hands: ascending accumulates\n * what each hand beats, descending what it loses to. Ties need no special case\n * — a hand's own tie group is committed only after the group is queried, so\n * equal-strength hands and the hand itself fall out of both sums.\n */\n\nimport { COMBO_CARDS, COMBO_LANES, COMBOS, DECK, suitLanes } from './cards.ts';\nimport { evaluate } from './eval7.ts';\nimport type { Runouts } from './runouts.ts';\n\n/** Single-card sums occupy 0..51; the pair sum for combo c sits at 52 + c. */\nconst SUBSET_SPACE = DECK + COMBOS;\n\n/** Strength ordering, for one final board, of the combinations that matter. */\nexport interface ShowdownTable {\n\t/** Final-round boards this covers. */\n\treadonly boards: number;\n\t/** Entries reserved per board: the size of the two ranges' union. */\n\treadonly stride: number;\n\t/** `boards * stride`: live combinations, ascending by strength. */\n\treadonly order: Uint16Array;\n\t/** Live combinations per board. */\n\treadonly liveCount: Uint16Array;\n\t/** `boards * (COMBOS + 1)`: tie-group boundaries into `order`. */\n\treadonly groupStart: Uint16Array;\n\t/** Tie groups per board. */\n\treadonly groupCount: Uint16Array;\n\treadonly bytes: number;\n}\n\n/** Reusable buffers, so the hot loop never allocates. */\nexport interface TerminalScratch {\n\treadonly weaker: Float64Array;\n\treadonly stronger: Float64Array;\n\treadonly all: Float64Array;\n\treadonly win: Float64Array;\n}\n\n/** Allocate terminal-kernel scratch. */\nexport function makeTerminalScratch(): TerminalScratch {\n\treturn {\n\t\tweaker: new Float64Array(SUBSET_SPACE),\n\t\tstronger: new Float64Array(SUBSET_SPACE),\n\t\tall: new Float64Array(SUBSET_SPACE),\n\t\twin: new Float64Array(COMBOS),\n\t};\n}\n\n/**\n * Rank the combinations that matter, on every final board.\n *\n * Only hands in one of the two ranges are ranked. A board leaves about 1081 of\n * the 1326 combinations playable, but a real range holds a few hundred at most,\n * and the rest carry zero reach forever — ranking them is pure waste, and it\n * dominated the solve before this was restricted.\n *\n * @param runouts board completions\n * @param relevant combinations in either range; all of them if omitted\n */\nexport function buildShowdownTable(runouts: Runouts, relevant?: Uint8Array): ShowdownTable {\n\tconst round = runouts.rounds - 1;\n\tconst boards = runouts.counts[round];\n\tconst width = runouts.width[round];\n\tconst boardCards = runouts.cards[round];\n\n\tconst wanted: number[] = [];\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tif (!relevant || relevant[combo]) wanted.push(combo);\n\t}\n\tconst stride = Math.max(1, wanted.length);\n\n\tconst order = new Uint16Array(boards * stride);\n\tconst liveCount = new Uint16Array(boards);\n\tconst groupStart = new Uint16Array(boards * (stride + 1));\n\tconst groupCount = new Uint16Array(boards);\n\n\tconst lanes = new Int32Array(4);\n\tconst onBoard = new Uint8Array(DECK);\n\tconst strength = new Int32Array(COMBOS);\n\tconst live = new Uint16Array(COMBOS);\n\n\tfor (let board = 0; board < boards; board++) {\n\t\tconst base = board * width;\n\t\tonBoard.fill(0);\n\t\tfor (let i = 0; i < width; i++) onBoard[boardCards[base + i]] = 1;\n\t\tsuitLanes(boardCards.subarray(base, base + width), lanes);\n\t\tconst b0 = lanes[0];\n\t\tconst b1 = lanes[1];\n\t\tconst b2 = lanes[2];\n\t\tconst b3 = lanes[3];\n\n\t\tlet count = 0;\n\t\tfor (const combo of wanted) {\n\t\t\tif (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;\n\t\t\tconst lane = combo * 4;\n\t\t\tstrength[combo] = evaluate(\n\t\t\t\tCOMBO_LANES[lane] | b0,\n\t\t\t\tCOMBO_LANES[lane + 1] | b1,\n\t\t\t\tCOMBO_LANES[lane + 2] | b2,\n\t\t\t\tCOMBO_LANES[lane + 3] | b3,\n\t\t\t);\n\t\t\tlive[count++] = combo;\n\t\t}\n\n\t\tconst slice = live.subarray(0, count);\n\t\tslice.sort((x, y) => strength[x] - strength[y]);\n\t\torder.set(slice, board * stride);\n\t\tliveCount[board] = count;\n\n\t\tconst groupBase = board * (stride + 1);\n\t\tlet groups = 0;\n\t\tlet i = 0;\n\t\twhile (i < count) {\n\t\t\tgroupStart[groupBase + groups] = i;\n\t\t\tconst value = strength[slice[i]];\n\t\t\twhile (i < count && strength[slice[i]] === value) i++;\n\t\t\tgroups++;\n\t\t}\n\t\tgroupStart[groupBase + groups] = count;\n\t\tgroupCount[board] = groups;\n\t}\n\n\treturn {\n\t\tboards,\n\t\tstride,\n\t\torder,\n\t\tliveCount,\n\t\tgroupStart,\n\t\tgroupCount,\n\t\tbytes: order.byteLength + liveCount.byteLength + groupStart.byteLength + groupCount.byteLength,\n\t};\n}\n\n/**\n * Counterfactual values at a showdown, exact under card removal.\n *\n * Two passes over strength-ordered hands: ascending for the reach each hand\n * beats, descending for the reach that beats it. Each is a running total minus\n * what the hand's own cards block — the reach on its first card plus the reach\n * on its second. The pair term inclusion-exclusion would subtract is always\n * zero here: the only hand holding both cards is this one, and a hand's tie\n * group is added only after the group is queried. So no pair sums are kept.\n *\n * Most tie groups hold one hand, and those query and commit in one step.\n * Only the 52 single-card sums are dirtied, so they are cleared by a fill\n * rather than a pass over the hands.\n *\n * This order of operations is bit-for-bit the reference kernel's, which\n * matters: a value that is truly zero stays exactly zero, and regret matching,\n * being discontinuous at zero, would otherwise amplify rounding noise.\n *\n * @param reach opponent reach per combination\n * @param table strength ordering\n * @param board final-round board index\n * @param payoff chips the winner gains, i.e. each player's contribution\n * @param scratch reusable buffers\n * @param out destination of length COMBOS; every live entry is written\n */\nexport function showdownValues(\n\treach: Float64Array,\n\ttable: ShowdownTable,\n\tboard: number,\n\tpayoff: number,\n\tscratch: TerminalScratch,\n\tout: Float64Array,\n): void {\n\tconst { weaker, stronger, win } = scratch;\n\t// Reading an imported const crosses a module binding on every access, which\n\t// in a loop this tight costs more than the arithmetic. Hoist them.\n\tconst cards = COMBO_CARDS;\n\tconst order = table.order;\n\tconst starts = table.groupStart;\n\tconst orderBase = board * table.stride;\n\tconst groupBase = board * (table.stride + 1);\n\tconst groups = table.groupCount[board];\n\tif (table.liveCount[board] === 0) return;\n\n\tlet running = 0;\n\tfor (let g = 0; g < groups; g++) {\n\t\tconst from = starts[groupBase + g];\n\t\tconst to = starts[groupBase + g + 1];\n\t\tif (to - from === 1) {\n\t\t\tconst combo = order[orderBase + from];\n\t\t\tconst a = cards[combo * 2];\n\t\t\tconst b = cards[combo * 2 + 1];\n\t\t\twin[combo] = running - (weaker[a] + weaker[b]);\n\t\t\tconst value = reach[combo];\n\t\t\tif (value !== 0) {\n\t\t\t\trunning += value;\n\t\t\t\tweaker[a] += value;\n\t\t\t\tweaker[b] += value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\twin[combo] = running - (weaker[cards[combo * 2]] + weaker[cards[combo * 2 + 1]]);\n\t\t}\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\tconst value = reach[combo];\n\t\t\tif (value === 0) continue;\n\t\t\trunning += value;\n\t\t\tweaker[cards[combo * 2]] += value;\n\t\t\tweaker[cards[combo * 2 + 1]] += value;\n\t\t}\n\t}\n\n\trunning = 0;\n\tfor (let g = groups - 1; g >= 0; g--) {\n\t\tconst from = starts[groupBase + g];\n\t\tconst to = starts[groupBase + g + 1];\n\t\tif (to - from === 1) {\n\t\t\tconst combo = order[orderBase + from];\n\t\t\tconst a = cards[combo * 2];\n\t\t\tconst b = cards[combo * 2 + 1];\n\t\t\tout[combo] = payoff * (win[combo] - (running - (stronger[a] + stronger[b])));\n\t\t\tconst value = reach[combo];\n\t\t\tif (value !== 0) {\n\t\t\t\trunning += value;\n\t\t\t\tstronger[a] += value;\n\t\t\t\tstronger[b] += value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\tout[combo] =\n\t\t\t\tpayoff * (win[combo] - (running - (stronger[cards[combo * 2]] + stronger[cards[combo * 2 + 1]])));\n\t\t}\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\tconst value = reach[combo];\n\t\t\tif (value === 0) continue;\n\t\t\trunning += value;\n\t\t\tstronger[cards[combo * 2]] += value;\n\t\t\tstronger[cards[combo * 2 + 1]] += value;\n\t\t}\n\t}\n\n\tweaker.fill(0, 0, DECK);\n\tstronger.fill(0, 0, DECK);\n}\n\n/**\n * The showdown kernel as it was before `showdownValues` dropped the pair sums\n * and the clearing pass, kept as the reference it is tested against — to the\n * last bit.\n *\n * @param reach opponent reach per combination\n * @param table strength ordering\n * @param board final-round board index\n * @param payoff chips the winner gains, i.e. each player's contribution\n * @param scratch reusable buffers\n * @param out destination of length COMBOS; fully overwritten\n */\nexport function showdownValuesReference(\n\treach: Float64Array,\n\ttable: ShowdownTable,\n\tboard: number,\n\tpayoff: number,\n\tscratch: TerminalScratch,\n\tout: Float64Array,\n): void {\n\tconst { weaker, stronger, win } = scratch;\n\t// Reading an imported const crosses a module binding on every access, which\n\t// in a loop this tight costs more than the arithmetic. Hoist them.\n\tconst cards = COMBO_CARDS;\n\tconst deck = DECK;\n\tconst order = table.order;\n\tconst starts = table.groupStart;\n\tconst orderBase = board * table.stride;\n\tconst groupBase = board * (table.stride + 1);\n\tconst groups = table.groupCount[board];\n\tconst live = table.liveCount[board];\n\n\t// Only the live entries are ever read, so clearing all 1326 would be waste\n\t// proportional to how narrow the ranges are.\n\tfor (let i = 0; i < live; i++) out[order[orderBase + i]] = 0;\n\tif (live === 0) return;\n\n\tlet running = 0;\n\tfor (let g = 0; g < groups; g++) {\n\t\tconst from = starts[groupBase + g];\n\t\tconst to = starts[groupBase + g + 1];\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\tconst a = cards[combo * 2];\n\t\t\tconst b = cards[combo * 2 + 1];\n\t\t\twin[combo] = running - (weaker[a] + weaker[b] - weaker[deck + combo]);\n\t\t}\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\tconst value = reach[combo];\n\t\t\tif (value === 0) continue;\n\t\t\trunning += value;\n\t\t\tweaker[cards[combo * 2]] += value;\n\t\t\tweaker[cards[combo * 2 + 1]] += value;\n\t\t\tweaker[deck + combo] += value;\n\t\t}\n\t}\n\n\trunning = 0;\n\tfor (let g = groups - 1; g >= 0; g--) {\n\t\tconst from = starts[groupBase + g];\n\t\tconst to = starts[groupBase + g + 1];\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\tconst a = cards[combo * 2];\n\t\t\tconst b = cards[combo * 2 + 1];\n\t\t\tout[combo] = payoff * (win[combo] - (running - (stronger[a] + stronger[b] - stronger[deck + combo])));\n\t\t}\n\t\tfor (let i = from; i < to; i++) {\n\t\t\tconst combo = order[orderBase + i];\n\t\t\tconst value = reach[combo];\n\t\t\tif (value === 0) continue;\n\t\t\trunning += value;\n\t\t\tstronger[cards[combo * 2]] += value;\n\t\t\tstronger[cards[combo * 2 + 1]] += value;\n\t\t\tstronger[deck + combo] += value;\n\t\t}\n\t}\n\n\t// Leave the accumulators as they were found, so the next call needs no\n\t// clearing pass of its own. Only hands with reach ever touched them, and\n\t// late in a solve most have none.\n\tfor (let i = 0; i < live; i++) {\n\t\tconst combo = order[orderBase + i];\n\t\tif (reach[combo] === 0) continue;\n\t\tweaker[cards[combo * 2]] = 0;\n\t\tweaker[cards[combo * 2 + 1]] = 0;\n\t\tweaker[deck + combo] = 0;\n\t\tstronger[cards[combo * 2]] = 0;\n\t\tstronger[cards[combo * 2 + 1]] = 0;\n\t\tstronger[deck + combo] = 0;\n\t}\n}\n\n/**\n * Counterfactual values at a fold, exact under card removal.\n *\n * @param reach opponent reach per combination\n * @param live combinations not blocked by the board\n * @param liveCount entries in `live`\n * @param payoff signed chips the traverser gains\n * @param scratch reusable buffers\n * @param out destination of length COMBOS; fully overwritten\n */\nexport function foldValues(\n\treach: Float64Array,\n\tlive: Uint16Array,\n\tliveCount: number,\n\tpayoff: number,\n\tscratch: TerminalScratch,\n\tout: Float64Array,\n): void {\n\tconst sums = scratch.all;\n\tconst cards = COMBO_CARDS;\n\tconst deck = DECK;\n\n\tif (liveCount === 0) return;\n\n\tlet total = 0;\n\tfor (let i = 0; i < liveCount; i++) {\n\t\tconst combo = live[i];\n\t\tconst value = reach[combo];\n\t\tif (value === 0) continue;\n\t\ttotal += value;\n\t\tsums[cards[combo * 2]] += value;\n\t\tsums[cards[combo * 2 + 1]] += value;\n\t\tsums[deck + combo] += value;\n\t}\n\t// A hand's pair entry is read by that hand alone, so it is cleared as it\n\t// is read; the 52 single-card entries are cleared together after.\n\tfor (let i = 0; i < liveCount; i++) {\n\t\tconst combo = live[i];\n\t\tconst pair = deck + combo;\n\t\tout[combo] = payoff * (total - (sums[cards[combo * 2]] + sums[cards[combo * 2 + 1]] - sums[pair]));\n\t\tsums[pair] = 0;\n\t}\n\tsums.fill(0, 0, deck);\n}\n","/**\n * Values against single opposing hands, many at once.\n *\n * Purpose: answer \"what is each of my hands worth against that one hand of\n * theirs, from here on\" for a whole list of their hands in one walk of the\n * tree. `valuesAt` with a one-hot opponent reach gives the same numbers, one\n * opposing hand per walk; this shares everything that does not depend on the\n * opposing hand:\n *\n * - the tree walk itself, and every average-strategy lookup on the way;\n * - the traverser's reach, which never depends on the opposing hand;\n * - terminals, where a single opposing hand needs no card-removal kernel:\n * at a fold every hand not sharing a card wins or loses the same amount,\n * and at a showdown it is a comparison of two strengths.\n *\n * An opposing hand drops out of the walk as soon as its own strategy stops\n * reaching a line, or a dealt card hits it, so lines a hand never takes cost\n * nothing for it.\n *\n * Reads the average strategy only. Results match `valuesAt` with a one-hot\n * reach to floating-point accuracy.\n */\n\nimport { COMBO_CARDS, COMBOS } from './cards.ts';\nimport type { Context } from './cfr.ts';\nimport { averageStrategy } from './cfr.ts';\nimport { NodeKind } from './tree.ts';\n\n/** Opposing hands per walk; more share the walk better but need more memory. */\nconst CHUNK = 64;\n\ninterface PairBuffers {\n\treadonly value: Float64Array[];\n\treadonly cols: Int32Array[];\n\treadonly colReach: Float64Array[];\n\treadonly live: Uint16Array[];\n\t/** Opposing hands relabelled onto a stored board, per depth. */\n\treadonly hands: Uint16Array[];\n\treadonly strategy: Float64Array[];\n\treadonly rank: Int32Array;\n}\n\nfunction treeDepth(ctx: Context): number {\n\tconst { tree } = ctx;\n\tconst depth = new Int32Array(tree.nodeCount).fill(-1);\n\tdepth[0] = 1;\n\tlet max = 1;\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tconst here = depth[node];\n\t\tif (here < 0) continue;\n\t\tif (here > max) max = here;\n\t\tfor (let e = 0; e < tree.numEdges[node]; e++) {\n\t\t\tconst child = tree.edgeChild[tree.firstEdge[node] + e];\n\t\t\tif (depth[child] < here + 1) depth[child] = here + 1;\n\t\t}\n\t}\n\treturn max + 2;\n}\n\nfunction makeBuffers(ctx: Context, width: number): PairBuffers {\n\tconst depth = treeDepth(ctx);\n\tconst make = <T>(factory: () => T): T[] => Array.from({ length: depth }, factory);\n\tconst actions = ctx.layout.maxActions;\n\treturn {\n\t\tvalue: make(() => new Float64Array(width * COMBOS)),\n\t\tcols: make(() => new Int32Array(width)),\n\t\tcolReach: make(() => new Float64Array(width)),\n\t\tlive: make(() => new Uint16Array(COMBOS)),\n\t\thands: make(() => new Uint16Array(width)),\n\t\tstrategy: make(() => new Float64Array(actions * COMBOS)),\n\t\trank: new Int32Array(COMBOS),\n\t};\n}\n\n/**\n * Counterfactual values for `traverser` from `node` on `board`, against each\n * opposing hand alone.\n *\n * @param hands the opposing hands, one per result row\n * @param handReach each opposing hand's reach at `node`\n * @returns `hands.length * COMBOS` values; row `k` is what `valuesAt` returns\n * for an opponent reach holding only `hands[k]` at `handReach[k]`\n */\nexport function pairValues(\n\tctx: Context,\n\tnode: number,\n\tboard: number,\n\ttraverser: 0 | 1,\n\thands: Uint16Array,\n\thandReach: Float64Array,\n\tlive: Uint16Array,\n\tliveCount: number,\n): Float64Array {\n\tconst result = new Float64Array(hands.length * COMBOS);\n\tif (hands.length === 0) return result;\n\tconst width = Math.min(CHUNK, hands.length);\n\tconst buffers = makeBuffers(ctx, width);\n\t// Only the traverser's own hands get a value, so only they are carried.\n\tconst mine = new Uint16Array(liveCount);\n\tlet mineCount = 0;\n\tfor (let i = 0; i < liveCount; i++) if (ctx.players[traverser].slot[live[i]] >= 0) mine[mineCount++] = live[i];\n\tfor (let start = 0; start < hands.length; start += width) {\n\t\tconst chunk = hands.subarray(start, Math.min(hands.length, start + width));\n\t\tconst colReach = buffers.colReach[0];\n\t\tconst cols = buffers.cols[0];\n\t\tlet count = 0;\n\t\tfor (let k = 0; k < chunk.length; k++) {\n\t\t\tcolReach[k] = handReach[start + k];\n\t\t\tif (colReach[k] !== 0) cols[count++] = k;\n\t\t}\n\t\tconst value = walk(ctx, buffers, traverser, chunk, node, board, colReach, cols, count, mine, mineCount, 0);\n\t\tfor (let c = 0; c < count; c++) {\n\t\t\tconst k = cols[c];\n\t\t\tconst row = value.subarray(k * COMBOS, (k + 1) * COMBOS);\n\t\t\tfor (let i = 0; i < mineCount; i++) result[(start + k) * COMBOS + mine[i]] = row[mine[i]];\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction walk(\n\tctx: Context,\n\tbuffers: PairBuffers,\n\ttraverser: 0 | 1,\n\thands: Uint16Array,\n\tnode: number,\n\tboard: number,\n\tcolReach: Float64Array,\n\tcols: Int32Array,\n\tcolCount: number,\n\tlive: Uint16Array,\n\tliveCount: number,\n\tdepth: number,\n): Float64Array {\n\tconst { tree, runouts } = ctx;\n\tconst out = buffers.value[depth];\n\tconst kind = tree.kind[node];\n\tconst cards = COMBO_CARDS;\n\n\tfor (let c = 0; c < colCount; c++) {\n\t\tconst row = cols[c] * COMBOS;\n\t\tfor (let i = 0; i < liveCount; i++) out[row + live[i]] = 0;\n\t}\n\tif (colCount === 0) return out;\n\n\tif (kind === NodeKind.TerminalFold) {\n\t\tconst signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];\n\t\tconst weight = (signed * ctx.runoutWeight[tree.round[node]]) / ctx.chipScale;\n\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\tconst k = cols[c];\n\t\t\tconst a = cards[hands[k] * 2];\n\t\t\tconst b = cards[hands[k] * 2 + 1];\n\t\t\tconst v = weight * colReach[k];\n\t\t\tconst row = k * COMBOS;\n\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\tconst combo = live[i];\n\t\t\t\tconst x = cards[combo * 2];\n\t\t\t\tconst y = cards[combo * 2 + 1];\n\t\t\t\tif (x !== a && x !== b && y !== a && y !== b) out[row + combo] = v;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.TerminalShowdown) {\n\t\tconst weight = (tree.payoff[node] * ctx.runoutWeight[tree.round[node]]) / ctx.chipScale;\n\t\t// Strength on this final board as a tie-group index.\n\t\tconst table = ctx.showdown;\n\t\tconst rank = buffers.rank;\n\t\tconst orderBase = board * table.stride;\n\t\tconst groupBase = board * (table.stride + 1);\n\t\tfor (let g = 0; g < table.groupCount[board]; g++) {\n\t\t\tfor (let i = table.groupStart[groupBase + g]; i < table.groupStart[groupBase + g + 1]; i++) {\n\t\t\t\trank[table.order[orderBase + i]] = g;\n\t\t\t}\n\t\t}\n\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\tconst k = cols[c];\n\t\t\tconst theirs = hands[k];\n\t\t\tconst a = cards[theirs * 2];\n\t\t\tconst b = cards[theirs * 2 + 1];\n\t\t\tconst strength = rank[theirs];\n\t\t\tconst v = weight * colReach[k];\n\t\t\tconst row = k * COMBOS;\n\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\tconst combo = live[i];\n\t\t\t\tconst x = cards[combo * 2];\n\t\t\t\tconst y = cards[combo * 2 + 1];\n\t\t\t\tif (x === a || x === b || y === a || y === b) continue;\n\t\t\t\tconst mine = rank[combo];\n\t\t\t\tif (mine > strength) out[row + combo] = v;\n\t\t\t\telse if (mine < strength) out[row + combo] = -v;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.Chance) {\n\t\tconst nextRound = tree.round[node] + 1;\n\t\tconst child = tree.edgeChild[tree.firstEdge[node]];\n\t\tconst width = runouts.width[nextRound];\n\t\tconst dealtCards = runouts.cards[nextRound];\n\t\tconst orbitStart = runouts.orbitStart[nextRound];\n\t\tconst childLive = buffers.live[depth];\n\t\tconst childCols = buffers.cols[depth + 1];\n\t\tconst mappedHands = buffers.hands[depth];\n\n\t\tfor (let childBoard = runouts.childStart[nextRound][board]; childBoard < runouts.childStart[nextRound][board + 1]; childBoard++) {\n\t\t\t// Every deal this board stands for, the stored one first. The\n\t\t\t// opposing hands are an arbitrary list, not a symmetric range, so a\n\t\t\t// mirrored deal is walked with every hand relabelled onto the\n\t\t\t// stored board rather than assumed equal to it.\n\t\t\tfor (let m = orbitStart[childBoard]; m < orbitStart[childBoard + 1]; m++) {\n\t\t\t\tconst dealt = m === orbitStart[childBoard] ? dealtCards[childBoard * width + width - 1] : runouts.orbitCard[nextRound][m];\n\t\t\t\tconst map = runouts.maps.combo[runouts.orbitMap[nextRound][m]];\n\n\t\t\t\tlet childCount = 0;\n\t\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\t\tconst combo = live[i];\n\t\t\t\t\tif (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;\n\t\t\t\t\tchildLive[childCount++] = map[combo];\n\t\t\t\t}\n\t\t\t\tlet childColCount = 0;\n\t\t\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\t\t\tconst k = cols[c];\n\t\t\t\t\tif (cards[hands[k] * 2] !== dealt && cards[hands[k] * 2 + 1] !== dealt) childCols[childColCount++] = k;\n\t\t\t\t}\n\t\t\t\tif (childColCount === 0) continue;\n\t\t\t\tfor (let k = 0; k < hands.length; k++) mappedHands[k] = map[hands[k]];\n\n\t\t\t\tconst value = walk(\n\t\t\t\t\tctx, buffers, traverser, mappedHands.subarray(0, hands.length), child, childBoard, colReach,\n\t\t\t\t\tchildCols, childColCount, childLive, childCount, depth + 1,\n\t\t\t\t);\n\t\t\t\tfor (let c = 0; c < childColCount; c++) {\n\t\t\t\t\tconst row = childCols[c] * COMBOS;\n\t\t\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\t\t\tconst combo = live[i];\n\t\t\t\t\t\tif (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;\n\t\t\t\t\t\tout[row + combo] += value[row + map[combo]];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t// --- decision ---\n\tconst actions = tree.numEdges[node];\n\tconst edgeBase = tree.firstEdge[node];\n\tconst owner = tree.player[node] as 0 | 1;\n\tconst index = ctx.players[owner];\n\tconst stride = index.count;\n\tconst slotBase = ctx.layout.offset[node] + board * actions * stride;\n\tconst lists = ctx.active;\n\tconst listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;\n\tconst active = lists.list;\n\tconst activeFrom = lists.start[listSlot];\n\tconst activeCount = lists.count[listSlot];\n\tconst strategy = buffers.strategy[depth];\n\taverageStrategy(ctx.strategySum, slotBase, actions, stride, active, lists.slot, activeFrom, activeCount, strategy, ctx.regret);\n\n\t// The traverser's values are counterfactual: its own reach never enters.\n\tif (owner === traverser) {\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst offset = a * COMBOS;\n\t\t\tconst value = walk(\n\t\t\t\tctx, buffers, traverser, hands, tree.edgeChild[edgeBase + a], board, colReach,\n\t\t\t\tcols, colCount, live, liveCount, depth + 1,\n\t\t\t);\n\t\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\t\tconst row = cols[c] * COMBOS;\n\t\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\t\tconst combo = active[activeFrom + i];\n\t\t\t\t\tout[row + combo] += strategy[a * stride + lists.slot[activeFrom + i]] * value[row + combo];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t// The opposing hands act: each column follows its own hand's strategy.\n\tconst childReach = buffers.colReach[depth + 1];\n\tconst childCols = buffers.cols[depth + 1];\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * COMBOS;\n\t\tlet childCount = 0;\n\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\tconst k = cols[c];\n\t\t\t// Strategies are laid out by storage slot.\n\t\t\tconst r = colReach[k] * strategy[a * stride + index.slot[hands[k]]];\n\t\t\tchildReach[k] = r;\n\t\t\tif (r !== 0) childCols[childCount++] = k;\n\t\t}\n\t\tif (childCount === 0) continue;\n\t\tconst value = walk(\n\t\t\tctx, buffers, traverser, hands, tree.edgeChild[edgeBase + a], board, childReach,\n\t\t\tchildCols, childCount, live, liveCount, depth + 1,\n\t\t);\n\t\tfor (let c = 0; c < childCount; c++) {\n\t\t\tconst row = childCols[c] * COMBOS;\n\t\t\tfor (let i = 0; i < liveCount; i++) out[row + live[i]] += value[row + live[i]];\n\t\t}\n\t}\n\treturn out;\n}\n","// Generated by scripts/build-wasm.ts from assembly/kernels.ts. Do not edit.\n/** The SIMD kernels, 1327 bytes of WebAssembly. */\nexport const KERNELS_WASM = 'AGFzbQEAAAABEwJgBX9/f39/AGAHf39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBycDC3JlZ3JldE1hdGNoAAAMYXZlcmFnZU1hdGNoAAEGbWVtb3J5AgAK0AkC8AMDB38BfAJ7IARBfnEhCANAIAQgBUoEQCACIAVBA3RqRAAAAAAAAAAAOQMAIAVBAWohBQwBCwsDQCADIAZKBEAgBCAGbEEDdCEJQQAhBQNAIAUgCEgEQCAFQQN0IgogCWoiCyAAav0ABAD9DAAAAAAAAAAAAAAAAAAAAAD99QEhDSABIAtqIA39CwQAIAIgCmoiCiAK/QAEACAN/fAB/QsEACAFQQJqIQUMAQsLA0AgBCAFSgRAIAVBA3QiCiAAIAlqaisDACIMRAAAAAAAAAAAIAxEAAAAAAAAAABkGyEMIAEgCWogCmogDDkDACACIApqIgogCisDACAMoDkDACAFQQFqIQUMAQsLIAZBAWohBgwBCwtEAAAAAAAA8D8gA7ej/RQhDgNAIAMgB0oEQCAEIAdsQQN0IQVBACEAA0AgACAISARAIABBA3QiBiABIAVqaiIJIAn9AAQAIAIgBmr9AAQAIg398wEgDiAN/QwAAAAAAAAAAAAAAAAAAAAA/Ur9Uv0LBAAgAEECaiEADAELCwNAIAA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yAKQQFqIQoMAQsLCw==';\n","/**\n * The WebAssembly SIMD kernels, loaded.\n *\n * Purpose: give one thread its own instance of the kernels in\n * `assembly/kernels.ts`, or say there is none, so the caller falls back to\n * JavaScript.\n *\n * Each thread gets a private memory. The solver's accumulators stay where\n * they are — ordinary or shared typed arrays — and a block is copied in\n * before a kernel runs on it, which is a native memcpy (converting from f32\n * or i16 storage on the way) and costs far less than the kernel saves. That\n * keeps worker threads exactly as they were: nothing about sharing changes.\n */\n\nimport { KERNELS_WASM } from './wasm/kernels.ts';\n\n/** One thread's kernels and the memory they work in. */\nexport interface Kernels {\n\t/**\n\t * Regret matching over one block, `actions` rows of `count` slots. The\n\t * block must already be in `input`; the strategy lands in `out`.\n\t */\n\tregretMatch(out: Float64Array, actions: number, count: number): void;\n\t/**\n\t * The average strategy over one block: its strategy sums in `input`, and\n\t * its regrets in `second` when `hasRegret`, for hands whose sums are zero.\n\t */\n\taverageMatch(out: Float64Array, actions: number, count: number, hasRegret: boolean): void;\n\t/** Where a block is copied before a kernel runs on it. */\n\treadonly input: Float64Array;\n\t/** A second block, for kernels that read two. */\n\treadonly second: Float64Array;\n\t/**\n\t * A strategy buffer in kernel memory, `actions * count` doubles: what\n\t * `regretMatch` writes into. One per traversal depth.\n\t */\n\tstrategy(depth: number): Float64Array;\n}\n\n/** The parts of the WebAssembly API used here, typed locally: the project builds without DOM typings. */\ninterface WasmApi {\n\tvalidate(bytes: Uint8Array): boolean;\n\tModule: new (bytes: Uint8Array) => object;\n\tInstance: new (module: object, imports: object) => { exports: Record<string, unknown> };\n\tMemory: new (descriptor: { initial: number }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\n\nlet module: object | null | undefined;\n\n/** The compiled module, or null where WebAssembly SIMD is unavailable. */\nfunction compiled(): object | null {\n\tif (module !== undefined) return module;\n\tmodule = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst bytes = Uint8Array.from(atob(KERNELS_WASM), (c) => c.charCodeAt(0));\n\t\t// Validation fails exactly where SIMD is unsupported.\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tmodule = new wasm.Module(bytes);\n\t} catch {\n\t\tmodule = null;\n\t}\n\treturn module;\n}\n\n/**\n * Instantiate the kernels for one thread.\n *\n * @param depths traversal depths, each needing its own strategy buffer\n * @param width doubles per buffer: actions times the widest range\n * @returns null where WebAssembly SIMD is unavailable\n */\nexport function loadKernels(depths: number, width: number): Kernels | null {\n\tconst compiledModule = compiled();\n\tif (!compiledModule || !wasm) return null;\n\t// Layout, in doubles: two inputs, totals (twice over), then one strategy\n\t// buffer per depth.\n\tconst second = width;\n\tconst totals = 2 * width;\n\tconst first = 4 * width;\n\tconst bytes = (first + depths * width) * 8;\n\tconst memory = new wasm.Memory({ initial: Math.ceil(bytes / 65536) + 1 });\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory } });\n\tconst regretMatch = instance.exports.regretMatch as (\n\t\tregret: number,\n\t\tout: number,\n\t\ttotal: number,\n\t\tactions: number,\n\t\tcount: number,\n\t) => void;\n\tconst averageMatch = instance.exports.averageMatch as (\n\t\tsums: number,\n\t\tregret: number,\n\t\tout: number,\n\t\ttotal: number,\n\t\tactions: number,\n\t\tcount: number,\n\t\thasRegret: number,\n\t) => void;\n\tconst heap = new Float64Array(memory.buffer);\n\tconst input = heap.subarray(0, width);\n\tconst secondInput = heap.subarray(second, second + width);\n\tconst buffers = Array.from({ length: depths }, (_, depth) =>\n\t\theap.subarray(first + depth * width, first + (depth + 1) * width),\n\t);\n\treturn {\n\t\tinput,\n\t\tsecond: secondInput,\n\t\tstrategy: (depth) => buffers[depth],\n\t\tregretMatch(out, actions, count) {\n\t\t\tregretMatch(0, out.byteOffset, totals * 8, actions, count);\n\t\t},\n\t\taverageMatch(out, actions, count, hasRegret) {\n\t\t\taverageMatch(0, second * 8, out.byteOffset, totals * 8, actions, count, hasRegret ? 1 : 0);\n\t\t},\n\t};\n}\n\n/** Whether this platform runs the WebAssembly SIMD kernels; false means JavaScript throughout. */\nexport function simdAvailable(): boolean {\n\treturn compiled() !== null;\n}\n","/**\n * Vector CFR+ over a fixed board.\n *\n * Purpose: the one place equilibrium computation happens.\n *\n * Every traversal carries vectors over all 1326 combinations, so one walk of\n * the tree updates every hand at once. Returned values are counterfactual — the\n * opponent's reach is already folded in — which is exactly what the regret\n * update expects, so nothing is rescaled anywhere.\n *\n * Values are UNNORMALISED: summed over runouts rather than averaged. CFR is\n * invariant to a positive scale, and dividing once at the top by the total\n * weighted mass of legal matchups is both cheaper and harder to get wrong than\n * threading a probability through every node.\n *\n * Storage is sized by each player's own range, not by all 1326 combinations —\n * a decision node belongs to one player, and a typical range is a few hundred\n * hands, so this is the difference between fitting and not.\n */\n\nimport { COMBO_CARDS, COMBOS, DECK } from './cards.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { ShowdownTable, TerminalScratch } from './showdown.ts';\nimport { foldValues, makeTerminalScratch, showdownValues } from './showdown.ts';\nimport type { Tree } from './tree.ts';\nimport { pairValues } from './pairs.ts';\nimport type { Kernels } from './kernels.ts';\nimport { loadKernels } from './kernels.ts';\nimport { NodeKind } from './tree.ts';\n\n/** Which combinations a player holds, and where each sits in storage. */\nexport interface PlayerIndex {\n\t/** Combinations with any weight, ascending. */\n\treadonly combos: Uint16Array;\n\treadonly count: number;\n\t/** Combination to storage slot, or -1. */\n\treadonly slot: Int32Array;\n\t/** Starting reach: the range weights themselves. */\n\treadonly weights: Float64Array;\n}\n\n/** Build a player's index from their range weights. */\nexport function buildPlayerIndex(weights: Float64Array): PlayerIndex {\n\tconst combos: number[] = [];\n\tconst slot = new Int32Array(COMBOS).fill(-1);\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tif (weights[combo] > 0) {\n\t\t\tslot[combo] = combos.length;\n\t\t\tcombos.push(combo);\n\t\t}\n\t}\n\treturn { combos: Uint16Array.from(combos), count: combos.length, slot, weights };\n}\n\n/** Slot offsets for every decision node. */\nexport interface Layout {\n\treadonly offset: Int32Array;\n\t/**\n\t * First block of each decision node, else -1. A block is one node on one\n\t * board — `actions * combosOfItsOwner` slots, exactly what one visit\n\t * updates — and block `blockOffset[node] + board` is where 16-bit storage\n\t * keeps its scale.\n\t */\n\treadonly blockOffset: Int32Array;\n\treadonly blocks: number;\n\treadonly totalSlots: number;\n\treadonly maxActions: number;\n\treadonly bytes: number;\n}\n\n/**\n * Size storage. A node's block is `boards * actions * combosOfItsOwner`.\n * @param bytesPerElement 8 for float64, 4 for float32, 2 for 16-bit, which\n * also keeps one float64 scale per block for each accumulator\n */\nexport function buildLayout(\n\ttree: Tree,\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tbytesPerElement: number,\n): Layout {\n\tconst offset = new Int32Array(tree.nodeCount).fill(-1);\n\tconst blockOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tlet total = 0;\n\tlet blocks = 0;\n\tlet maxActions = 0;\n\n\tfor (let i = 0; i < tree.decisionNodes.length; i++) {\n\t\tconst node = tree.decisionNodes[i];\n\t\tconst actions = tree.numEdges[node];\n\t\tif (actions > maxActions) maxActions = actions;\n\t\toffset[node] = total;\n\t\tblockOffset[node] = blocks;\n\t\ttotal += runouts.counts[tree.round[node]] * actions * players[tree.player[node]].count;\n\t\tblocks += runouts.counts[tree.round[node]];\n\t}\n\tconst scales = bytesPerElement === 2 ? blocks * 8 * 2 : 0;\n\treturn { offset, blockOffset, blocks, totalSlots: total, maxActions, bytes: total * bytesPerElement * 2 + scales };\n}\n\n/** Accumulated regrets: float, or 16-bit integers scaled per block. */\nexport type RegretStore = Float64Array | Float32Array | Int16Array;\n/** Accumulated strategy sums: float, or 16-bit integers scaled per block. */\nexport type SumStore = Float64Array | Float32Array | Uint16Array;\n\n/** Largest magnitudes 16-bit storage encodes. */\nconst REGRET_STEPS = 32767;\nconst SUM_STEPS = 65535;\n\n/** Everything a traversal needs. */\nexport interface Context {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly showdown: ShowdownTable;\n\treadonly regret: RegretStore;\n\treadonly strategySum: SumStore;\n\t/**\n\t * Per-block scales when the accumulators are 16-bit, else null: a stored\n\t * integer `q` in block `b` means `q * scale[b]`. Only updates need them.\n\t * Everything that reads a strategy divides each hand's values by their own\n\t * total within one block, so the scale cancels and the integers are read\n\t * as they are.\n\t */\n\treadonly regretScale: Float64Array | null;\n\treadonly sumScale: Float64Array | null;\n\treadonly scratch: TerminalScratch;\n\treadonly chipScale: number;\n\t/** Which combinations each player can hold on each board. */\n\treadonly active: ActiveLists;\n\t/**\n\t * Board completions still to come after each round, with four cards already\n\t * removed for the two hands. A hand that ends early would otherwise be\n\t * counted once while one reaching showdown is counted once per runout.\n\t */\n\treadonly runoutWeight: Float64Array;\n\t/** Total weighted mass of legal matchups; divides raw values into chips. */\n\treadonly totalMass: number;\n\t/** Discounted CFR in place of CFR+; see `DCFR_ALPHA`. */\n\treadonly dcfr: boolean;\n\t/**\n\t * Runout range this traversal is responsible for, as [start, end), at\n\t * `shardRound`. Workers each take a slice; a single-threaded solve takes\n\t * the whole level. Runouts partition storage, so slices never collide.\n\t */\n\tshardStart: number;\n\tshardEnd: number;\n\t/** Round at which sharding applies; -1 to disable. */\n\tshardRound: number;\n\t/** Whether traverser nodes accumulate regret. False during a collect pass. */\n\tapplyUpdates: boolean;\n\t/** Captures the reach a worker will need, instead of expanding. */\n\tchanceCollect: ((node: number, reachMe: Float64Array, reachOpp: Float64Array) => void) | null;\n\t/** Values to substitute for chance nodes at the shard round, by entry index. */\n\tchanceOverride: Float64Array | null;\n\t/** Node index to entry index for shard-round chance nodes, else -1. */\n\tentryIndexOf: Int32Array | null;\n\t/**\n\t * How a stored board stands for the deals it represents. False: add its\n\t * values relabelled, which is exact when reach is symmetric under the\n\t * spot's symmetries — always so from the root, since the ranges are. True:\n\t * walk it once per represented deal with that deal's reach relabelled\n\t * onto it, exact for any reach, at the cost of the walks saved.\n\t */\n\texpandOrbits: boolean;\n\t/** Use the WebAssembly SIMD kernels where the platform has them. */\n\treadonly simd: boolean;\n}\n\n/**\n * Completions remaining after each round, both players' cards removed.\n * Constant across hands because the two hands are always disjoint.\n */\nexport function runoutWeights(runouts: Runouts): Float64Array {\n\tconst weights = new Float64Array(runouts.rounds).fill(1);\n\tfor (let round = 0; round < runouts.rounds; round++) {\n\t\tlet weight = 1;\n\t\tfor (let r = round + 1; r < runouts.rounds; r++) weight *= DECK - 4 - runouts.width[r - 1];\n\t\tweights[round] = weight;\n\t}\n\treturn weights;\n}\n\n/**\n * Weighted mass of hand pairs the two players can hold at once.\n *\n * Not a combination count: with weighted ranges it is\n * `sum over disjoint (h0, h1) of w0(h0) * w1(h1)`. Getting this wrong scales\n * every reported number silently.\n */\nexport function matchupMass(a: Float64Array, b: Float64Array): number {\n\t// Card-level sums turn the disjointness test into inclusion-exclusion.\n\tconst single = new Float64Array(DECK);\n\tconst pair = new Float64Array(COMBOS);\n\tlet totalB = 0;\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tconst w = b[combo];\n\t\tif (w === 0) continue;\n\t\ttotalB += w;\n\t\tsingle[COMBO_CARDS[combo * 2]] += w;\n\t\tsingle[COMBO_CARDS[combo * 2 + 1]] += w;\n\t\tpair[combo] += w;\n\t}\n\n\tlet mass = 0;\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tconst w = a[combo];\n\t\tif (w === 0) continue;\n\t\tconst clash = single[COMBO_CARDS[combo * 2]] + single[COMBO_CARDS[combo * 2 + 1]] - pair[combo];\n\t\tmass += w * (totalB - clash);\n\t}\n\treturn mass;\n}\n\n/**\n * Which combinations each player can hold on each board.\n *\n * This depends only on the board and the player, never on the node, so\n * rebuilding it at every one of the tens of thousands of node visits per\n * traversal was pure repetition.\n */\ninterface ActiveLists {\n\t/** Start of each list in `list`, indexed by `slotOf(round, board, player)`. */\n\treadonly start: Int32Array;\n\treadonly count: Uint16Array;\n\treadonly list: Uint16Array;\n\t/**\n\t * Each entry's storage slot in its player's index, beside `list`, so the\n\t * hot loops read it in sequence instead of looking it up per combination.\n\t */\n\treadonly slot: Uint16Array;\n\t/** First list index of each round. */\n\treadonly roundBase: Int32Array;\n\t/**\n\t * Hands that mirror each other on a board with symmetry left, whose\n\t * accumulators are kept equal, indexed by the same slot as `start`:\n\t * `ties[tieStart[slot]..tieStart[slot + 1]]` is a run of classes, each its\n\t * size then that many storage slots. Empty almost everywhere.\n\t */\n\treadonly tieStart: Int32Array;\n\treadonly ties: Int32Array;\n}\n\nfunction buildActiveLists(\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n): ActiveLists {\n\tconst roundBase = new Int32Array(runouts.rounds + 1);\n\tfor (let round = 0; round < runouts.rounds; round++) {\n\t\troundBase[round + 1] = roundBase[round] + runouts.counts[round];\n\t}\n\tconst slots = roundBase[runouts.rounds] * 2;\n\n\tconst start = new Int32Array(slots);\n\tconst count = new Uint16Array(slots);\n\tconst entries: number[] = [];\n\tconst entrySlots: number[] = [];\n\tconst onBoard = new Uint8Array(DECK);\n\n\tfor (let round = 0; round < runouts.rounds; round++) {\n\t\tconst width = runouts.width[round];\n\t\tconst cards = runouts.cards[round];\n\t\tfor (let board = 0; board < runouts.counts[round]; board++) {\n\t\t\tonBoard.fill(0);\n\t\t\tfor (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst index = players[player];\n\t\t\t\tconst slot = (roundBase[round] + board) * 2 + player;\n\t\t\t\tstart[slot] = entries.length;\n\t\t\t\tfor (let i = 0; i < index.count; i++) {\n\t\t\t\t\tconst combo = index.combos[i];\n\t\t\t\t\tif (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;\n\t\t\t\t\tentries.push(combo);\n\t\t\t\t\tentrySlots.push(i);\n\t\t\t\t}\n\t\t\t\tcount[slot] = entries.length - start[slot];\n\t\t\t}\n\t\t}\n\t}\n\t// Tie classes. A board's stabiliser fixes it, so it permutes the hands\n\t// live on it; a player's range is unchanged by it, so the image of one of\n\t// their hands is theirs too.\n\tconst tieStart = new Int32Array(slots + 1);\n\tconst ties: number[] = [];\n\tfor (let round = 0; round < runouts.rounds; round++) {\n\t\tconst stabStart = runouts.stabiliserStart[round];\n\t\tconst stabMap = runouts.stabiliserMap[round];\n\t\tfor (let board = 0; board < runouts.counts[round]; board++) {\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst slot = (roundBase[round] + board) * 2 + player;\n\t\t\t\ttieStart[slot] = ties.length;\n\t\t\t\tif (stabStart[board + 1] - stabStart[board] < 2) continue;\n\t\t\t\tconst index = players[player];\n\t\t\t\tconst seen = new Uint8Array(index.count);\n\t\t\t\tfor (let e = start[slot]; e < start[slot] + count[slot]; e++) {\n\t\t\t\t\tconst first = entrySlots[e];\n\t\t\t\t\tif (seen[first]) continue;\n\t\t\t\t\tconst members: number[] = [];\n\t\t\t\t\tfor (let k = stabStart[board]; k < stabStart[board + 1]; k++) {\n\t\t\t\t\t\tconst image = index.slot[runouts.maps.combo[stabMap[k]][entries[e]]];\n\t\t\t\t\t\tif (image < 0 || seen[image]) continue;\n\t\t\t\t\t\tseen[image] = 1;\n\t\t\t\t\t\tmembers.push(image);\n\t\t\t\t\t}\n\t\t\t\t\tif (members.length > 1) ties.push(members.length, ...members);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ttieStart[slots] = ties.length;\n\n\treturn {\n\t\tstart, count, list: Uint16Array.from(entries), slot: Uint16Array.from(entrySlots), roundBase,\n\t\ttieStart, ties: Int32Array.from(ties),\n\t};\n}\n\n/**\n * Make mirrored hands' accumulators equal, by averaging each tie class.\n *\n * Their updates are equal in exact arithmetic but not in floating point, and\n * regret matching is discontinuous at zero, so left alone the copies drift to\n * genuinely different strategies — and the reach that flows from them stops\n * being symmetric, which is what lets a stored board stand for its mirror\n * images. Averaging restores exact equality after every update. It is CFR on\n * the folded game, where the mirrored hands are one information set.\n */\nexport function tieMirrors(\n\tstore: RegretStore | SumStore,\n\tslotBase: number,\n\tactions: number,\n\tstride: number,\n\tties: Int32Array,\n\tfrom: number,\n\tto: number,\n\tinteger: boolean,\n): void {\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst row = slotBase + a * stride;\n\t\tfor (let k = from; k < to; ) {\n\t\t\tconst size = ties[k];\n\t\t\tlet sum = 0;\n\t\t\tfor (let j = 1; j <= size; j++) sum += store[row + ties[k + j]];\n\t\t\tlet mean = sum / size;\n\t\t\tif (integer) mean = Math.round(mean);\n\t\t\tfor (let j = 1; j <= size; j++) store[row + ties[k + j]] = mean;\n\t\t\tk += size + 1;\n\t\t}\n\t}\n}\n\n/**\n * Tie mirrored hands on one node and board, as every update does; for code\n * that writes accumulators outside a traversal, such as a warm start.\n */\nexport function tieBlock(ctx: Context, node: number, board: number): void {\n\tconst { tree } = ctx;\n\tconst owner = tree.player[node];\n\tconst lists = ctx.active;\n\tconst listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;\n\tconst from = lists.tieStart[listSlot];\n\tconst to = lists.tieStart[listSlot + 1];\n\tif (from === to) return;\n\tconst actions = tree.numEdges[node];\n\tconst stride = ctx.players[owner].count;\n\tconst base = ctx.layout.offset[node] + board * actions * stride;\n\tconst integer = ctx.regretScale !== null;\n\tif (ctx.regret.length > 0) tieMirrors(ctx.regret, base, actions, stride, lists.ties, from, to, integer);\n\ttieMirrors(ctx.strategySum, base, actions, stride, lists.ties, from, to, integer);\n}\n\n/** Per-depth buffers, so the hot loop never allocates. */\ninterface Buffers {\n\treadonly value: Float64Array[];\n\t/**\n\t * Reach buffers per player. Only ever written at that player's own\n\t * combinations, so entries belonging to the other player stay zero from\n\t * allocation and never need clearing.\n\t */\n\treadonly reachFor: readonly [Float64Array[], Float64Array[]];\n\treadonly strategy: Float64Array[];\n\treadonly actionValues: Float64Array[];\n\treadonly live: Uint16Array[];\n\t/** Reach and live hands relabelled onto a stored board, for `expandOrbits`. */\n\treadonly mappedMe: Float64Array[];\n\treadonly mappedOpp: Float64Array[];\n\treadonly mappedLive: Uint16Array[];\n\t/** This thread's SIMD kernels, whose memory holds `strategy`; null for JavaScript. */\n\treadonly kernels: Kernels | null;\n}\n\nfunction makeBuffers(tree: Tree, maxActions: number, simd: boolean): Buffers {\n\tconst depth = treeDepth(tree) + 2;\n\tconst make = <T>(factory: () => T): T[] => Array.from({ length: depth }, factory);\n\tconst kernels = simd ? loadKernels(depth, maxActions * COMBOS) : null;\n\treturn {\n\t\tkernels,\n\t\tvalue: make(() => new Float64Array(COMBOS)),\n\t\treachFor: [make(() => new Float64Array(COMBOS)), make(() => new Float64Array(COMBOS))],\n\t\tstrategy: kernels\n\t\t\t? Array.from({ length: depth }, (_, d) => kernels.strategy(d))\n\t\t\t: make(() => new Float64Array(maxActions * COMBOS)),\n\t\tactionValues: make(() => new Float64Array(maxActions * COMBOS)),\n\t\tlive: make(() => new Uint16Array(COMBOS)),\n\t\tmappedMe: make(() => new Float64Array(COMBOS)),\n\t\tmappedOpp: make(() => new Float64Array(COMBOS)),\n\t\tmappedLive: make(() => new Uint16Array(COMBOS)),\n\t};\n}\n\nfunction treeDepth(tree: Tree): number {\n\tconst depth = new Int32Array(tree.nodeCount).fill(-1);\n\tdepth[0] = 1;\n\tlet max = 1;\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tconst here = depth[node];\n\t\tif (here < 0) continue;\n\t\tif (here > max) max = here;\n\t\tfor (let e = 0; e < tree.numEdges[node]; e++) {\n\t\t\tconst child = tree.edgeChild[tree.firstEdge[node] + e];\n\t\t\tif (depth[child] < here + 1) depth[child] = here + 1;\n\t\t}\n\t}\n\treturn max;\n}\n\n/**\n * Discounted CFR (Brown & Sandholm, 2019) at its usual setting. Before\n * iteration `t` adds its regrets, accumulated positive regret is scaled by\n * `(t-1)^α / ((t-1)^α + 1)` and negative regret by `(t-1)^β / ((t-1)^β + 1)`,\n * so a negative regret is halved each iteration rather than clamped; the\n * strategy sum is scaled by `((t-1) / t)^γ`, weighting iteration `t` about\n * `t^γ`. Every slot is visited exactly once per iteration, by its owner's\n * traversal, so discounting at that visit is the same as discounting\n * everything between iterations — without a separate pass over memory.\n */\nconst DCFR_ALPHA = 1.5;\nconst DCFR_BETA = 0;\nconst DCFR_GAMMA = 2;\n\nexport const Mode = { Train: 0, BestResponse: 1, Average: 2 } as const;\nexport type Mode = (typeof Mode)[keyof typeof Mode];\n\n/**\n * Normalise accumulated values into a strategy: each action's share of the\n * positive values, uniform where there are none. One hand at a time, so its\n * few actions stay in registers rather than round-tripping through a sum array.\n *\n * @param source regrets, for the current strategy\n * @param slots each active entry's storage slot, beside `active`\n * @param strategy written as storage is laid out: `strategy[a * stride + slot]`\n */\nfunction normalise(\n\tsource: RegretStore | SumStore,\n\tbase: number,\n\tactions: number,\n\tstride: number,\n\tactive: Uint16Array,\n\tslots: Uint16Array,\n\tfrom: number,\n\tcount: number,\n\tstrategy: Float64Array,\n): void {\n\tconst uniform = 1 / actions;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst slot = slots[from + i];\n\t\tconst at = base + slot;\n\t\tlet total = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst value = source[at + a * stride];\n\t\t\tconst positive = value > 0 ? value : 0;\n\t\t\tstrategy[a * stride + slot] = positive;\n\t\t\ttotal += positive;\n\t\t}\n\t\tif (total > 0) {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * stride + slot] /= total;\n\t\t} else {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * stride + slot] = uniform;\n\t\t}\n\t}\n}\n\n/** Current strategy from positive regrets; uniform where there is none. */\nfunction regretMatch(\n\tregret: RegretStore,\n\tbase: number,\n\tactions: number,\n\tstride: number,\n\tactive: Uint16Array,\n\tslots: Uint16Array,\n\tfrom: number,\n\tcount: number,\n\tstrategy: Float64Array,\n): void {\n\tnormalise(regret, base, actions, stride, active, slots, from, count, strategy);\n}\n\n/**\n * Average strategy from accumulated sums, which are never negative.\n *\n * A hand whose sum is zero here never reached this node on its own, so the\n * average says nothing about it. Its regrets are still updated — weighted by\n * the opponent's reach — so it plays the current strategy: whatever goes on to\n * continue it from here (a best response, another player's rules, a user\n * browsing the line) then sees sensible play rather than every action at an\n * equal share. Uniform only where the regrets are all non-positive too, or\n * where there are none (an `analysisOnly` run).\n *\n * @param regret the regrets beside `strategySum`, or omitted for none\n */\nexport function averageStrategy(\n\tstrategySum: SumStore,\n\tbase: number,\n\tactions: number,\n\tstride: number,\n\tactive: Uint16Array,\n\tslots: Uint16Array,\n\tfrom: number,\n\tcount: number,\n\tstrategy: Float64Array,\n\tregret?: RegretStore,\n): void {\n\tconst fallback = regret !== undefined && regret.length > 0 ? regret : null;\n\tconst uniform = 1 / actions;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst slot = slots[from + i];\n\t\tconst at = base + slot;\n\t\tlet total = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst value = strategySum[at + a * stride];\n\t\t\tstrategy[a * stride + slot] = value;\n\t\t\ttotal += value;\n\t\t}\n\t\tif (total > 0) {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * stride + slot] /= total;\n\t\t\tcontinue;\n\t\t}\n\t\tif (fallback !== null) {\n\t\t\tfor (let a = 0; a < actions; a++) {\n\t\t\t\tconst value = fallback[at + a * stride];\n\t\t\t\tconst positive = value > 0 ? value : 0;\n\t\t\t\tstrategy[a * stride + slot] = positive;\n\t\t\t\ttotal += positive;\n\t\t\t}\n\t\t}\n\t\tif (total > 0) {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * stride + slot] /= total;\n\t\t} else {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * stride + slot] = uniform;\n\t\t}\n\t}\n}\n\nfunction traverse(\n\tctx: Context,\n\tbuffers: Buffers,\n\tmode: Mode,\n\ttraverser: 0 | 1,\n\titerWeight: number,\n\tnode: number,\n\tboard: number,\n\treachMe: Float64Array,\n\treachOpp: Float64Array,\n\tlive: Uint16Array,\n\tliveCount: number,\n\tdepth: number,\n): Float64Array {\n\tconst { tree, runouts } = ctx;\n\tconst out = buffers.value[depth];\n\tconst kind = tree.kind[node];\n\n\tif (kind === NodeKind.TerminalFold) {\n\t\tconst signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];\n\t\tconst weight = ctx.runoutWeight[tree.round[node]] / ctx.chipScale;\n\t\tfoldValues(reachOpp, live, liveCount, signed * weight, ctx.scratch, out);\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.TerminalShowdown) {\n\t\tconst weight = ctx.runoutWeight[tree.round[node]] / ctx.chipScale;\n\t\tshowdownValues(reachOpp, ctx.showdown, board, tree.payoff[node] * weight, ctx.scratch, out);\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.Chance) {\n\t\tfor (let i = 0; i < liveCount; i++) out[live[i]] = 0;\n\t\tconst nextRound = tree.round[node] + 1;\n\n\t\t// At the shard boundary the subtree below belongs to the workers: the\n\t\t// collect pass records what they need, and the apply pass reads back\n\t\t// the totals they produced.\n\t\tif (ctx.entryIndexOf !== null && nextRound === ctx.shardRound) {\n\t\t\tconst entry = ctx.entryIndexOf[node];\n\t\t\tif (entry >= 0) {\n\t\t\t\tif (ctx.chanceCollect !== null) {\n\t\t\t\t\tctx.chanceCollect(node, reachMe, reachOpp);\n\t\t\t\t\treturn out;\n\t\t\t\t}\n\t\t\t\tif (ctx.chanceOverride !== null) {\n\t\t\t\t\tconst base = entry * COMBOS;\n\t\t\t\t\tfor (let i = 0; i < liveCount; i++) out[live[i]] = ctx.chanceOverride[base + live[i]];\n\t\t\t\t\treturn out;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst child = tree.edgeChild[tree.firstEdge[node]];\n\t\tconst width = runouts.width[nextRound];\n\t\tconst cards = runouts.cards[nextRound];\n\t\tconst orbitStart = runouts.orbitStart[nextRound];\n\t\tconst orbitMap = runouts.orbitMap[nextRound];\n\t\tconst orbitCard = runouts.orbitCard[nextRound];\n\t\tconst comboMaps = runouts.maps.combo;\n\n\t\tconst childLive = buffers.live[depth];\n\t\tconst comboCards = COMBO_CARDS;\n\n\t\t// Workers own contiguous slices of the boards at the shard round.\n\t\tconst sharded = nextRound === ctx.shardRound;\n\t\tconst first = runouts.childStart[nextRound][board];\n\t\tconst last = runouts.childStart[nextRound][board + 1];\n\t\tconst from = sharded && ctx.shardStart > first ? ctx.shardStart : first;\n\t\tconst to = sharded && ctx.shardEnd < last ? ctx.shardEnd : last;\n\n\t\tfor (let childBoard = from; childBoard < to; childBoard++) {\n\t\t\tconst dealt = cards[childBoard * width + width - 1];\n\n\t\t\t// A deal changes which hands are live, not their reach, so the\n\t\t\t// child gets the parent's reach vectors as they are. Nothing below\n\t\t\t// reads a hand the dealt card blocks — every loop runs over\n\t\t\t// `childLive` or the board's own active list — and nothing below\n\t\t\t// writes to them: each node writes only its own depth's buffers.\n\t\t\tlet childCount = 0;\n\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\tconst combo = live[i];\n\t\t\t\tif (comboCards[combo * 2] === dealt || comboCards[combo * 2 + 1] === dealt) continue;\n\t\t\t\tchildLive[childCount++] = combo;\n\t\t\t}\n\n\t\t\tconst value = traverse(\n\t\t\t\tctx, buffers, mode, traverser, iterWeight,\n\t\t\t\tchild, childBoard, reachMe, reachOpp, childLive, childCount, depth + 1,\n\t\t\t);\n\t\t\tfor (let i = 0; i < childCount; i++) out[childLive[i]] += value[childLive[i]];\n\n\t\t\t// The other deals this board stands for. Hand `h` after the real\n\t\t\t// card plays as `map[h]` after the stored one.\n\t\t\tconst membersEnd = orbitStart[childBoard + 1];\n\t\t\tfor (let m = orbitStart[childBoard] + 1; m < membersEnd; m++) {\n\t\t\t\tconst map = comboMaps[orbitMap[m]];\n\t\t\t\tconst real = orbitCard[m];\n\t\t\t\tif (!ctx.expandOrbits) {\n\t\t\t\t\t// Reach is symmetric under the map, so the stored subtree's\n\t\t\t\t\t// values ARE the mirrored subtree's, relabelled.\n\t\t\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\t\t\tconst combo = live[i];\n\t\t\t\t\t\tif (comboCards[combo * 2] === real || comboCards[combo * 2 + 1] === real) continue;\n\t\t\t\t\t\tout[combo] += value[map[combo]];\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Any reach: walk the stored subtree again with the real deal's\n\t\t\t\t// reach relabelled onto it.\n\t\t\t\tconst mappedMe = buffers.mappedMe[depth];\n\t\t\t\tconst mappedOpp = buffers.mappedOpp[depth];\n\t\t\t\tconst mappedLive = buffers.mappedLive[depth];\n\t\t\t\tlet mappedCount = 0;\n\t\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\t\tconst combo = live[i];\n\t\t\t\t\tif (comboCards[combo * 2] === real || comboCards[combo * 2 + 1] === real) continue;\n\t\t\t\t\tconst image = map[combo];\n\t\t\t\t\tmappedMe[image] = reachMe[combo];\n\t\t\t\t\tmappedOpp[image] = reachOpp[combo];\n\t\t\t\t\tmappedLive[mappedCount++] = image;\n\t\t\t\t}\n\t\t\t\tconst mirrored = traverse(\n\t\t\t\t\tctx, buffers, mode, traverser, iterWeight,\n\t\t\t\t\tchild, childBoard, mappedMe, mappedOpp, mappedLive, mappedCount, depth + 1,\n\t\t\t\t);\n\t\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\t\tconst combo = live[i];\n\t\t\t\t\tif (comboCards[combo * 2] === real || comboCards[combo * 2 + 1] === real) continue;\n\t\t\t\t\tout[combo] += mirrored[map[combo]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t// --- decision ---\n\tconst actions = tree.numEdges[node];\n\tconst edgeBase = tree.firstEdge[node];\n\tconst owner = tree.player[node] as 0 | 1;\n\tconst index = ctx.players[owner];\n\tconst stride = index.count;\n\tconst slotBase = ctx.layout.offset[node] + board * actions * stride;\n\tconst isTraverser = owner === traverser;\n\n\t// Which hands this player can hold here was settled when the boards were\n\t// enumerated; it does not depend on the node.\n\tconst lists = ctx.active;\n\tconst listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;\n\tconst active = lists.list;\n\tconst activeSlot = lists.slot;\n\tconst activeFrom = lists.start[listSlot];\n\tconst activeCount = lists.count[listSlot];\n\n\t// Laid out as storage is: `strategy[a * stride + slot]`.\n\tconst strategy = buffers.strategy[depth];\n\tif (mode === Mode.Train && buffers.kernels !== null) {\n\t\tconst kernels = buffers.kernels;\n\t\tkernels.input.set(ctx.regret.subarray(slotBase, slotBase + actions * stride));\n\t\tkernels.regretMatch(strategy, actions, stride);\n\t} else if (mode === Mode.Train) {\n\t\tregretMatch(ctx.regret, slotBase, actions, stride, active, activeSlot, activeFrom, activeCount, strategy);\n\t} else if (buffers.kernels !== null) {\n\t\tconst kernels = buffers.kernels;\n\t\tconst length = actions * stride;\n\t\tkernels.input.set(ctx.strategySum.subarray(slotBase, slotBase + length));\n\t\tconst hasRegret = ctx.regret.length > 0;\n\t\tif (hasRegret) kernels.second.set(ctx.regret.subarray(slotBase, slotBase + length));\n\t\tkernels.averageMatch(strategy, actions, stride, hasRegret);\n\t} else {\n\t\taverageStrategy(ctx.strategySum, slotBase, actions, stride, active, activeSlot, activeFrom, activeCount, strategy, ctx.regret);\n\t}\n\n\tfor (let i = 0; i < liveCount; i++) out[live[i]] = 0;\n\n\tif (isTraverser && mode === Mode.BestResponse) {\n\t\tlet first = true;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst value = traverse(\n\t\t\t\tctx, buffers, mode, traverser, iterWeight,\n\t\t\t\ttree.edgeChild[edgeBase + a], board, reachMe, reachOpp, live, liveCount, depth + 1,\n\t\t\t);\n\t\t\tif (first) {\n\t\t\t\tfor (let i = 0; i < activeCount; i++) out[active[activeFrom + i]] = value[active[activeFrom + i]];\n\t\t\t\tfirst = false;\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\t\tconst combo = active[activeFrom + i];\n\t\t\t\t\tif (value[combo] > out[combo]) out[combo] = value[combo];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t// Owned by whoever is acting, so hands they cannot hold are already zero\n\t// and only their own need writing.\n\tconst childReach = buffers.reachFor[owner][depth];\n\tconst actionValues = buffers.actionValues[depth];\n\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * COMBOS;\n\t\tconst row = a * stride;\n\t\tconst source = isTraverser ? reachMe : reachOpp;\n\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\tconst combo = active[activeFrom + i];\n\t\t\tchildReach[combo] = source[combo] * strategy[row + activeSlot[activeFrom + i]];\n\t\t}\n\n\t\tconst value = traverse(\n\t\t\tctx, buffers, mode, traverser, iterWeight,\n\t\t\ttree.edgeChild[edgeBase + a], board,\n\t\t\tisTraverser ? childReach : reachMe,\n\t\t\tisTraverser ? reachOpp : childReach,\n\t\t\tlive, liveCount, depth + 1,\n\t\t);\n\n\t\tif (isTraverser) {\n\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\tconst combo = active[activeFrom + i];\n\t\t\t\tactionValues[offset + combo] = value[combo];\n\t\t\t\tout[combo] += strategy[row + activeSlot[activeFrom + i]] * value[combo];\n\t\t\t}\n\t\t} else {\n\t\t\t// The opponent's strategy already sits inside their reach, so the\n\t\t\t// counterfactual value is the plain sum over their actions.\n\t\t\tfor (let i = 0; i < liveCount; i++) out[live[i]] += value[live[i]];\n\t\t}\n\t}\n\n\tif (isTraverser && mode === Mode.Train && ctx.applyUpdates && ctx.regretScale !== null) {\n\t\tupdateQuantised(\n\t\t\tctx, ctx.layout.blockOffset[node] + board, slotBase, actions, stride,\n\t\t\tactive, activeSlot, activeFrom, activeCount, iterWeight, reachMe, strategy, actionValues, out,\n\t\t);\n\t} else if (isTraverser && mode === Mode.Train && ctx.applyUpdates && ctx.dcfr) {\n\t\t// `iterWeight` is the iteration number, counted from 1.\n\t\tconst previous = iterWeight - 1;\n\t\tconst grown = previous ** DCFR_ALPHA;\n\t\tconst shrunk = previous ** DCFR_BETA;\n\t\tconst keepPositive = grown / (grown + 1);\n\t\tconst keepNegative = shrunk / (shrunk + 1);\n\t\tconst keepSum = (previous / iterWeight) ** DCFR_GAMMA;\n\t\tconst regret = ctx.regret;\n\t\tconst strategySum = ctx.strategySum;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst offset = a * COMBOS;\n\t\t\tconst slotRow = slotBase + a * stride;\n\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\tconst combo = active[activeFrom + i];\n\t\t\t\tconst at = slotRow + activeSlot[activeFrom + i];\n\t\t\t\tconst accumulated = regret[at];\n\t\t\t\tregret[at] =\n\t\t\t\t\taccumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[offset + combo] - out[combo];\n\t\t\t\tstrategySum[at] = strategySum[at] * keepSum + reachMe[combo] * strategy[a * stride + activeSlot[activeFrom + i]];\n\t\t\t}\n\t\t}\n\t} else if (isTraverser && mode === Mode.Train && ctx.applyUpdates) {\n\t\tconst regret = ctx.regret;\n\t\tconst strategySum = ctx.strategySum;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst offset = a * COMBOS;\n\t\t\tconst slotRow = slotBase + a * stride;\n\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\tconst combo = active[activeFrom + i];\n\t\t\t\tconst at = slotRow + activeSlot[activeFrom + i];\n\t\t\t\t// CFR+: clamp the accumulated regret at zero in the same pass.\n\t\t\t\tconst updated = regret[at] + actionValues[offset + combo] - out[combo];\n\t\t\t\tregret[at] = updated > 0 ? updated : 0;\n\t\t\t\tstrategySum[at] += iterWeight * reachMe[combo] * strategy[a * stride + activeSlot[activeFrom + i]];\n\t\t\t}\n\t\t}\n\t}\n\n\tif (isTraverser && mode === Mode.Train && ctx.applyUpdates) {\n\t\tconst tieFrom = lists.tieStart[listSlot];\n\t\tconst tieTo = lists.tieStart[listSlot + 1];\n\t\tif (tieFrom < tieTo) {\n\t\t\tconst integer = ctx.regretScale !== null;\n\t\t\ttieMirrors(ctx.regret, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);\n\t\t\ttieMirrors(ctx.strategySum, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * The regret and strategy-sum update for 16-bit storage, under either rule.\n *\n * A block is rescaled whole on every update: decode, update in float, find the\n * block's largest magnitude, re-encode against it.\n *\n * Regrets round to nearest. Strategy sums round up or down at random, with\n * odds set by the remainder, so each is right on average: rounded to nearest,\n * a hand whose sum is small beside its block's largest loses most of every\n * iteration's contribution, and measured, exploitability stalls near 0.04%\n * of pot where float32 keeps falling. The randomness is a hash of the slot and\n * the iteration, so a solve stays deterministic at any thread count.\n *\n * `actionValues` and `strategy` are not needed once their values are used, so\n * the new regrets and sums are staged in them rather than in buffers of their\n * own.\n */\nfunction updateQuantised(\n\tctx: Context,\n\tblock: number,\n\tslotBase: number,\n\tactions: number,\n\tstride: number,\n\tactive: Uint16Array,\n\tactiveSlot: Uint16Array,\n\tactiveFrom: number,\n\tactiveCount: number,\n\titerWeight: number,\n\treachMe: Float64Array,\n\tstrategy: Float64Array,\n\tactionValues: Float64Array,\n\tout: Float64Array,\n): void {\n\tconst regret = ctx.regret;\n\tconst strategySum = ctx.strategySum;\n\tconst regretScale = ctx.regretScale!;\n\tconst sumScale = ctx.sumScale!;\n\tconst oldRegret = regretScale[block];\n\tconst oldSum = sumScale[block];\n\n\t// CFR+ is the special case that clamps and keeps everything: a negative\n\t// regret is floored at zero, a positive one kept whole, and iteration `t`\n\t// is weighted `t` in the sum.\n\tlet keepPositive = 1;\n\tlet keepNegative = 0;\n\tlet keepSum = 1;\n\tlet weight = iterWeight;\n\tconst clamp = !ctx.dcfr;\n\tif (ctx.dcfr) {\n\t\tconst previous = iterWeight - 1;\n\t\tconst grown = previous ** DCFR_ALPHA;\n\t\tconst shrunk = previous ** DCFR_BETA;\n\t\tkeepPositive = grown / (grown + 1);\n\t\tkeepNegative = shrunk / (shrunk + 1);\n\t\tkeepSum = (previous / iterWeight) ** DCFR_GAMMA;\n\t\tweight = 1;\n\t}\n\n\tlet largestRegret = 0;\n\tlet largestSum = 0;\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * COMBOS;\n\t\tconst slotRow = slotBase + a * stride;\n\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\tconst combo = active[activeFrom + i];\n\t\t\tconst at = slotRow + activeSlot[activeFrom + i];\n\t\t\tconst accumulated = regret[at] * oldRegret;\n\t\t\tlet updated =\n\t\t\t\taccumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[offset + combo] - out[combo];\n\t\t\tif (clamp && updated < 0) updated = 0;\n\t\t\tconst magnitude = updated < 0 ? -updated : updated;\n\t\t\tif (magnitude > largestRegret) largestRegret = magnitude;\n\t\t\tactionValues[offset + combo] = updated;\n\n\t\t\tconst sum = strategySum[at] * oldSum * keepSum + weight * reachMe[combo] * strategy[a * stride + activeSlot[activeFrom + i]];\n\t\t\tif (sum > largestSum) largestSum = sum;\n\t\t\tstrategy[a * stride + activeSlot[activeFrom + i]] = sum;\n\t\t}\n\t}\n\n\t// Storing into a 16-bit array truncates toward zero, so adding a half away\n\t// from zero rounds to nearest, and adding the dither rounds at random. A\n\t// value at the very top of the range plus nearly a whole dither would\n\t// reach 65536 and wrap to zero, hence the cap.\n\tconst regretStep = largestRegret > 0 ? REGRET_STEPS / largestRegret : 0;\n\tconst sumStep = largestSum > 0 ? SUM_STEPS / largestSum : 0;\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * COMBOS;\n\t\tconst slotRow = slotBase + a * stride;\n\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\tconst combo = active[activeFrom + i];\n\t\t\tconst at = slotRow + activeSlot[activeFrom + i];\n\t\t\tconst r = actionValues[offset + combo] * regretStep;\n\t\t\tregret[at] = r < 0 ? r - 0.5 : r + 0.5;\n\t\t\tconst s = strategy[a * stride + activeSlot[activeFrom + i]] * sumStep + dither(at, iterWeight);\n\t\t\tstrategySum[at] = s < SUM_STEPS ? s : SUM_STEPS;\n\t\t}\n\t}\n\tregretScale[block] = largestRegret / REGRET_STEPS;\n\tsumScale[block] = largestSum / SUM_STEPS;\n}\n\n/** A deterministic uniform value in [0, 1) for a slot on an iteration. */\nfunction dither(slot: number, iteration: number): number {\n\tlet h = Math.imul(slot ^ Math.imul(iteration, 0x9e3779b1), 0x85ebca6b);\n\th ^= h >>> 13;\n\th = Math.imul(h, 0xc2b2ae35);\n\th ^= h >>> 16;\n\treturn (h >>> 0) / 4294967296;\n}\n\n/** A whole-tree traversal, returning the root value vector. */\nexport type RootTraversal = (mode: Mode, traverser: 0 | 1, iterWeight: number) => Float64Array;\n\n/** A prepared solver. */\nexport interface Solver {\n\treadonly ctx: Context;\n\t/**\n\t * One traversal for `traverser` on this thread alone, returning the root\n\t * value vector.\n\t */\n\ttraverseRoot(mode: Mode, traverser: 0 | 1, iterWeight: number): Float64Array;\n\t/**\n\t * Route the whole-tree traversals behind `iterate`, `expectedValue` and\n\t * `exploitability` elsewhere — a worker pool — or back to `traverseRoot`\n\t * with null.\n\t */\n\tuseRoot(root: RootTraversal | null): void;\n\t/** One chance node's subtree, honouring the context shard. */\n\ttraverseChance(\n\t\tmode: Mode,\n\t\ttraverser: 0 | 1,\n\t\titerWeight: number,\n\t\tnode: number,\n\t\treachMe: Float64Array,\n\t\treachOpp: Float64Array,\n\t): Float64Array;\n\t/** Combinations live on the given board, shared by root and workers. */\n\treadonly rootLive: Uint16Array;\n\treadonly rootCount: number;\n\titerate(count: number, from: number): void;\n\texpectedValue(): [number, number];\n\texploitability(): number;\n\taverageStrategyAt(node: number, board: number): { actions: number; probs: Float64Array };\n\t/**\n\t * Counterfactual values under the average strategy from any node, for\n\t * reach vectors the caller supplies. Returns a fresh copy.\n\t */\n\tvaluesAt(\n\t\tnode: number,\n\t\tboard: number,\n\t\ttraverser: 0 | 1,\n\t\treachMe: Float64Array,\n\t\treachOpp: Float64Array,\n\t\tlive: Uint16Array,\n\t\tliveCount: number,\n\t): Float64Array;\n\t/**\n\t * Counterfactual values under the average strategy from any node against\n\t * each of `hands` alone, at the reach given for it: the same as `valuesAt`\n\t * with a one-hot opponent reach, for many opposing hands in one walk.\n\t * Returns `hands.length * COMBOS` values, one row per opposing hand.\n\t */\n\tpairValuesAt(\n\t\tnode: number,\n\t\tboard: number,\n\t\ttraverser: 0 | 1,\n\t\thands: Uint16Array,\n\t\thandReach: Float64Array,\n\t\tlive: Uint16Array,\n\t\tliveCount: number,\n\t): Float64Array;\n}\n\n/** Create a solver over prepared structures. */\nexport function makeSolver(ctx: Context): Solver {\n\tconst buffers = makeBuffers(ctx.tree, ctx.layout.maxActions, ctx.simd);\n\tconst reach0 = new Float64Array(COMBOS);\n\tconst reach1 = new Float64Array(COMBOS);\n\tconst rootLive = new Uint16Array(COMBOS);\n\n\t// Only hands one of the players can actually hold, minus whatever the given\n\t// board blocks. Carrying the other thousand-odd combinations through every\n\t// traversal would cost far more than the solve itself.\n\tlet rootCount = 0;\n\t{\n\t\tconst onBoard = new Uint8Array(DECK);\n\t\tfor (const card of ctx.runouts.initial) onBoard[card] = 1;\n\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\tif (ctx.players[0].slot[combo] < 0 && ctx.players[1].slot[combo] < 0) continue;\n\t\t\tif (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;\n\t\t\trootLive[rootCount++] = combo;\n\t\t}\n\t}\n\n\tconst run = (mode: Mode, traverser: 0 | 1, iterWeight: number): Float64Array => {\n\t\treach0.set(ctx.players[0].weights);\n\t\treach1.set(ctx.players[1].weights);\n\t\tfor (let i = 0; i < COMBOS; i++) {\n\t\t\t// Anything the board holds cannot be in either range.\n\t\t\tif (ctx.players[0].slot[i] < 0) reach0[i] = 0;\n\t\t\tif (ctx.players[1].slot[i] < 0) reach1[i] = 0;\n\t\t}\n\t\tconst me = traverser === 0 ? reach0 : reach1;\n\t\tconst opp = traverser === 0 ? reach1 : reach0;\n\t\treturn traverse(ctx, buffers, mode, traverser, iterWeight, 0, 0, me, opp, rootLive, rootCount, 0);\n\t};\n\n\tlet root: RootTraversal = run;\n\n\tconst total = (values: Float64Array, traverser: 0 | 1): number => {\n\t\t// Values are counterfactual, so weighting by this player's own reach\n\t\t// turns them into the value of the spot.\n\t\tconst weights = ctx.players[traverser].weights;\n\t\tlet sum = 0;\n\t\tfor (let i = 0; i < rootCount; i++) {\n\t\t\tconst combo = rootLive[i];\n\t\t\tsum += weights[combo] * values[combo];\n\t\t}\n\t\treturn sum / ctx.totalMass;\n\t};\n\n\treturn {\n\t\tctx,\n\t\trootLive,\n\t\tget rootCount() {\n\t\t\treturn rootCount;\n\t\t},\n\t\ttraverseRoot: run,\n\t\tuseRoot(next) {\n\t\t\troot = next ?? run;\n\t\t},\n\t\ttraverseChance(mode, traverser, iterWeight, node, me, opp) {\n\t\t\treturn traverse(\n\t\t\t\tctx, buffers, mode, traverser, iterWeight, node, 0, me, opp, rootLive, rootCount, 0,\n\t\t\t);\n\t\t},\n\t\titerate(count, from) {\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\tconst t = from + i + 1;\n\t\t\t\troot(Mode.Train, 0, t);\n\t\t\t\troot(Mode.Train, 1, t);\n\t\t\t}\n\t\t},\n\t\texpectedValue() {\n\t\t\treturn [total(root(Mode.Average, 0, 0), 0), total(root(Mode.Average, 1, 0), 1)];\n\t\t},\n\t\texploitability() {\n\t\t\tconst br0 = total(root(Mode.BestResponse, 0, 0), 0);\n\t\t\tconst br1 = total(root(Mode.BestResponse, 1, 0), 1);\n\t\t\treturn (br0 + br1) / 2;\n\t\t},\n\t\tvaluesAt(node, board, traverser, reachMe, reachOpp, live, liveCount) {\n\t\t\t// The caller's reach need not be symmetric, so mirrored deals are\n\t\t\t// walked rather than assumed.\n\t\t\tconst expanded = ctx.expandOrbits;\n\t\t\tctx.expandOrbits = true;\n\t\t\ttry {\n\t\t\t\tconst value = traverse(\n\t\t\t\t\tctx, buffers, Mode.Average, traverser, 0, node, board, reachMe, reachOpp, live, liveCount, 0,\n\t\t\t\t);\n\t\t\t\treturn Float64Array.from(value.subarray(0, COMBOS));\n\t\t\t} finally {\n\t\t\t\tctx.expandOrbits = expanded;\n\t\t\t}\n\t\t},\n\t\tpairValuesAt(node, board, traverser, hands, handReach, live, liveCount) {\n\t\t\treturn pairValues(ctx, node, board, traverser, hands, handReach, live, liveCount);\n\t\t},\n\t\taverageStrategyAt(node, board) {\n\t\t\tconst owner = ctx.tree.player[node] as 0 | 1;\n\t\t\tconst index = ctx.players[owner];\n\t\t\tconst actions = ctx.tree.numEdges[node];\n\t\t\tconst base = ctx.layout.offset[node] + board * actions * index.count;\n\t\t\tconst probs = new Float64Array(index.count * actions);\n\t\t\t// Where the sum is zero, the current strategy; see `averageStrategy`.\n\t\t\tconst regret = ctx.regret;\n\t\t\tfor (let i = 0; i < index.count; i++) {\n\t\t\t\tlet sum = 0;\n\t\t\t\tfor (let a = 0; a < actions; a++) sum += ctx.strategySum[base + a * index.count + i];\n\t\t\t\tlet source: RegretStore | SumStore = ctx.strategySum;\n\t\t\t\tif (!(sum > 0) && regret.length > 0) {\n\t\t\t\t\tfor (let a = 0; a < actions; a++) {\n\t\t\t\t\t\tconst value = regret[base + a * index.count + i];\n\t\t\t\t\t\tif (value > 0) sum += value;\n\t\t\t\t\t}\n\t\t\t\t\tsource = regret;\n\t\t\t\t}\n\t\t\t\tfor (let a = 0; a < actions; a++) {\n\t\t\t\t\tconst value = source[base + a * index.count + i];\n\t\t\t\t\tprobs[i * actions + a] = sum > 0 ? (value > 0 ? value / sum : 0) : 1 / actions;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { actions, probs };\n\t\t},\n\t};\n}\n\nexport { buildActiveLists, makeTerminalScratch };\n","/**\n * Warm starts.\n *\n * Purpose: begin a solve from a previous one's regrets and strategy sums\n * instead of from nothing.\n *\n * A tweaked spot — a different pot, a bet size nudged, a range reweighted —\n * has nearly the same equilibrium as the one before, so starting there costs\n * a fraction of the iterations. Nothing about the answer is approximate: CFR\n * converges from any starting point, and this one is merely close.\n *\n * What carries over is the regrets — they ARE the current strategy, which is\n * what a nearby equilibrium shares — and, only for the very same spot, the\n * average strategy too, so a solve can be resumed exactly.\n *\n * The two trees are walked together from the root. A decision matches when\n * the same player acts in the same round; its actions match by kind, and bets\n * and raises by size as a fraction of the pot, the nearest within a factor of\n * `SIZE_TOLERANCE`. Whatever matches nothing starts cold. Boards match by\n * their real cards, so two spots may store different runouts (one folding\n * mirrored deals, the other not); hands match by combination, so a range may\n * have grown or shrunk.\n */\n\nimport type { Context, RegretStore, SumStore } from './cfr.ts';\nimport { tieBlock } from './cfr.ts';\nimport { COMBOS } from './cards.ts';\nimport type { Runouts } from './runouts.ts';\nimport { resolveBoard } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ActionKind, NodeKind } from './tree.ts';\n\n/** Largest ratio between two bet sizes, as pot fractions, still taken as the same. */\nconst SIZE_TOLERANCE = 1.35;\n\nconst REGRET_STEPS = 32767;\nconst SUM_STEPS = 65535;\n\n/** What a warm start carried over. */\nexport interface WarmStartReport {\n\t/** Decision nodes of the new tree that found a match in the old one. */\n\treadonly matchedNodes: number;\n\treadonly decisionNodes: number;\n\t/**\n\t * Whether the average strategy was carried over too. Only for the very\n\t * same spot: the average of another spot's iterations would have to be\n\t * outweighed before the new spot's own could show, and measured, that\n\t * costs more than it saves — a pot 20% bigger took 475 iterations to\n\t * reach 0.1% of pot carrying it, 100 without, 125 from cold.\n\t */\n\treadonly averages: boolean;\n}\n\n/**\n * Pair each decision node of `to` with its counterpart in `from`, or -1.\n */\nexport function matchNodes(to: Tree, from: Tree): Int32Array {\n\tconst match = new Int32Array(to.nodeCount).fill(-1);\n\tconst walk = (a: number, b: number): void => {\n\t\tif (to.kind[a] !== from.kind[b] || to.round[a] !== from.round[b]) return;\n\t\tif (to.kind[a] === NodeKind.Chance) {\n\t\t\twalk(to.edgeChild[to.firstEdge[a]], from.edgeChild[from.firstEdge[b]]);\n\t\t\treturn;\n\t\t}\n\t\tif (to.kind[a] !== NodeKind.Decision || to.player[a] !== from.player[b]) return;\n\t\tmatch[a] = b;\n\t\tfor (let e = 0; e < to.numEdges[a]; e++) {\n\t\t\tconst edge = to.firstEdge[a] + e;\n\t\t\tconst other = matchEdge(to, edge, a, from, b);\n\t\t\tif (other >= 0) walk(to.edgeChild[edge], from.edgeChild[other]);\n\t\t}\n\t};\n\twalk(0, 0);\n\treturn match;\n}\n\nfunction matchEdge(to: Tree, edge: number, node: number, from: Tree, other: number): number {\n\tconst kind = to.edgeAction[edge];\n\tconst sized = kind === ActionKind.Bet || kind === ActionKind.Raise;\n\tconst size = to.edgeTarget[edge] / to.pot[node];\n\tlet best = -1;\n\tlet bestGap = Infinity;\n\tfor (let e = 0; e < from.numEdges[other]; e++) {\n\t\tconst candidate = from.firstEdge[other] + e;\n\t\tif (from.edgeAction[candidate] !== kind) continue;\n\t\tif (!sized) return candidate;\n\t\tconst gap = Math.abs(Math.log(from.edgeTarget[candidate] / from.pot[other] / size));\n\t\tif (gap < bestGap) {\n\t\t\tbestGap = gap;\n\t\t\tbest = candidate;\n\t\t}\n\t}\n\treturn bestGap <= Math.log(SIZE_TOLERANCE) ? best : -1;\n}\n\n/** Read one block — a node on a board — as plain numbers, `actions * count` of them. */\nfunction readBlock(\n\tstore: RegretStore | SumStore,\n\tscale: Float64Array | null,\n\tblock: number,\n\tbase: number,\n\tlength: number,\n\tout: Float64Array,\n): void {\n\tconst factor = scale ? scale[block] : 1;\n\tfor (let i = 0; i < length; i++) out[i] = store[base + i] * factor;\n}\n\n/** Write one block, re-encoding it when storage is 16-bit. */\nfunction writeBlock(\n\tstore: RegretStore | SumStore,\n\tscale: Float64Array | null,\n\tsteps: number,\n\tblock: number,\n\tbase: number,\n\tlength: number,\n\tvalues: Float64Array,\n): void {\n\tif (!scale) {\n\t\tfor (let i = 0; i < length; i++) store[base + i] = values[i];\n\t\treturn;\n\t}\n\tlet largest = 0;\n\tfor (let i = 0; i < length; i++) {\n\t\tconst magnitude = Math.abs(values[i]);\n\t\tif (magnitude > largest) largest = magnitude;\n\t}\n\tconst step = largest > 0 ? steps / largest : 0;\n\tfor (let i = 0; i < length; i++) store[base + i] = Math.round(values[i] * step);\n\tscale[block] = largest / steps;\n}\n\n/** The real cards of a stored board. */\nfunction realCards(runouts: Runouts, round: number, board: number): number[] {\n\tconst width = runouts.width[round];\n\treturn Array.from(runouts.cards[round].subarray(board * width, (board + 1) * width));\n}\n\n/**\n * Seed `to` from `from`. Both must be built on the same board.\n *\n * @returns what matched\n * @throws if the boards differ\n */\nexport function warmStart(to: Context, from: Context, averages: boolean): WarmStartReport {\n\tconst a = to.runouts.initial;\n\tconst b = from.runouts.initial;\n\tif (a.length !== b.length || a.some((card, i) => card !== b[i])) {\n\t\tthrow new Error('A warm start must come from a solve of the same board');\n\t}\n\tconst match = matchNodes(to.tree, from.tree);\n\tconst { tree } = to;\n\tconst width = to.layout.maxActions * COMBOS;\n\tconst oldRegret = new Float64Array(width);\n\tconst oldSum = new Float64Array(width);\n\tconst newRegret = new Float64Array(width);\n\tconst newSum = new Float64Array(width);\n\tconst hasRegret = to.regret.length > 0 && from.regret.length > 0;\n\n\tlet matched = 0;\n\tfor (const node of tree.decisionNodes) {\n\t\tconst old = match[node];\n\t\tif (old < 0) continue;\n\t\tmatched++;\n\t\tconst round = tree.round[node];\n\t\tconst owner = tree.player[node];\n\t\tconst actions = tree.numEdges[node];\n\t\tconst oldActions = from.tree.numEdges[old];\n\t\tconst index = to.players[owner];\n\t\tconst oldIndex = from.players[owner];\n\n\t\t// Which old action each new one continues.\n\t\tconst actionOf = new Int32Array(actions).fill(-1);\n\t\tfor (let e = 0; e < actions; e++) {\n\t\t\tconst other = matchEdge(tree, tree.firstEdge[node] + e, node, from.tree, old);\n\t\t\tif (other >= 0) actionOf[e] = other - from.tree.firstEdge[old];\n\t\t}\n\n\t\tfor (let board = 0; board < to.runouts.counts[round]; board++) {\n\t\t\tconst resolved = resolveBoard(from.runouts, realCards(to.runouts, round, board));\n\t\t\tconst oldBlock = from.layout.blockOffset[old] + resolved.board;\n\t\t\tconst oldBase = from.layout.offset[old] + resolved.board * oldActions * oldIndex.count;\n\t\t\tconst oldLength = oldActions * oldIndex.count;\n\t\t\tif (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);\n\t\t\treadBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);\n\n\t\t\tconst length = actions * index.count;\n\t\t\tnewRegret.fill(0, 0, length);\n\t\t\tnewSum.fill(0, 0, length);\n\t\t\tfor (let i = 0; i < index.count; i++) {\n\t\t\t\tconst slot = oldIndex.slot[resolved.combos[index.combos[i]]];\n\t\t\t\tif (slot < 0) continue;\n\t\t\t\tfor (let e = 0; e < actions; e++) {\n\t\t\t\t\tconst action = actionOf[e];\n\t\t\t\t\tif (action < 0) continue;\n\t\t\t\t\tnewRegret[e * index.count + i] = oldRegret[action * oldIndex.count + slot];\n\t\t\t\t\tnewSum[e * index.count + i] = oldSum[action * oldIndex.count + slot];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst block = to.layout.blockOffset[node] + board;\n\t\t\tconst base = to.layout.offset[node] + board * length;\n\t\t\tif (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS, block, base, length, newRegret);\n\t\t\tif (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS, block, base, length, newSum);\n\t\t\t// The old solve may not have kept mirrored hands equal; this one must.\n\t\t\ttieBlock(to, node, board);\n\t\t}\n\t}\n\treturn { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };\n}\n","/**\n * Browser platform.\n *\n * Purpose: stand in for `node.ts` in a browser build, with the same exports.\n *\n * The browser build is for small solves — river and toy spots — so it is\n * single-threaded: no worker threads, no SharedArrayBuffer, and so no\n * cross-origin isolation headers needed on the page. Run the solve inside a\n * Web Worker to keep the page responsive; see `examples/browser-worker.ts`.\n */\n\nimport type { WorkerSetup } from '../parallel.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'browser';\n\n/** Whether `workers > 1` can be honoured here. */\nexport const THREADS_AVAILABLE = false;\n\n/**\n * Default ceiling on solver storage. A tab gets far less memory than a Node\n * process, so an accidental flop solve fails fast with a clear message rather\n * than taking the tab down.\n */\nexport const DEFAULT_MAX_BYTES = 512 * 1024 * 1024;\n\n/** A spawned solver thread. */\nexport interface WorkerHandle {\n\tterminate(): void;\n}\n\n/** Always one: the browser build solves on the calling thread. */\nexport function defaultWorkerCount(): number {\n\treturn 1;\n}\n\n/** Never called: `createRun` resolves to one thread before planning a pool. */\nexport function spawnWorker(_setup: WorkerSetup, _onError: (error: Error) => void): WorkerHandle {\n\tthrow new Error('Worker threads are only available in the Node build; use workers: 1 in the browser');\n}\n","/**\n * Worker-thread parallelism.\n *\n * Purpose: the one place solving is split across cores.\n *\n * The split is by RUNOUT, at the first round with more than one board. Storage\n * is indexed runout-outermost, so each worker owns a disjoint slice of the\n * shared regret and strategy arrays and never needs a lock for anything below\n * that round.\n *\n * The round ABOVE the split is the exception: its regret update needs the value\n * summed over every runout, and CFR+ clamps at zero, which is not linear, so\n * partial updates cannot simply be added. That round stays on the main thread,\n * which walks it twice per traversal — once to collect the reach vectors the\n * workers need, once to apply updates from the totals they returned. It carries\n * a single board, so this costs almost nothing.\n *\n * The main thread takes the first shard itself rather than sleeping while the\n * workers run, so `workers` counts every thread doing the work: two means the\n * main thread and one worker.\n *\n * Every traversal goes through here, not just training: an exploitability\n * check is a full best-response pass, and left single-threaded it would cost\n * as many iterations as there are threads.\n *\n * Coordination is through Atomics rather than messages, so the public solve API\n * stays synchronous.\n *\n * Agreement with a single-threaded solve is to floating point, not bit-for-bit:\n * each worker sums its own slice of runouts before the totals are summed across\n * workers, which is a different association of the same addition.\n */\n\nimport { COMBOS } from './cards.ts';\nimport type { Context, RootTraversal, Solver } from './cfr.ts';\nimport { Mode } from './cfr.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { NodeKind } from './tree.ts';\nimport type { WorkerHandle } from './platform/node.ts';\nimport { spawnWorker } from './platform/node.ts';\n\nexport { defaultWorkerCount } from './platform/node.ts';\n\nexport const CONTROL = {\n\tgeneration: 0,\n\tdone: 1,\n\tcommand: 2,\n\ttraverser: 3,\n\titerWeight: 4,\n\tready: 5,\n\tmode: 6,\n\tsize: 8,\n} as const;\n\nexport const COMMAND = { work: 0, exit: 1 } as const;\n\n/** How the runouts are split and where the cut sits in the tree. */\nexport interface ShardPlan {\n\treadonly round: number;\n\treadonly boards: number;\n\t/** Chance nodes feeding that round. */\n\treadonly entryNodes: Int32Array;\n\treadonly entryIndexOf: Int32Array;\n\t/** Shard boundaries, `workers + 1` entries; shard 0 is the main thread's. */\n\treadonly bounds: Int32Array;\n}\n\n/**\n * Decide how to split a spot across workers, or null if it is not worth it.\n * @param tree the betting tree\n * @param runouts board completions\n * @param workers worker count\n */\nexport function planShards(tree: Tree, runouts: Runouts, workers: number): ShardPlan | null {\n\tif (workers < 2) return null;\n\tlet round = -1;\n\tfor (let r = 1; r < runouts.rounds; r++) {\n\t\tif (runouts.counts[r] > 1) {\n\t\t\tround = r;\n\t\t\tbreak;\n\t\t}\n\t}\n\t// A river spot has one board and nothing to divide; it also solves instantly.\n\tif (round < 0) return null;\n\n\tconst boards = runouts.counts[round];\n\tif (boards < workers * 2) return null;\n\n\tconst entryIndexOf = new Int32Array(tree.nodeCount).fill(-1);\n\tconst entryNodes: number[] = [];\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (tree.kind[node] !== NodeKind.Chance) continue;\n\t\tif (tree.round[node] + 1 !== round) continue;\n\t\tentryIndexOf[node] = entryNodes.length;\n\t\tentryNodes.push(node);\n\t}\n\tif (entryNodes.length === 0) return null;\n\n\tconst bounds = new Int32Array(workers + 1);\n\tfor (let w = 0; w <= workers; w++) bounds[w] = Math.round((boards * w) / workers);\n\n\treturn { round, boards, entryNodes: Int32Array.from(entryNodes), entryIndexOf, bounds };\n}\n\n/** Everything a worker needs to rebuild the solver. */\nexport interface WorkerSetup {\n\t/** Index among the spawned threads; this worker owns shard `workerId + 1`. */\n\treadonly workerId: number;\n\treadonly payload: unknown;\n\treadonly plan: { round: number; entryNodes: Int32Array; entryIndexOf: Int32Array };\n\treadonly shardStart: number;\n\treadonly shardEnd: number;\n\treadonly regret: SharedArrayBuffer;\n\treadonly strategySum: SharedArrayBuffer;\n\t/** Per-block scales, for 16-bit storage only. */\n\treadonly regretScale: SharedArrayBuffer | null;\n\treadonly sumScale: SharedArrayBuffer | null;\n\treadonly control: SharedArrayBuffer;\n\treadonly exchange: SharedArrayBuffer;\n\treadonly entryCount: number;\n}\n\n/** A running pool of solver workers. */\nexport interface Pool {\n\t/** One traversal for one traverser, returning the root value vector. */\n\treadonly traverse: RootTraversal;\n\tclose(): void;\n\t/** Threads doing the work, the main thread included. */\n\treadonly workers: number;\n}\n\n/**\n * Start a worker pool.\n *\n * @param ctx solver context, whose accumulators must be SharedArrayBuffer backed\n * @param solver single-threaded solver, used for the round above the split\n * @param plan how the runouts are split\n * @param payload everything the worker needs to rebuild the context\n * @param workers threads doing the work, the main thread included\n */\nexport function startPool(\n\tctx: Context,\n\tsolver: Solver,\n\tplan: ShardPlan,\n\tpayload: unknown,\n\tworkers: number,\n): Pool {\n\tconst entryCount = plan.entryNodes.length;\n\t// The main thread is one of the `workers`; only the rest are spawned.\n\tconst spawned = workers - 1;\n\tconst reachFloats = entryCount * 2 * COMBOS;\n\tconst partialFloats = spawned * entryCount * COMBOS;\n\tconst exchangeBuffer = new SharedArrayBuffer((reachFloats + partialFloats) * 8);\n\tconst exchange = new Float64Array(exchangeBuffer);\n\tconst controlBuffer = new SharedArrayBuffer(CONTROL.size * 4);\n\tconst control = new Int32Array(controlBuffer);\n\n\tconst threads: WorkerHandle[] = [];\n\tlet failure: Error | null = null;\n\n\tfor (let w = 0; w < spawned; w++) {\n\t\tconst setup: WorkerSetup = {\n\t\t\tworkerId: w,\n\t\t\tpayload,\n\t\t\tplan: { round: plan.round, entryNodes: plan.entryNodes, entryIndexOf: plan.entryIndexOf },\n\t\t\tshardStart: plan.bounds[w + 1],\n\t\t\tshardEnd: plan.bounds[w + 2],\n\t\t\tregret: ctx.regret.buffer as SharedArrayBuffer,\n\t\t\tstrategySum: ctx.strategySum.buffer as SharedArrayBuffer,\n\t\t\tregretScale: (ctx.regretScale?.buffer as SharedArrayBuffer | undefined) ?? null,\n\t\t\tsumScale: (ctx.sumScale?.buffer as SharedArrayBuffer | undefined) ?? null,\n\t\t\tcontrol: controlBuffer,\n\t\t\texchange: exchangeBuffer,\n\t\t\tentryCount,\n\t\t};\n\t\t// A worker that dies would otherwise leave the main thread waiting on a\n\t\t// counter that can never reach its target.\n\t\tconst thread = spawnWorker(setup, (error: Error) => {\n\t\t\tfailure ??= error;\n\t\t\tAtomics.store(control, CONTROL.ready, spawned);\n\t\t\tAtomics.add(control, CONTROL.done, spawned);\n\t\t\tAtomics.notify(control, CONTROL.done);\n\t\t\tAtomics.notify(control, CONTROL.ready);\n\t\t});\n\t\tthreads.push(thread);\n\t}\n\n\t// Barrier: a worker that started after the first dispatch would never see\n\t// the generation change, and the pool would deadlock.\n\tfor (;;) {\n\t\tconst ready = Atomics.load(control, CONTROL.ready);\n\t\tif (ready >= spawned || failure) break;\n\t\tAtomics.wait(control, CONTROL.ready, ready, 20);\n\t}\n\tif (failure) {\n\t\tfor (const thread of threads) thread.terminate();\n\t\tthrow failure;\n\t}\n\n\tconst total = new Float64Array(COMBOS);\n\tconst chanceValues = new Float64Array(entryCount * COMBOS);\n\n\tconst mainReachMe = new Float64Array(COMBOS);\n\tconst mainReachOpp = new Float64Array(COMBOS);\n\n\tconst dispatch = (mode: Mode, traverser: 0 | 1, iterWeight: number): void => {\n\t\tAtomics.store(control, CONTROL.done, 0);\n\t\tAtomics.store(control, CONTROL.mode, mode);\n\t\tAtomics.store(control, CONTROL.traverser, traverser);\n\t\tAtomics.store(control, CONTROL.iterWeight, iterWeight);\n\t\tAtomics.store(control, CONTROL.command, COMMAND.work);\n\t\tAtomics.add(control, CONTROL.generation, 1);\n\t\tAtomics.notify(control, CONTROL.generation);\n\n\t\t// Shard 0 is this thread's, done while the workers do theirs. With no\n\t\t// collect or override set the split-round chance nodes expand as usual,\n\t\t// over whatever slice the context names.\n\t\tconst fullStart = ctx.shardStart;\n\t\tconst fullEnd = ctx.shardEnd;\n\t\tctx.shardStart = plan.bounds[0];\n\t\tctx.shardEnd = plan.bounds[1];\n\t\t// Pass A left updates off; below the split they are this shard's own.\n\t\tctx.applyUpdates = true;\n\t\ttry {\n\t\t\tfor (let entry = 0; entry < entryCount; entry++) {\n\t\t\t\tfor (let i = 0; i < COMBOS; i++) {\n\t\t\t\t\tmainReachMe[i] = exchange[entry * 2 * COMBOS + i];\n\t\t\t\t\tmainReachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];\n\t\t\t\t}\n\t\t\t\tconst value = solver.traverseChance(\n\t\t\t\t\tmode, traverser, iterWeight, plan.entryNodes[entry], mainReachMe, mainReachOpp,\n\t\t\t\t);\n\t\t\t\tchanceValues.set(value.subarray(0, COMBOS), entry * COMBOS);\n\t\t\t}\n\t\t} finally {\n\t\t\tctx.shardStart = fullStart;\n\t\t\tctx.shardEnd = fullEnd;\n\t\t}\n\n\t\tfor (;;) {\n\t\t\tconst done = Atomics.load(control, CONTROL.done);\n\t\t\tif (done >= spawned) break;\n\t\t\tif (failure) throw failure;\n\t\t\tAtomics.wait(control, CONTROL.done, done, 50);\n\t\t}\n\t\tif (failure) throw failure;\n\t};\n\n\treturn {\n\t\tworkers,\n\t\ttraverse(mode, traverser, iterWeight) {\n\t\t\t// Pass A: walk the round above the split to capture what each worker\n\t\t\t// needs, applying nothing.\n\t\t\tctx.applyUpdates = false;\n\t\t\tctx.chanceOverride = null;\n\t\t\tctx.chanceCollect = (node, reachMe, reachOpp) => {\n\t\t\t\tconst entry = plan.entryIndexOf[node];\n\t\t\t\texchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);\n\t\t\t\texchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tsolver.traverseRoot(mode, traverser, iterWeight);\n\t\t\t} finally {\n\t\t\t\tctx.chanceCollect = null;\n\t\t\t}\n\n\t\t\t// Leaves this thread's own partial in `chanceValues`.\n\t\t\tdispatch(mode, traverser, iterWeight);\n\n\t\t\tfor (let w = 0; w < spawned; w++) {\n\t\t\t\tconst base = reachFloats + w * entryCount * COMBOS;\n\t\t\t\tfor (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];\n\t\t\t}\n\n\t\t\t// Pass B: finish that round from the totals, now applying updates.\n\t\t\tctx.chanceOverride = chanceValues;\n\t\t\tctx.applyUpdates = true;\n\t\t\ttry {\n\t\t\t\tconst value = solver.traverseRoot(mode, traverser, iterWeight);\n\t\t\t\ttotal.set(value.subarray(0, COMBOS));\n\t\t\t} finally {\n\t\t\t\tctx.chanceOverride = null;\n\t\t\t}\n\t\t\treturn total;\n\t\t},\n\t\tclose() {\n\t\t\tAtomics.store(control, CONTROL.command, COMMAND.exit);\n\t\t\tAtomics.add(control, CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, CONTROL.generation);\n\t\t\tfor (const thread of threads) thread.terminate();\n\t\t},\n\t};\n}\n","/**\n * Postflop Texas Hold'em solver.\n *\n * Purpose: the public surface. Give it a board, a pot, stacks, two ranges and a\n * betting scheme; it solves to showdown.\n *\n * There is no preflop round. The ranges you supply already encode whatever spot\n * you are in, so the solver starts from a dead pot with both players even.\n */\n\nimport { COMBO_CARDS, COMBOS, comboIndex, formatCards, parseCards } from './cards.ts';\nimport type { BetSize, RaiseSizes, Tree } from './tree.ts';\nimport { ACTION_LABELS, ActionKind, buildTree, NodeKind, raisesPerRound } from './tree.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { ResolvedBoard } from './runouts.ts';\nimport type { RunoutMerge } from './runouts.ts';\nimport { boardAtRound, enumerateRunouts, rankSwap, resolveBoard } from './runouts.ts';\nimport { suitSymmetries } from './abstraction.ts';\nimport { activeCombos, parseRange, rangeWeight } from './range.ts';\nimport { buildShowdownTable } from './showdown.ts';\nimport type { WarmStartReport } from './warm.ts';\nimport { warmStart } from './warm.ts';\nimport type { Pool } from './parallel.ts';\nimport { defaultWorkerCount, planShards, startPool } from './parallel.ts';\nimport { DEFAULT_MAX_BYTES, PLATFORM, THREADS_AVAILABLE } from './platform/node.ts';\nimport type { Context, PlayerIndex, RegretStore, Solver, SumStore } from './cfr.ts';\nimport {\n\tbuildActiveLists,\n\tbuildLayout,\n\tbuildPlayerIndex,\n\tmakeSolver,\n\tmakeTerminalScratch,\n\tmatchupMass,\n\trunoutWeights,\n} from './cfr.ts';\n\nexport * from './cards.ts';\nexport * from './eval7.ts';\nexport { activeCombos, parseRange, rangeWeight } from './range.ts';\nexport type { ResolvedBoard } from './runouts.ts';\nexport type { WarmStartReport } from './warm.ts';\nexport { simdAvailable } from './kernels.ts';\nexport type { BetSize } from './tree.ts';\nexport type { Solver } from './cfr.ts';\nexport { ACTION_LABELS, ActionKind, NodeKind } from './tree.ts';\n/** 'node' or 'browser': which build is running. */\nexport { PLATFORM } from './platform/node.ts';\n\n/** Sub-chip resolution, so pot-fraction sizing is exact. */\nconst DEFAULT_CHIP_SCALE = 100;\n\n/** Measured throughput on a warm run, used only to project solve time. */\nconst OPS_PER_SECOND = 2e8;\n\n/** A spot to solve. */\nexport interface SpotConfig {\n\t/** 3, 4 or 5 cards, e.g. \"AsKh7d\" or \"As Kh 7d 2c\". */\n\treadonly board: string;\n\t/** Dead money already in the middle, in chips. */\n\treadonly pot: number;\n\t/** Effective stack behind, per player, in chips. */\n\treadonly stack: number;\n\t/**\n\t * The out-of-position player's range, who acts first: range notation, or\n\t * a weight per combination indexed like `COMBO_CARDS`, as\n\t * `Solution.subgameAt` produces.\n\t */\n\treadonly oop: string | Float64Array;\n\t/** The in-position player's range, in either form. */\n\treadonly ip: string | Float64Array;\n\t/** Bet sizes per betting round; a single row applies to every round. */\n\treadonly betSizes: readonly (readonly BetSize[])[];\n\t/**\n\t * Sizes offered when facing a bet; unset, raises use the bet sizes. One\n\t * row for every round, or a row per round like `betSizes`.\n\t */\n\treadonly raiseSizes?: RaiseSizes;\n\t/**\n\t * Maximum aggressive actions per round; the opening bet is the first.\n\t * One number, or one per round. Default 1.\n\t */\n\treadonly maxRaises?: number | readonly number[];\n\t/** Offer a shove alongside the configured sizes; once, or per round. Default false. */\n\treadonly allowAllIn?: boolean | readonly boolean[];\n\t/**\n\t * Turn a bet or raise into a shove when it would commit at least this\n\t * fraction of the actor's remaining stack — 0.67 makes any bet of two\n\t * thirds of what is left an all-in. Trims the near-all-in lines that\n\t * multiply a tree for little strategic difference. Once, or per round.\n\t * Unset, never.\n\t */\n\treadonly allInThreshold?: number | readonly number[];\n\t/**\n\t * Forbid donk bets: out of position may only check when opening a round\n\t * into the player who made the last bet or raise of the round before.\n\t * Once, or per round. Default false.\n\t */\n\treadonly noDonk?: boolean | readonly boolean[];\n\t/**\n\t * Collapse pot-fraction sizes closer together than this into their mean:\n\t * with 0.1, sizes 0.33 and 0.4 become one 0.365. Default 0, none.\n\t */\n\treadonly mergeSizes?: number;\n\t/** Refuse a range wider than this many combinations. */\n\treadonly maxCombos?: number;\n\t/**\n\t * Drop combinations weighted below this from both ranges. Imported ranges\n\t * are often full of hands at a few percent that barely move the answer\n\t * but cost as much as any other; this removes them. It edits the ranges,\n\t * so it changes the game being solved. Default 0, keep everything.\n\t */\n\treadonly minWeight?: number;\n\t/**\n\t * Refuse a spot needing more than this much storage. Defaults to 6 GiB in\n\t * the Node build and 512 MiB in the browser build, where a tab has far less\n\t * to give.\n\t */\n\treadonly maxBytes?: number;\n\treadonly chipScale?: number;\n\t/**\n\t * Fold mirror-image runouts together. When the board and both ranges are\n\t * unchanged by swapping some suits — two suits absent from a two-tone flop,\n\t * three from a monotone one — a deal in one of those suits is the mirror\n\t * image of a deal in another, so only one is solved and it stands for both.\n\t * Exact, not an approximation: strategies on a mirrored runout are the\n\t * stored ones relabelled. Default true; ranges that differ between suits\n\t * anywhere simply have no symmetry to use.\n\t */\n\treadonly isomorphism?: boolean;\n\t/**\n\t * Solve one turn or river card for several that play alike — an\n\t * approximation. Two cards of one suit are bucketed together when neither\n\t * pairs the board, they connect equally to its straights, and swapping\n\t * their ranks maps each range onto itself (so `98s` in a range keeps an 8\n\t * and a 9 apart). The stored card stands for the others with hands\n\t * relabelled by that swap. How much it saves depends on the ranges: with\n\t * pairs and broadway hands most low cards bucket together; suited\n\t * connectors keep them apart. `trueExploitabilityPercent()` measures the\n\t * strategy in the real game, every card dealt. Default false.\n\t */\n\treadonly runoutBuckets?: boolean | number;\n}\n\n/** Projected cost of solving a spot. */\nexport interface Estimate {\n\treadonly rounds: number;\n\t/**\n\t * Final boards stored. With `isomorphism` a mirrored runout is not\n\t * stored, so this can be well under the number of real runouts.\n\t */\n\treadonly runouts: number;\n\treadonly combos: readonly [number, number];\n\treadonly decisionNodes: number;\n\treadonly totalSlots: number;\n\t/** Storage at 32-bit precision, the default for any sizeable spot. */\n\treadonly bytes: number;\n\t/**\n\t * Storage at 16-bit precision, a little over half of `bytes`; what a spot\n\t * that does not fit at 32 bits is solved with.\n\t */\n\treadonly compressedBytes: number;\n\treadonly secondsPerThousandIterations: number;\n\t/** Whether the spot fits `maxBytes` at 16 bits or better. */\n\treadonly fits: boolean;\n\treadonly suggestions: readonly string[];\n}\n\n/** Thrown when a spot would need more memory than allowed. */\nexport class SpotTooLargeError extends Error {\n\treadonly estimate: Estimate;\n\tconstructor(estimate: Estimate, maxBytes: number) {\n\t\tsuper(\n\t\t\t`This spot needs ~${formatBytes(estimate.compressedBytes)} even at 16-bit precision, ` +\n\t\t\t\t`but the limit is ${formatBytes(maxBytes)}.\\n` +\n\t\t\t\t` ${estimate.decisionNodes} decision nodes x up to ${estimate.runouts.toLocaleString()} runouts ` +\n\t\t\t\t`x ${Math.max(...estimate.combos)} combos.\\n` +\n\t\t\t\t(estimate.suggestions.length\n\t\t\t\t\t? `Try:\\n${estimate.suggestions.map((s) => ` - ${s}`).join('\\n')}\\n`\n\t\t\t\t\t: '') +\n\t\t\t\t'Raise the ceiling with `maxBytes` if you have the memory.',\n\t\t);\n\t\tthis.name = 'SpotTooLargeError';\n\t\tthis.estimate = estimate;\n\t}\n}\n\nfunction formatBytes(bytes: number): string {\n\tconst units = ['B', 'KB', 'MB', 'GB', 'TB'];\n\tlet value = bytes;\n\tlet unit = 0;\n\twhile (value >= 1024 && unit < units.length - 1) {\n\t\tvalue /= 1024;\n\t\tunit++;\n\t}\n\treturn `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;\n}\n\n/** A prepared spot, ready to solve. */\nexport interface Spot {\n\treadonly board: number[];\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly estimate: Estimate;\n\treadonly chipScale: number;\n\treadonly potUnits: number;\n\treadonly stackUnits: number;\n\t/** The configuration this was built from, so a worker can rebuild it. */\n\treadonly source: SpotConfig;\n\t/**\n\t * Find the stored board standing for a real one, and how hands relabel\n\t * onto it. Board indices everywhere else — `strategyAt`, `reachAt`,\n\t * `subgameAt` — index stored boards; with `isomorphism` a mirrored runout\n\t * is not stored, and this is how to read it.\n\t *\n\t * @param board the spot's board followed by the cards dealt, in order\n\t */\n\tresolveBoard(board: string | readonly number[]): ResolvedBoard;\n}\n\n/**\n * Validate a spot and build everything needed to solve it.\n * @throws {SpotTooLargeError} when it would exceed the memory ceiling\n */\nexport function defineSpot(config: SpotConfig): Spot {\n\tconst chipScale = config.chipScale ?? DEFAULT_CHIP_SCALE;\n\tconst maxBytes = config.maxBytes ?? DEFAULT_MAX_BYTES;\n\tconst board = parseCards(config.board);\n\tif (board.length < 3 || board.length > 5) {\n\t\tthrow new Error(`A postflop board has 3, 4 or 5 cards; got ${board.length} (${formatCards(board)})`);\n\t}\n\tconst rounds = 6 - board.length;\n\n\tif (config.pot <= 0) throw new Error('pot must be positive');\n\tif (config.stack <= 0) throw new Error('stack must be positive');\n\n\tconst rows =\n\t\tconfig.betSizes.length === 1\n\t\t\t? Array.from({ length: rounds }, () => config.betSizes[0])\n\t\t\t: config.betSizes;\n\tif (rows.length !== rounds) {\n\t\tthrow new Error(\n\t\t\t`betSizes has ${config.betSizes.length} rows but this board has ${rounds} ` +\n\t\t\t\t'betting rounds; give one row per round, or a single row for all of them',\n\t\t);\n\t}\n\n\t// Board cards cannot be in anyone's range.\n\tconst onBoard = new Set(board);\n\tconst trim = (range: string | Float64Array, who: string): Float64Array => {\n\t\tconst weights = typeof range === 'string' ? parseRange(range) : Float64Array.from(range);\n\t\tif (weights.length !== COMBOS) {\n\t\t\tthrow new Error(`The ${who} range has ${weights.length} weights; one per combination is ${COMBOS}`);\n\t\t}\n\t\tconst floor = config.minWeight ?? 0;\n\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\tif (weights[combo] === 0) continue;\n\t\t\tif (onBoard.has(COMBO_CARDS[combo * 2]) || onBoard.has(COMBO_CARDS[combo * 2 + 1])) {\n\t\t\t\tweights[combo] = 0;\n\t\t\t} else if (weights[combo] < floor) {\n\t\t\t\tweights[combo] = 0;\n\t\t\t}\n\t\t}\n\t\tconst live = activeCombos(weights).length;\n\t\tif (live === 0) throw new Error(`The ${who} range is empty once the board is removed`);\n\t\tif (config.maxCombos !== undefined && live > config.maxCombos) {\n\t\t\tthrow new Error(\n\t\t\t\t`The ${who} range has ${live} combinations, over the ${config.maxCombos} limit. ` +\n\t\t\t\t\t'Narrow the range or raise `maxCombos`.',\n\t\t\t);\n\t\t}\n\t\treturn weights;\n\t};\n\n\tconst players: [PlayerIndex, PlayerIndex] = [\n\t\tbuildPlayerIndex(trim(config.oop, 'out-of-position')),\n\t\tbuildPlayerIndex(trim(config.ip, 'in-position')),\n\t];\n\n\t// Symmetry needs the ranges, so the runouts come after them.\n\tconst symmetries =\n\t\tconfig.isomorphism === false || board.length === 5\n\t\t\t? undefined\n\t\t\t: suitSymmetries(board, [players[0].weights, players[1].weights]);\n\tconst runouts = enumerateRunouts(\n\t\tboard,\n\t\tsymmetries,\n\t\tconfig.runoutBuckets && board.length < 5\n\t\t\t? rangeRankMerge(players, config.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config.runoutBuckets)\n\t\t\t: undefined,\n\t);\n\n\tconst tree = buildTree(\n\t\t{\n\t\t\tpotUnits: Math.round(config.pot * chipScale),\n\t\t\tstackUnits: Math.round(config.stack * chipScale),\n\t\t\tbetSizes: rows,\n\t\t\traiseSizes: config.raiseSizes,\n\t\t\tmaxRaises: config.maxRaises ?? 1,\n\t\t\tallowAllIn: config.allowAllIn ?? false,\n\t\t\tallInThreshold: config.allInThreshold,\n\t\t\tnoDonk: config.noDonk,\n\t\t\tmergeSizes: config.mergeSizes,\n\t\t\tchipScale,\n\t\t\tminRaiseUnits: chipScale,\n\t\t},\n\t\trunouts,\n\t);\n\n\tconst layout = buildLayout(tree, runouts, players, 4);\n\tconst last = runouts.rounds - 1;\n\tconst showdownBytes = runouts.counts[last] * (2 * COMBOS + COMBOS + 1) * 2;\n\tconst bytes = layout.bytes + showdownBytes;\n\tconst compressedBytes = buildLayout(tree, runouts, players, 2).bytes + showdownBytes;\n\n\tconst suggestions: string[] = [];\n\tif (compressedBytes > maxBytes) {\n\t\tconst widest = Math.max(...rows.map((r) => r.length));\n\t\tif (widest > 1) suggestions.push(`use fewer bet sizes (currently up to ${widest} per round)`);\n\t\tif (Math.max(...[config.maxRaises ?? 1].flat()) > 1) suggestions.push(`lower maxRaises to 1`);\n\t\tsuggestions.push(`narrow the ranges (currently ${players[0].count} and ${players[1].count} combos)`);\n\t\tif (runouts.rounds === 3) suggestions.push('solve from the turn instead of the flop');\n\t}\n\n\tconst estimate: Estimate = {\n\t\trounds: runouts.rounds,\n\t\trunouts: runouts.counts[last],\n\t\tcombos: [players[0].count, players[1].count],\n\t\tdecisionNodes: tree.decisionNodes.length,\n\t\ttotalSlots: layout.totalSlots,\n\t\tbytes,\n\t\tcompressedBytes,\n\t\tsecondsPerThousandIterations: (layout.totalSlots * 4 * 1000) / OPS_PER_SECOND,\n\t\tfits: compressedBytes <= maxBytes,\n\t\tsuggestions,\n\t};\n\tif (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);\n\n\treturn {\n\t\tboard,\n\t\ttree,\n\t\trunouts,\n\t\tplayers,\n\t\testimate,\n\t\tchipScale,\n\t\tpotUnits: Math.round(config.pot * chipScale),\n\t\tstackUnits: Math.round(config.stack * chipScale),\n\t\tsource: config,\n\t\tresolveBoard(cards) {\n\t\t\treturn resolveBoard(runouts, typeof cards === 'string' ? parseCards(cards) : cards);\n\t\t},\n\t};\n}\n\n/** Solver tuning. */\nexport interface SolveOptions {\n\t/**\n\t * Iterations to run. With `targetPercent` set this is only a cap, and the\n\t * solve normally stops well before it; `stoppedAt` on the result says which\n\t * of the two ended it.\n\t */\n\treadonly iterations?: number;\n\t/**\n\t * Stop once exploitability falls to this percentage of the pot — the\n\t * accuracy knob, and the cheapest way to cut solve time.\n\t *\n\t * Solvers conventionally quote accuracy this way, and it is the only form\n\t * comparable between spots of different sizes. As a rough guide, 1% of pot\n\t * is a sketch, 0.5% is enough to read strategies off, 0.1% is publishable\n\t * and costs several times as long.\n\t *\n\t * Checking is not free — see `exploitEvery` — so the solve overshoots the\n\t * target slightly rather than stopping on the exact iteration it was met.\n\t */\n\treadonly targetPercent?: number;\n\t/**\n\t * Measure exploitability every N iterations. Each costs about one iteration,\n\t * because it is a full best-response pass for both players.\n\t *\n\t * Left unset with `targetPercent` given, checks are scheduled by predicting\n\t * when the target will be met rather than at any fixed cadence — see\n\t * `nextCheck`. Setting this forces a fixed cadence instead.\n\t */\n\treadonly exploitEvery?: number;\n\treadonly onProgress?: (info: Progress) => void;\n\t/**\n\t * Accumulator storage. Unset, a small spot uses 'f64', a larger one 'f32',\n\t * and one too big for either under the spot's `maxBytes` uses 'i16'.\n\t *\n\t * 'i16' stores regrets and strategy sums as 16-bit integers with one scale\n\t * per node and board, about halving memory. It is for fitting a spot, not\n\t * for speed: the solver is compute-bound, and re-encoding each block on\n\t * update costs a little time per iteration.\n\t */\n\treadonly precision?: Precision;\n\t/**\n\t * Threads to split the runouts across, the calling thread included: 2 is\n\t * the caller and one worker. 1 stays single-threaded; 'auto' picks a count\n\t * from the machine. Exploitability and EV passes use them too.\n\t *\n\t * A fixed worker count is bitwise deterministic, but CHANGING it moves the\n\t * answer slightly: a worker sums its own slice of runouts before the totals\n\t * are summed across workers, which associates the same addition\n\t * differently, and the non-linear clamp in CFR+ compounds that rounding.\n\t * Measured here it sits at 1e-15 through three hundred iterations and\n\t * reaches 1e-7 by two thousand — always orders of magnitude under the\n\t * exploitability, so never the largest error in the answer, but do not\n\t * expect two worker counts to agree bit for bit.\n\t *\n\t * The browser build is single-threaded: any count resolves to 1 there.\n\t */\n\treadonly workers?: number | 'auto';\n\t/**\n\t * The update rule. 'dcfr' (the default) is Discounted CFR, which discounts\n\t * old regrets and weights recent iterations more heavily; measured, it\n\t * reaches 0.3% of pot in 35–45% fewer iterations than 'cfr+' on river,\n\t * turn and flop spots alike. 'cfr+' clamps regrets at zero and weights\n\t * iteration `t` by `t` in the average.\n\t *\n\t * Predictive Discounted CFR+ (Xu et al., 2024) was implemented and measured\n\t * against 'dcfr' and is not offered: at the paper's parameters (α 2.3,\n\t * γ 5) it took 165 iterations to 0.3% of pot on the bench turn spot where\n\t * 'dcfr' takes 85, and 120 to 65 on the river; no α, γ tried (1 to 2.3, 2\n\t * to 5) came close, with or without the prediction.\n\t */\n\treadonly algorithm?: Algorithm;\n\t/**\n\t * Allocate only the strategy sums, for loading a saved strategy and\n\t * analysing it. Such a run must never be stepped.\n\t */\n\treadonly analysisOnly?: boolean;\n\t/**\n\t * Start from a previous solve of the same board instead of from nothing.\n\t *\n\t * For re-solving a tweaked spot — another pot or stack, a bet size nudged,\n\t * a range reweighted — whose equilibrium is close to the old one. The\n\t * answer is not approximate: CFR converges from any start, and this one is\n\t * near. Nodes match by the actions leading to them, bet sizes by the\n\t * nearest pot fraction; hands by combination; anything without a match\n\t * starts cold. `SolveRun.warmStart` says how much matched.\n\t *\n\t * Regrets carry over; the average strategy only when the spot is the\n\t * same, which resumes a solve exactly. Measured on a river spot re-solved\n\t * to 0.1% of pot, a nudged bet size took 15 iterations instead of 130 from\n\t * cold, a reweighted range 80 instead of 130, a 20% bigger pot 100\n\t * instead of 125.\n\t */\n\treadonly warmStart?: Solution | SolveRun;\n\t/**\n\t * The iteration to carry on counting from, which sets how heavily DCFR\n\t * discounts the inherited regrets and how CFR+ weights the averages. Unset,\n\t * the old solve's own count: the new solve continues it. Lower it to let\n\t * the new spot's own iterations outweigh the old ones sooner.\n\t */\n\treadonly warmIteration?: number;\n\t/**\n\t * Approximations that keep the game but solve it more cheaply. All off by\n\t * default. Each costs some accuracy, which the exploitability — measured\n\t * exactly, in the full game — shows.\n\t */\n\treadonly approximations?: Approximations;\n\t/**\n\t * Use the WebAssembly SIMD kernels where the platform supports them,\n\t * falling back to JavaScript where it does not. Results are identical\n\t * either way, to the bit; this exists to compare the two. Default true.\n\t */\n\treadonly simd?: boolean;\n}\n\n/** See `SolveOptions.approximations`. */\nexport interface Approximations {\n\t/*\n\t * Threshold pruning — skipping opponent actions taken with negligible\n\t * reach — was built and measured, and is deliberately not offered: a\n\t * threshold on reach mass also skips deep lines that are rare overall but\n\t * matter to the few hands that reach them, their strategy stops training,\n\t * and the best response walks straight into it. On a wide turn spot it\n\t * plateaued near 0.8% of pot where the unpruned solve reached 0.17%, for\n\t * at most 15% less time per iteration.\n\t *\n\t * River hand buckets — one strategy per set of hands of equal strength\n\t * and equal ranks, suits told apart only where a flush is possible — were\n\t * built and measured too, and also left out. The solver updates every hand\n\t * in one vector pass, so fewer separate strategies did not mean fewer\n\t * iterations, while the lost blocker detail put a floor under accuracy:\n\t * 105 iterations to 0.3% of pot on a turn spot instead of 85, and a\n\t * plateau near 0.15% where the exact solve went on to 0.1%.\n\t *\n\t * Chance sampling — walking each river deal in training with probability\n\t * p and weighting it by 1/p, with DCFR discounts caught up for deals left\n\t * out — was built and measured as well. Iterations got cheaper, but the\n\t * sampling noise, which DCFR's weighting of recent iterations amplifies,\n\t * cost more iterations than it saved: a flop spot on 4 threads reached\n\t * 0.3% of pot in 14.1 s exact, 23.1 s at p = 0.5, and not within 400\n\t * iterations at p = 0.25; at best it broke even to 1%.\n\t */\n}\n\nexport type Algorithm = 'cfr+' | 'dcfr';\n\nexport type Precision = 'f64' | 'f32' | 'i16';\n\n/** Bytes per stored value at each precision. */\nexport const PRECISION_BYTES = { f64: 8, f32: 4, i16: 2 } as const;\n\nexport interface Progress {\n\treadonly iteration: number;\n\treadonly exploitability: number;\n\treadonly elapsedMs: number;\n}\n\n/** A solved spot. */\nexport interface Solution {\n\treadonly spot: Spot;\n\t/** Iterations this solve ran. */\n\treadonly iterations: number;\n\t/** Iterations behind the strategy, counting any a warm start inherited. */\n\treadonly totalIterations: number;\n\t/**\n\t * Which stopping rule ended the solve. 'iterations' with a `targetPercent`\n\t * set means the target was NOT reached and the answer is looser than asked\n\t * for — worth surfacing rather than swallowing.\n\t */\n\treadonly stoppedAt: 'target' | 'iterations';\n\t/** Worker threads the solve actually used, which 'auto' does not tell you. */\n\treadonly workers: number;\n\t/** The solver behind this solution, for analysis and warm starts. */\n\treadonly solver: Solver;\n\t/** Chips per hand for a player, under the average strategy. */\n\tev(player: 0 | 1): number;\n\t/** Distance from equilibrium, in chips per hand. */\n\texploitability(): number;\n\t/**\n\t * Distance from equilibrium as a percentage of the pot, which is how\n\t * solvers conventionally report it and the only form comparable between\n\t * spots of different sizes.\n\t */\n\texploitabilityPercent(): number;\n\t/** Action probabilities for every combination this player holds. */\n\tstrategyAt(node: number, board: number): StrategyView;\n\t/** Readable action path to a node. */\n\tpath(node: number): string;\n\t/**\n\t * How likely each combination is to reach a node on a board, for one\n\t * player: their range weight times the probability of every action they\n\t * took on the way, under the average strategy. Indexed by combination.\n\t * The other player's actions do not enter: this is the player's own range\n\t * at the node, not the joint probability of getting there.\n\t */\n\treachAt(node: number, board: number, player: 0 | 1): Float64Array;\n\t/**\n\t * The spot that starts at a node: the board as dealt there, the pot and\n\t * stacks as they stand, and each player's range as `reachAt` gives it.\n\t * Defining and solving it re-solves that part of the game, typically with\n\t * more bet sizes than the whole spot could afford.\n\t *\n\t * This is unsafe re-solving: the subgame is solved for the ranges that\n\t * arrive, so its strategy can be exploited in ways the original solution\n\t * did not allow for. It answers \"how should these ranges play from here\"\n\t * well; it does not make the earlier streets any more accurate.\n\t *\n\t * @param node a decision that opens a betting round after the first, or the root\n\t * @param board the board index at that node's round\n\t * @param betting overrides; unset, the original spot's betting carries over\n\t */\n\tsubgameAt(node: number, board: number, betting?: SubgameBetting): SpotConfig;\n\treadonly history: readonly Progress[];\n}\n\n/** Betting for a subgame; anything unset keeps the original spot's. */\nexport type SubgameBetting = Partial<\n\tPick<\n\t\tSpotConfig,\n\t\t'betSizes' | 'raiseSizes' | 'maxRaises' | 'allowAllIn' | 'allInThreshold' | 'noDonk' | 'mergeSizes' | 'maxCombos' | 'maxBytes'\n\t>\n>;\n\nexport interface StrategyView {\n\treadonly node: number;\n\treadonly board: number;\n\treadonly player: 0 | 1;\n\treadonly actions: readonly string[];\n\treadonly combos: Uint16Array;\n\t/** Row-major `combos.length * actions.length`. */\n\treadonly probs: Float64Array;\n}\n\n/** An in-progress solve the caller drives. */\nexport interface SolveRun {\n\treadonly spot: Spot;\n\t/** Iterations completed so far, by this run; a warm start's are not counted. */\n\treadonly completed: number;\n\t/** Iterations behind the strategy, counting any a warm start inherited. */\n\treadonly totalIterations: number;\n\t/** What a warm start carried over, or null without one. */\n\treadonly warmStart: WarmStartReport | null;\n\t/** Run `count` more iterations. */\n\tstep(count: number): void;\n\t/** Distance from equilibrium as a percentage of the pot. */\n\texploitabilityPercent(): number;\n\t/**\n\t * Exploitability in the real game, every card dealt, as a percentage of\n\t * the pot. The same as `exploitabilityPercent()` unless `runoutBuckets`\n\t * folded cards that are not exact mirror images; then the strategy is\n\t * copied onto every real runout of an unbucketed spot and measured there,\n\t * which costs that spot's memory and one best-response pass over it.\n\t */\n\ttrueExploitabilityPercent(): number;\n\t/** A view of the strategy as it stands; cheap, take a fresh one each time. */\n\tsnapshot(history?: readonly Progress[], stoppedAt?: 'target' | 'iterations'): Solution;\n\t/** Release worker threads. Snapshots taken before this stay usable. */\n\tclose(): void;\n\t/** Worker threads actually in use; 1 when single-threaded. */\n\treadonly workers: number;\n\t/** The underlying solver, for per-node analysis once solving is done. */\n\treadonly solver: Solver;\n}\n\n/**\n * Prepare a solve without running it.\n *\n * Stepping costs nothing over one long call — the work per iteration is\n * identical — and it is what lets a caller report progress or stop early while\n * keeping the partial answer.\n *\n * @param spot from {@link defineSpot}\n * @param options solver setup\n */\nexport function createRun(spot: Spot, options: SolveOptions = {}): SolveRun {\n\t// A saved strategy is loaded as float32 sums, so analysis stays there.\n\tconst maxBytes = spot.source.maxBytes ?? DEFAULT_MAX_BYTES;\n\tconst { totalSlots, bytes } = spot.estimate;\n\tconst precision: Precision = options.analysisOnly\n\t\t? 'f32'\n\t\t: options.precision ??\n\t\t\t(totalSlots < 4_000_000 && bytes * 2 <= maxBytes ? 'f64' : bytes <= maxBytes ? 'f32' : 'i16');\n\n\t// Hands neither player holds never carry reach, so they need no ranking.\n\tconst relevant = new Uint8Array(COMBOS);\n\tfor (const combo of spot.players[0].combos) relevant[combo] = 1;\n\tfor (const combo of spot.players[1].combos) relevant[combo] = 1;\n\n\tconst showdown = buildShowdownTable(spot.runouts, relevant);\n\tconst layout = buildLayout(spot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision]);\n\tconst weights = runoutWeights(spot.runouts);\n\n\tconst requested = resolveWorkers(options);\n\tconst plan = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;\n\n\t// Workers need the accumulators in shared memory. Allocating shared for a\n\t// single-threaded solve would cost nothing but buys nothing either.\n\tconst allocate = (bytes: number): ArrayBuffer | SharedArrayBuffer =>\n\t\tplan ? new SharedArrayBuffer(bytes) : new ArrayBuffer(bytes);\n\tconst width = PRECISION_BYTES[precision];\n\tconst quantised = precision === 'i16';\n\n\tconst ctx: Context = {\n\t\ttree: spot.tree,\n\t\trunouts: spot.runouts,\n\t\tplayers: spot.players,\n\t\tlayout,\n\t\tshowdown,\n\t\tregret: options.analysisOnly\n\t\t\t? new Float32Array(0)\n\t\t\t: makeRegretStore(precision, allocate(layout.totalSlots * width)),\n\t\tstrategySum: makeSumStore(precision, allocate(layout.totalSlots * width)),\n\t\tregretScale: quantised ? new Float64Array(allocate(layout.blocks * 8)) : null,\n\t\tsumScale: quantised ? new Float64Array(allocate(layout.blocks * 8)) : null,\n\t\tscratch: makeTerminalScratch(),\n\t\tchipScale: spot.chipScale,\n\t\tactive: buildActiveLists(spot.runouts, spot.players),\n\t\trunoutWeight: weights,\n\t\tshardStart: 0,\n\t\tshardEnd: plan ? plan.boards : 0,\n\t\tshardRound: plan ? plan.round : -1,\n\t\tapplyUpdates: true,\n\t\tchanceCollect: null,\n\t\tchanceOverride: null,\n\t\tentryIndexOf: plan ? plan.entryIndexOf : null,\n\t\texpandOrbits: false,\n\t\tsimd: options.simd ?? true,\n\t\t// The traversal sums over every runout, so the denominator has to count\n\t\t// them too: a hand pair is dealt once per compatible completion, not\n\t\t// once. With a river board that factor is 1, which is exactly why this\n\t\t// is easy to miss.\n\t\ttotalMass: matchupMass(spot.players[0].weights, spot.players[1].weights) * weights[0],\n\t\tdcfr: (options.algorithm ?? 'dcfr') === 'dcfr',\n\t};\n\n\t// Seeded before any worker starts, so they all see the inherited values.\n\tlet warm: WarmStartReport | null = null;\n\tlet offset = 0;\n\tif (options.warmStart) {\n\t\tconst source = options.warmStart;\n\t\twarm = warmStart(ctx, source.solver.ctx, sameSpot(spot.source, source.spot.source));\n\t\toffset = options.warmIteration ?? source.totalIterations;\n\t}\n\n\tconst solver = makeSolver(ctx);\n\tconst pool: Pool | null = plan\n\t\t? startPool(ctx, solver, plan, { config: spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd }, requested)\n\t\t: null;\n\tif (pool) solver.useRoot(pool.traverse);\n\tlet completed = 0;\n\n\treturn {\n\t\tspot,\n\t\tsolver,\n\t\tworkers: pool ? pool.workers : 1,\n\t\tget completed() {\n\t\t\treturn completed;\n\t\t},\n\t\twarmStart: warm,\n\t\tget totalIterations() {\n\t\t\treturn offset + completed;\n\t\t},\n\t\tstep(count) {\n\t\t\tif (count <= 0) return;\n\t\t\tsolver.iterate(count, offset + completed);\n\t\t\tcompleted += count;\n\t\t},\n\t\tclose() {\n\t\t\t// Snapshots stay usable afterwards, on this thread alone.\n\t\t\tsolver.useRoot(null);\n\t\t\tpool?.close();\n\t\t},\n\t\texploitabilityPercent() {\n\t\t\treturn (100 * solver.exploitability()) / (spot.potUnits / spot.chipScale);\n\t\t},\n\t\ttrueExploitabilityPercent() {\n\t\t\tif (!spot.runouts.approximate) return this.exploitabilityPercent();\n\t\t\tconst real = createRun(defineSpot({ ...spot.source, runoutBuckets: false }), {\n\t\t\t\tworkers: pool ? pool.workers : 1,\n\t\t\t\tprecision,\n\t\t\t});\n\t\t\ttry {\n\t\t\t\twarmStart(real.solver.ctx, ctx, true);\n\t\t\t\treturn real.exploitabilityPercent();\n\t\t\t} finally {\n\t\t\t\treal.close();\n\t\t\t}\n\t\t},\n\t\tsnapshot(history = [], stoppedAt = 'iterations') {\n\t\t\treturn makeSolution(spot, ctx, solver, completed, offset + completed, [...history], stoppedAt, pool ? pool.workers : 1);\n\t\t},\n\t};\n}\n\n/**\n * Whether two configurations describe the very same game. Limits and how\n * runouts are stored do not change the game, so they are left out.\n */\nfunction sameSpot(a: SpotConfig, b: SpotConfig): boolean {\n\tconst plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, ...game }: SpotConfig): string =>\n\t\tJSON.stringify(game, (_, value: unknown) => (value instanceof Float64Array ? Array.from(value) : value));\n\treturn plain(a) === plain(b);\n}\n\n/** Largest rank distance within a runout bucket, for `runoutBuckets: true`. */\nconst DEFAULT_BUCKET_GAP = 1;\n\n/** Rank swaps that keep every hand of both ranges in its range. */\nfunction rangeRankMerge(players: readonly [PlayerIndex, PlayerIndex], maxGap: number): RunoutMerge {\n\tconst allowed = new Uint8Array(13 * 13);\n\tfor (let a = 0; a < 13; a++) {\n\t\tfor (let b = a; b < 13; b++) {\n\t\t\tconst map = rankSwap(a, b);\n\t\t\tlet ok = true;\n\t\t\tfor (const player of players) {\n\t\t\t\tfor (let i = 0; ok && i < player.count; i++) {\n\t\t\t\t\tconst combo = player.combos[i];\n\t\t\t\t\tconst image = comboIndex(map[COMBO_CARDS[combo * 2]], map[COMBO_CARDS[combo * 2 + 1]]);\n\t\t\t\t\tif (player.slot[image] < 0) ok = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tallowed[a * 13 + b] = allowed[b * 13 + a] = ok ? 1 : 0;\n\t\t}\n\t}\n\treturn { ranks: (a, b) => allowed[a * 13 + b] === 1, maxGap };\n}\n\nlet warnedThreads = false;\n\n/**\n * Threads a run will use. The browser build has none to offer, so anything\n * above one falls back to the calling thread, with a single warning.\n */\nfunction resolveWorkers(options: SolveOptions): number {\n\tif (options.analysisOnly) return 1;\n\tconst asked = options.workers === 'auto' ? defaultWorkerCount() : (options.workers ?? 1);\n\tif (asked > 1 && !THREADS_AVAILABLE) {\n\t\tif (!warnedThreads) {\n\t\t\twarnedThreads = true;\n\t\t\tconsole.warn(`poker-flopsolve: worker threads are Node-only; solving on one thread (${PLATFORM} build)`);\n\t\t}\n\t\treturn 1;\n\t}\n\treturn asked;\n}\n\n/** View a buffer as regret storage of the given precision. */\nexport function makeRegretStore(precision: Precision, buffer: ArrayBuffer | SharedArrayBuffer): RegretStore {\n\tif (precision === 'f64') return new Float64Array(buffer);\n\treturn precision === 'f32' ? new Float32Array(buffer) : new Int16Array(buffer);\n}\n\n/** View a buffer as strategy-sum storage of the given precision. */\nexport function makeSumStore(precision: Precision, buffer: ArrayBuffer | SharedArrayBuffer): SumStore {\n\tif (precision === 'f64') return new Float64Array(buffer);\n\treturn precision === 'f32' ? new Float32Array(buffer) : new Uint16Array(buffer);\n}\n\n/**\n * Solve a prepared spot.\n * @param spot from {@link defineSpot}\n * @param options solver tuning\n */\nexport function solve(spot: Spot, options: SolveOptions = {}): Solution {\n\tconst iterations = options.iterations ?? 500;\n\tconst target = options.targetPercent ?? 0;\n\tconst fixed = options.exploitEvery ?? 0;\n\tconst run = createRun(spot, options);\n\tconst history: Progress[] = [];\n\tconst started = Date.now();\n\n\ttry {\n\t\treturn runAll();\n\t} finally {\n\t\trun.close();\n\t}\n\n\tfunction runAll(): Solution {\n\t\t// Nothing to measure for: run straight through in one call.\n\t\tif (fixed <= 0 && target <= 0) {\n\t\t\trun.step(iterations);\n\t\t\treturn run.snapshot(history, 'iterations');\n\t\t}\n\n\t\tlet stoppedAt: 'target' | 'iterations' = 'iterations';\n\t\tlet done = 0;\n\t\tlet next = fixed > 0 ? fixed : Math.min(iterations, FIRST_CHECK);\n\t\tlet prevIteration = 0;\n\t\tlet prevExploitability = 0;\n\n\t\twhile (done < iterations) {\n\t\t\tconst until = Math.min(next, iterations);\n\t\t\trun.step(until - done);\n\t\t\tdone = until;\n\n\t\t\t// One snapshot, because it caches the best-response pass that both\n\t\t\t// of these read. Two calls on the run itself would pay for it twice.\n\t\t\tconst measured = run.snapshot();\n\t\t\tconst info: Progress = {\n\t\t\t\titeration: done,\n\t\t\t\texploitability: measured.exploitability(),\n\t\t\t\telapsedMs: Date.now() - started,\n\t\t\t};\n\t\t\thistory.push(info);\n\t\t\toptions.onProgress?.(info);\n\n\t\t\tif (target > 0 && measured.exploitabilityPercent() <= target) {\n\t\t\t\tstoppedAt = 'target';\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (fixed > 0) {\n\t\t\t\tnext = done + fixed;\n\t\t\t} else {\n\t\t\t\t// Aim just short of where the target is predicted to be met, so\n\t\t\t\t// the overshoot is a few iterations rather than a whole doubling.\n\t\t\t\tconst predicted = predictCrossing(\n\t\t\t\t\tprevIteration,\n\t\t\t\t\tprevExploitability,\n\t\t\t\t\tdone,\n\t\t\t\t\tinfo.exploitability,\n\t\t\t\t\t(target * spot.potUnits) / (100 * spot.chipScale),\n\t\t\t\t);\n\t\t\t\tconst aim = predicted > 0 ? predicted * 0.95 : done * MAX_GROWTH;\n\t\t\t\tconst bounded = Math.min(Math.max(aim, done * MIN_GROWTH), done * MAX_GROWTH);\n\t\t\t\tnext = Math.max(done + 1, Math.ceil(bounded));\n\t\t\t\tprevIteration = done;\n\t\t\t\tprevExploitability = info.exploitability;\n\t\t\t}\n\t\t}\n\t\treturn run.snapshot(history, stoppedAt);\n\t}\n}\n\n/** Iterations before the first exploitability check. */\nconst FIRST_CHECK = 10;\n\n/** Bounds on how far ahead the next check may be scheduled. */\nconst MIN_GROWTH = 1.1;\nconst MAX_GROWTH = 2;\n\n/**\n * Predict the iteration at which exploitability will reach `target`.\n *\n * CFR+ exploitability falls as roughly `C / T^p`, so two measurements pin both\n * constants and the crossing follows. This beats any fixed cadence badly enough\n * to be worth the eight lines: a check is a full best-response pass for both\n * players, as costly as an iteration.\n *\n * Returns 0 when the two points say nothing useful — equal values, a rise, or a\n * non-finite fit — and the caller falls back to stepping the gap up.\n *\n * Exported because the browser UI drives its own loop, to stay stoppable, and\n * should schedule its checks the same way rather than reinventing a cadence.\n * Unit-agnostic: `e1`, `e2` and `target` need only share units.\n */\nexport function predictCrossing(\n\tt1: number,\n\te1: number,\n\tt2: number,\n\te2: number,\n\ttarget: number,\n): number {\n\tif (!(e1 > e2) || !(e2 > 0) || t2 <= t1) return 0;\n\tconst p = Math.log(e1 / e2) / Math.log(t2 / t1);\n\tif (!(p > 0)) return 0;\n\tconst predicted = t2 * (e2 / target) ** (1 / p);\n\treturn Number.isFinite(predicted) ? predicted : 0;\n}\n\nfunction makeSolution(\n\tspot: Spot,\n\tctx: Context,\n\tsolver: Solver,\n\titerations: number,\n\ttotalIterations: number,\n\thistory: Progress[],\n\tstoppedAt: 'target' | 'iterations',\n\tworkers: number,\n): Solution {\n\tconst { tree } = spot;\n\tconst parent = new Int32Array(tree.nodeCount).fill(-1);\n\tconst viaEdge = new Int32Array(tree.nodeCount).fill(-1);\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tfor (let e = 0; e < tree.numEdges[node]; e++) {\n\t\t\tconst edge = tree.firstEdge[node] + e;\n\t\t\tparent[tree.edgeChild[edge]] = node;\n\t\t\tviaEdge[tree.edgeChild[edge]] = edge;\n\t\t}\n\t}\n\n\tconst label = (edge: number): string => {\n\t\tconst kind = tree.edgeAction[edge];\n\t\tconst amount = tree.edgeTarget[edge] / spot.chipScale;\n\t\treturn kind >= ActionKind.Bet ? `${ACTION_LABELS[kind]} ${amount}` : ACTION_LABELS[kind];\n\t};\n\n\tconst reachAt = (node: number, board: number, player: 0 | 1): Float64Array => {\n\t\tconst index = spot.players[player];\n\t\tconst reach = new Float64Array(COMBOS);\n\t\tfor (let i = 0; i < index.count; i++) reach[index.combos[i]] = index.weights[index.combos[i]];\n\t\tconst round = tree.round[node];\n\n\t\tfor (let current = node; parent[current] >= 0; current = parent[current]) {\n\t\t\tconst owner = parent[current];\n\t\t\tif (tree.kind[owner] !== NodeKind.Decision || tree.player[owner] !== player) continue;\n\t\t\tconst at = boardAtRound(spot.runouts, board, round, tree.round[owner]);\n\t\t\tconst { actions, probs } = solver.averageStrategyAt(owner, at);\n\t\t\tconst action = viaEdge[current] - tree.firstEdge[owner];\n\t\t\tfor (let i = 0; i < index.count; i++) reach[index.combos[i]] *= probs[i * actions + action];\n\t\t}\n\t\treturn reach;\n\t};\n\n\tlet cachedEv: [number, number] | null = null;\n\tlet cachedExploit: number | null = null;\n\n\treturn {\n\t\tspot,\n\t\titerations,\n\t\ttotalIterations,\n\t\tstoppedAt,\n\t\tworkers,\n\t\tsolver,\n\t\thistory,\n\t\tev(player) {\n\t\t\tcachedEv ??= solver.expectedValue();\n\t\t\treturn cachedEv[player];\n\t\t},\n\t\texploitability() {\n\t\t\tcachedExploit ??= solver.exploitability();\n\t\t\treturn cachedExploit;\n\t\t},\n\t\texploitabilityPercent() {\n\t\t\tcachedExploit ??= solver.exploitability();\n\t\t\treturn (100 * cachedExploit) / (spot.potUnits / spot.chipScale);\n\t\t},\n\t\tstrategyAt(node, board) {\n\t\t\tif (tree.kind[node] !== NodeKind.Decision) throw new Error(`Node ${node} is not a decision`);\n\t\t\tconst owner = tree.player[node] as 0 | 1;\n\t\t\tconst { actions, probs } = solver.averageStrategyAt(node, board);\n\t\t\tconst names: string[] = [];\n\t\t\tfor (let a = 0; a < actions; a++) names.push(label(tree.firstEdge[node] + a));\n\t\t\treturn { node, board, player: owner, actions: names, combos: spot.players[owner].combos, probs };\n\t\t},\n\t\tpath(node) {\n\t\t\tconst steps: string[] = [];\n\t\t\tlet current = node;\n\t\t\twhile (parent[current] >= 0) {\n\t\t\t\tconst owner = parent[current];\n\t\t\t\tsteps.push(tree.kind[owner] === NodeKind.Decision ? label(viaEdge[current]) : '/');\n\t\t\t\tcurrent = owner;\n\t\t\t}\n\t\t\treturn steps.reverse().join(' ') || '(root)';\n\t\t},\n\t\treachAt,\n\t\tsubgameAt(node, board, betting = {}) {\n\t\t\tconst opensRound = node === 0 || (parent[node] >= 0 && tree.kind[parent[node]] === NodeKind.Chance);\n\t\t\tif (tree.kind[node] !== NodeKind.Decision || !opensRound) {\n\t\t\t\tthrow new Error(`Node ${node} does not open a betting round; a subgame must start where one does`);\n\t\t\t}\n\t\t\tconst round = tree.round[node];\n\t\t\tif (board < 0 || board >= spot.runouts.counts[round]) {\n\t\t\t\tthrow new Error(`Board ${board} is out of range for round ${round}`);\n\t\t\t}\n\n\t\t\t// A round opens with both players level, so what is in the middle\n\t\t\t// is dead money from here on and the stacks have shrunk equally.\n\t\t\tconst width = spot.runouts.width[round];\n\t\t\tconst cards = spot.runouts.cards[round].subarray(board * width, board * width + width);\n\t\t\tconst invested = (tree.pot[node] - spot.potUnits) / 2;\n\t\t\tconst { source } = spot;\n\t\t\t// Settings given per round lose the rounds already played.\n\t\t\tconst later = <T>(value: T | readonly T[], listed: boolean): T | readonly T[] =>\n\t\t\t\tlisted && (value as readonly T[]).length > 1 ? (value as readonly T[]).slice(round) : value;\n\t\t\tconst rows = later(source.betSizes, true) as readonly (readonly BetSize[])[];\n\t\t\tconst raiseRows = source.raiseSizes && (later<unknown>(source.raiseSizes, raisesPerRound(source.raiseSizes)) as RaiseSizes);\n\n\t\t\treturn {\n\t\t\t\tboard: formatCards(cards),\n\t\t\t\tpot: tree.pot[node] / spot.chipScale,\n\t\t\t\tstack: (spot.stackUnits - invested) / spot.chipScale,\n\t\t\t\toop: reachAt(node, board, 0),\n\t\t\t\tip: reachAt(node, board, 1),\n\t\t\t\tbetSizes: betting.betSizes ?? rows,\n\t\t\t\traiseSizes: 'raiseSizes' in betting ? betting.raiseSizes : raiseRows,\n\t\t\t\tmaxRaises: betting.maxRaises ?? (source.maxRaises === undefined ? undefined : later(source.maxRaises, Array.isArray(source.maxRaises))),\n\t\t\t\tallowAllIn: betting.allowAllIn ?? (source.allowAllIn === undefined ? undefined : later(source.allowAllIn, Array.isArray(source.allowAllIn))),\n\t\t\t\tallInThreshold: 'allInThreshold' in betting ? betting.allInThreshold : source.allInThreshold === undefined ? undefined : later(source.allInThreshold, Array.isArray(source.allInThreshold)),\n\t\t\t\tnoDonk: 'noDonk' in betting ? betting.noDonk : source.noDonk === undefined ? undefined : later(source.noDonk, Array.isArray(source.noDonk)),\n\t\t\t\tmergeSizes: 'mergeSizes' in betting ? betting.mergeSizes : source.mergeSizes,\n\t\t\t\tminWeight: source.minWeight,\n\t\t\t\tisomorphism: source.isomorphism,\n\t\t\t\tmaxCombos: 'maxCombos' in betting ? betting.maxCombos : source.maxCombos,\n\t\t\t\tmaxBytes: 'maxBytes' in betting ? betting.maxBytes : source.maxBytes,\n\t\t\t\tchipScale: spot.chipScale,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport { formatCards, parseCards };\n"],"mappings":";AAeA,IAAM,aAAa;AAGnB,IAAM,aAAa;AAEZ,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,OAAO;AAGb,IAAM,SAAS;AAGf,SAAS,OAAO,MAAsB;AAC5C,SAAO,QAAQ;AAChB;AAGO,SAAS,OAAO,MAAsB;AAC5C,SAAO,OAAO;AACf;AAGO,SAAS,OAAO,MAAc,MAAsB;AAC1D,SAAQ,QAAQ,IAAK;AACtB;AAMO,SAAS,WAAW,MAAsB;AAChD,SAAO,WAAW,OAAO,IAAI,CAAC,IAAI,WAAW,OAAO,IAAI,CAAC;AAC1D;AAGO,SAAS,YAAY,OAAiC;AAC5D,SAAO,CAAC,GAAG,KAAK,EAAE,IAAI,UAAU,EAAE,KAAK,GAAG;AAC3C;AAOO,SAAS,UAAU,MAAsB;AAC/C,MAAI,KAAK,WAAW,EAAG,OAAM,IAAI,MAAM,iBAAiB,IAAI,4BAA4B;AACxF,QAAM,OAAO,WAAW,QAAQ,KAAK,CAAC,EAAE,YAAY,CAAC;AACrD,QAAM,OAAO,WAAW,QAAQ,KAAK,CAAC,EAAE,YAAY,CAAC;AACrD,MAAI,OAAO,EAAG,OAAM,IAAI,MAAM,iBAAiB,KAAK,CAAC,CAAC,cAAc,IAAI,GAAG;AAC3E,MAAI,OAAO,EAAG,OAAM,IAAI,MAAM,iBAAiB,KAAK,CAAC,CAAC,cAAc,IAAI,GAAG;AAC3E,SAAO,OAAO,MAAM,IAAI;AACzB;AAOO,SAAS,WAAW,MAAwB;AAClD,QAAM,UAAU,KAAK,QAAQ,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