poker-flopsolve 0.5.0-beta.0 → 0.5.0-beta.2

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.
@@ -1 +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/hands.ts","../src/pairs.ts","../src/wasm/kernels.ts","../src/kernels.ts","../src/cfr.ts","../src/wasm/engine.ts","../src/wasm/engine-shared.ts","../src/platform/browser-threads.ts","../src/platform/browser.ts","../src/parallel.ts","../src/engine.ts","../src/warm.ts","../src/settle.ts","../src/history-merge.ts","../src/betting.ts","../src/resolve.ts","../src/hybrid.ts","../src/presets.ts","../src/lite.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/**\n * A setting given once for both players, or apart: `{ oop: …, ip: … }`, each\n * side in the setting's own form.\n */\nexport type PerPlayer<T> = T | { readonly oop: T; readonly ip: T };\n\n/** Whether a setting is given apart for each player. */\nexport function isPerPlayer<T>(value: PerPlayer<T>): value is { readonly oop: T; readonly ip: T } {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value) && 'oop' in value && 'ip' in value;\n}\n\n/** One player's side of a setting: 0 out of position, 1 in position. */\nexport function forPlayer<T>(value: PerPlayer<T>, player: number): T {\n\treturn isPerPlayer(value) ? (player === 0 ? value.oop : value.ip) : value;\n}\n\n/** Apply `f` to each side of a setting, keeping its shape. */\nexport function mapPlayers<T, U>(value: PerPlayer<T>, f: (side: T) => U): PerPlayer<U> {\n\treturn isPerPlayer(value) ? { oop: f(value.oop), ip: f(value.ip) } : f(value);\n}\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; for both players, or apart. */\n\treadonly betSizes: PerPlayer<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?: PerPlayer<RaiseSizes | undefined>;\n\t/**\n\t * Maximum aggressive actions per round, the opening bet the first; once or\n\t * per round. Given apart, a player may bet or raise only while the round's\n\t * aggressions are under their own limit.\n\t */\n\treadonly maxRaises: PerPlayer<number | readonly number[]>;\n\t/** Offer a shove alongside the configured sizes; once or per round. */\n\treadonly allowAllIn: PerPlayer<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?: PerPlayer<number | readonly number[] | undefined>;\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\t/**\n\t * Bets, raises and shoves to leave out, each by the readable path of the\n\t * node it leads to — `Solution.path` — with the subtree below it. Unset,\n\t * none. See `SpotConfig.removeActions`.\n\t */\n\treadonly removeActions?: readonly string[];\n\t/**\n\t * Keep one size at most nodes: see `SpotConfig.thinSizes`. Unset or\n\t * false, every size the other settings give.\n\t */\n\treadonly thinSizes?: boolean;\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/**\n * How a path names an action: `check`, `call`, `fold`, or the kind and the\n * actor's total investment after it in chips — `bet 18.15`, `raise 60`,\n * `allin 975`. `Solution.path` joins these with spaces, and `/` for a deal.\n */\nexport function actionLabel(action: number, target: number, chipScale: number): string {\n\treturn action >= ActionKind.Bet ? `${ACTION_LABELS[action]} ${target / chipScale}` : ACTION_LABELS[action];\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 SizedAction {\n\treadonly action: number;\n\treadonly target: number;\n}\n\n/** The pot fraction `thinSizes` keeps at most decisions. */\nconst THIN_BASE = 0.75;\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\t/** Earlier rounds that saw a bet. */\n\treadonly streetsBet: 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: Pick<Runouts, 'rounds'>): 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\t// Every betting setting resolved per player, then per round.\n\tconst players = [0, 1] as const;\n\tconst maxRaises = players.map((p) => {\n\t\tconst value = forPlayer(config.maxRaises, p);\n\t\treturn perRound(value, Array.isArray(value), rounds, 'maxRaises');\n\t});\n\tconst allowAllIn = players.map((p) => {\n\t\tconst value = forPlayer(config.allowAllIn, p);\n\t\treturn perRound(value, Array.isArray(value), rounds, 'allowAllIn');\n\t});\n\tconst merge = config.mergeSizes ?? 0;\n\tconst raiseSizes = players.map((p) => {\n\t\tconst value = forPlayer(config.raiseSizes, p);\n\t\treturn value\n\t\t\t? perRound<readonly BetSize[]>(value, raisesPerRound(value), rounds, 'raiseSizes').map((row) => mergeBetSizes(row, merge))\n\t\t\t: null;\n\t});\n\tconst betSizes = players.map((p) => forPlayer(config.betSizes, p).map((row) => mergeBetSizes(row, merge)));\n\tconst threshold = players.map((p) => {\n\t\tconst value = forPlayer(config.allInThreshold, p) ?? 0;\n\t\treturn perRound(value, Array.isArray(value), rounds, 'allInThreshold');\n\t});\n\tconst noDonk = perRound(config.noDonk ?? false, Array.isArray(config.noDonk), rounds, 'noDonk');\n\tconst half = Math.round(potUnits / 2);\n\t// Lines to cut, and which of them were found. Paths are only built when\n\t// there is something to cut, so a tree without cuts is built as before.\n\tconst remove = config.removeActions && config.removeActions.length > 0 ? new Set(config.removeActions) : null;\n\tconst removed = new Set<string>();\n\tconst extend = (path: string, step: string): string => (remove ? (path ? `${path} ${step}` : step) : '');\n\n\t// The sizes `thinSizes` keeps at a decision, in the order they came.\n\tconst thin = config.thinSizes === true;\n\tconst thinned = (sized: readonly SizedAction[], state: BetState): readonly SizedAction[] => {\n\t\t// Every size where the first round opens.\n\t\tif (state.round === 0 && state.aggressions === 0 && state.acted === 0) return sized;\n\t\tconst me = state.toAct;\n\t\tconst mine = state.invested[me];\n\t\tconst owed = Math.max(0, state.invested[1 - me] - mine);\n\t\tconst potAfterCall = potUnits + state.invested[0] + state.invested[1] + owed;\n\t\tconst fraction = (target: number): number => (target - mine - owed) / potAfterCall;\n\t\t// The size nearest three quarters of the pot: a shove where that is one.\n\t\tlet nearest = -1;\n\t\tsized.forEach((entry, i) => {\n\t\t\tconst distance = Math.abs(fraction(entry.target) - THIN_BASE);\n\t\t\tif (nearest < 0 || distance < Math.abs(fraction(sized[nearest].target) - THIN_BASE)) nearest = i;\n\t\t});\n\t\t// Opening the last round after an earlier one saw a bet: the big sizes too.\n\t\tconst big = rounds > 1 && state.round === rounds - 1 && owed === 0 && state.streetsBet > 0;\n\t\treturn sized.filter(\n\t\t\t(entry, i) => i === nearest || (big && (entry.action === ActionKind.AllIn || fraction(entry.target) > 1)),\n\t\t);\n\t};\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, path: string): 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\tstreetsBet: state.streetsBet + (state.aggressions > 0 ? 1 : 0),\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, extend(path, '/')) : buildDecision(next, extend(path, '/'));\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\t// Short of a full raise: bumped up to one where the stack allows it,\n\t\t// and otherwise all-in for less. A player can always put in everything\n\t\t// they have, raise or not — dropping that shove left a short stack\n\t\t// facing a bet only call or fold.\n\t\tconst raiseSize = target - theirs;\n\t\tconst minimum = Math.max(state.lastRaise, minRaiseUnits);\n\t\tif (raiseSize < minimum) target = Math.min(theirs + minimum, cap);\n\t\treturn target;\n\t};\n\n\tconst buildDecision = (state: BetState, path: string): 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[me][state.round] && myRemaining > owed && !donk) {\n\t\t\tconst seen = new Set<number>();\n\t\t\tconst sized: { action: number; target: number }[] = [];\n\t\t\tconst myRaises = raiseSizes[me];\n\t\t\tconst sizes: BetSize[] =\n\t\t\t\towed > 0 && myRaises\n\t\t\t\t\t? [...myRaises[state.round]]\n\t\t\t\t\t: [...(betSizes[me][state.round] ?? [])].filter((size) => !(typeof size === 'object' && 'times' in size));\n\t\t\tif (allowAllIn[me][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[me][state.round] > 0 && target - mine >= threshold[me][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\tsized.push({ action: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet, target });\n\t\t\t}\n\t\t\tfor (const entry of thin ? thinned(sized, state) : sized) {\n\t\t\t\tif (remove) {\n\t\t\t\t\tconst line = extend(path, actionLabel(entry.action, entry.target, chipScale));\n\t\t\t\t\tif (remove.has(line)) {\n\t\t\t\t\t\tremoved.add(line);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tactions.push(entry);\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\t// Labels only matter to a cut, so a tree without one formats none.\n\t\t\tconst line = remove ? extend(path, actionLabel(entry.action, entry.target, chipScale)) : '';\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 }, line)\n\t\t\t\t\t: buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 }, line);\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\tstreetsBet: state.streetsBet,\n\t\t\t\t}, line);\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\tstreetsBet: 0,\n\t}, '');\n\n\tif (remove && removed.size < remove.size) {\n\t\t// A line below a cut one went with it, so the tree never reached it.\n\t\tconst under = (line: string): boolean => [...removed].some((cut) => line.startsWith(`${cut} `));\n\t\tconst missing = [...remove].filter((line) => !removed.has(line) && !under(line));\n\t\tif (missing.length > 0) throw new Error(\n\t\t\t`removeActions: no bet, raise or shove in this tree ends the line ${missing.map((m) => `\"${m}\"`).join(', ')}. ` +\n\t\t\t\t'Give each as Solution.path writes the node the action leads to, e.g. \"check bet 18.15\"; ' +\n\t\t\t\t'checks, calls and folds cannot be removed',\n\t\t);\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, which the solver\n\t * stores once per orbit.\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\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\tconst base = p * previousWidth;\n\t\t\tconst children = dealChildren(maps, previousCards, base, previousWidth, stabilisers[p], merge);\n\t\t\tfor (const child of children) if (child.merged) approximate = true;\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/** One stored child of a board, and the real deals it stands for. */\nexport interface DealtChild {\n\treadonly card: number;\n\t/** Each member deal's map onto this board, and its card; see `Runouts.orbitMap`. */\n\treadonly maps: number[];\n\treadonly cards: number[];\n\t/** The parent's symmetries that also fix this card: the child's own. */\n\treadonly fixing: number[];\n\t/** Folded into an earlier child, so not stored. */\n\tmerged: boolean;\n}\n\nconst usedScratch = new Uint8Array(DECK);\nconst seenScratch = new Uint8Array(DECK);\n\n/**\n * The children of one board: one per orbit of its symmetries, ascending by\n * card, with runout buckets folded into earlier children (`merged`).\n *\n * @param maps the relabellings in use, which merges add to\n * @param cards flat board cards, the parent at `base`, `width` of them\n * @param stabiliser the parent's symmetries, identity first\n */\nexport function dealChildren(\n\tmaps: CardMaps,\n\tcards: ArrayLike<number>,\n\tbase: number,\n\twidth: number,\n\tstabiliser: readonly number[],\n\tmerge?: RunoutMerge,\n): DealtChild[] {\n\tconst used = usedScratch;\n\tconst seen = seenScratch;\n\tused.fill(0);\n\tseen.fill(0);\n\tfor (let i = 0; i < width; i++) used[cards[base + i]] = 1;\n\n\t// One stored child per orbit of the board's symmetries.\n\tconst children: DealtChild[] = [];\n\tfor (let card = 0; card < DECK; card++) {\n\t\tif (used[card] || seen[card]) continue;\n\t\t// Ascending, so the first unseen card of an orbit is its lowest.\n\t\tconst child: DealtChild = { card, maps: [], cards: [], fixing: [], merged: false };\n\t\tfor (const sigma of stabiliser) {\n\t\t\tconst image = maps.card[sigma][card];\n\t\t\tif (image === card) child.fixing.push(sigma);\n\t\t\tif (seen[image]) continue;\n\t\t\tseen[image] = 1;\n\t\t\t// `sigma` sends `card` to `image`, so its inverse sends the\n\t\t\t// deal of `image` back onto this board.\n\t\t\tchild.maps.push(image === card ? 0 : maps.inverse(sigma));\n\t\t\tchild.cards.push(image);\n\t\t}\n\t\tchildren.push(child);\n\t}\n\n\t// Runout buckets: a child that plays like an earlier one is folded\n\t// into it, relabelled by swapping the two cards' ranks.\n\tif (merge) {\n\t\tconst boardRanks = new Set<number>();\n\t\tfor (let i = 0; i < width; i++) boardRanks.add(cards[base + i] >> 2);\n\t\tfor (let j = 0; j < children.length; j++) {\n\t\t\tconst later = children[j];\n\t\t\tconst rankJ = later.card >> 2;\n\t\t\tif (boardRanks.has(rankJ)) continue;\n\t\t\tfor (let i = 0; i < j; i++) {\n\t\t\t\tconst earlier = children[i];\n\t\t\t\tif (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;\n\t\t\t\tconst rankI = earlier.card >> 2;\n\t\t\t\tif (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;\n\t\t\t\tif (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;\n\t\t\t\tconst swap = maps.add(rankSwap(rankI, rankJ));\n\t\t\t\tfor (let m = 0; m < later.maps.length; m++) {\n\t\t\t\t\tearlier.maps.push(maps.then(later.maps[m], swap));\n\t\t\t\t\tearlier.cards.push(later.cards[m]);\n\t\t\t\t}\n\t\t\t\tlater.merged = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn children;\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\tconst children = runouts.childStart[round];\n\t\tconst relabel = runouts.orbitMap[round];\n\t\tfor (let child = children[index]; child < children[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, relabel[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 * Hand-space index structures and terminal kernels.\n *\n * Purpose: let a traversal carry each player's reach and values as a dense\n * vector over the hands that player can hold on the current board — entry `i`\n * of their active list (`buildActiveLists` in cfr.ts) — instead of a sparse\n * 1326-wide array reached through a list of live combinations. Every loop\n * then runs `0..n` over contiguous memory.\n *\n * What a traversal needs to move between boards and to settle terminals:\n *\n * - At a deal, which parent hand each child hand is, for the stored board\n * and for every real deal it stands for (relabelled by the orbit's map).\n * Reach is gathered and values scatter-added through these.\n * - At a fold, which opposing hand is the very same combination as each of\n * mine, for the inclusion–exclusion that removes it.\n *\n * A showdown needs nothing here: on a final board the active lists are\n * already sorted by strength, with each entry's strength and cards beside it.\n */\n\nimport { COMBOS, DECK } from './cards.ts';\nimport type { PlayerIndex } from './cfr.ts';\nimport type { Runouts } from './runouts.ts';\n\n/** The active lists, as `buildActiveLists` lays them out. */\nexport interface HandLists {\n\treadonly start: Int32Array;\n\treadonly count: Uint16Array;\n\treadonly list: Uint16Array;\n\treadonly roundBase: Int32Array;\n\treadonly memberStart: Int32Array;\n\treadonly memberCombo: Uint16Array;\n}\n\n/** Everything a hand-space traversal looks up. */\nexport interface HandSpace {\n\t/**\n\t * Deals: for round `r`, orbit member `m` (an index into\n\t * `runouts.orbitMap[r]`) and player `p`, `up` from `upStart[r][m * 2 + p]`\n\t * holds, for each of the player's hands on the stored child board, the\n\t * index of the parent-board hand it is — through the member's relabelling.\n\t */\n\treadonly upStart: readonly Int32Array[];\n\treadonly up: Uint16Array;\n\t/**\n\t * Folds: for each list slot `(roundBase[r] + board) * 2 + p`, from\n\t * `sameStart[slot]`, the index in the other player's list of each of this\n\t * player's hands, or -1 where they cannot hold it.\n\t */\n\treadonly sameStart: Int32Array;\n\treadonly same: Int32Array;\n}\n\n/**\n * Point every hand the entries of one list stand for at its entry's position\n * in that list, or back at -1 with `clear`.\n */\nexport function markMembers(\n\tlists: Pick<HandLists, 'memberStart' | 'memberCombo'>,\n\tfrom: number,\n\tcount: number,\n\tindexOf: Int32Array,\n\tclear: boolean,\n): void {\n\tfor (let i = 0; i < count; i++) {\n\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\tindexOf[lists.memberCombo[m]] = clear ? -1 : i;\n\t\t}\n\t}\n}\n\n/** A list's offset and length for a round, board and player. */\nfunction span(lists: HandLists, round: number, board: number, player: number): [number, number] {\n\tconst slot = (lists.roundBase[round] + board) * 2 + player;\n\treturn [lists.start[slot], lists.count[slot]];\n}\n\n/** Build the hand-space structures for a prepared spot. */\nexport function buildHandSpace(\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tlists: HandLists,\n): HandSpace {\n\tvoid players;\n\tconst indexOf = new Int32Array(COMBOS).fill(-1);\n\n\t// Deals.\n\tconst upStart: Int32Array[] = [new Int32Array(0)];\n\tconst up: number[] = [];\n\tfor (let round = 1; round < runouts.rounds; round++) {\n\t\tconst orbitStart = runouts.orbitStart[round];\n\t\tconst starts = new Int32Array(runouts.orbitMap[round].length * 2);\n\t\tfor (let child = 0; child < runouts.counts[round]; child++) {\n\t\t\tconst parent = runouts.parent[round][child];\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst [parentFrom, parentCount] = span(lists, round - 1, parent, player);\n\t\t\t\tmarkMembers(lists, parentFrom, parentCount, indexOf, false);\n\t\t\t\tconst [childFrom, childCount] = span(lists, round, child, player);\n\t\t\t\tfor (let m = orbitStart[child]; m < orbitStart[child + 1]; m++) {\n\t\t\t\t\t// The member's map sends a real hand onto the stored board;\n\t\t\t\t\t// its inverse sends a stored hand back to the real one.\n\t\t\t\t\tconst back = runouts.maps.combo[runouts.maps.inverse(runouts.orbitMap[round][m])];\n\t\t\t\t\tstarts[m * 2 + player] = up.length;\n\t\t\t\t\tfor (let k = 0; k < childCount; k++) {\n\t\t\t\t\t\tconst real = back[lists.list[childFrom + k]];\n\t\t\t\t\t\tconst at = indexOf[real];\n\t\t\t\t\t\tif (at < 0) throw new Error('A relabelled hand is not in its range; the relabelling must preserve both ranges');\n\t\t\t\t\t\tup.push(at);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmarkMembers(lists, parentFrom, parentCount, indexOf, true);\n\t\t\t}\n\t\t}\n\t\tupStart.push(starts);\n\t}\n\n\t// Folds.\n\tconst slots = lists.roundBase[runouts.rounds] * 2;\n\tconst sameStart = new Int32Array(slots + 1);\n\tconst same: number[] = [];\n\tfor (let round = 0; round < runouts.rounds; 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 = (lists.roundBase[round] + board) * 2 + player;\n\t\t\t\tconst [otherFrom, otherCount] = span(lists, round, board, 1 - player);\n\t\t\t\tmarkMembers(lists, otherFrom, otherCount, indexOf, false);\n\t\t\t\tconst [from, count] = span(lists, round, board, player);\n\t\t\t\tsameStart[slot] = same.length;\n\t\t\t\tfor (let i = 0; i < count; i++) same.push(indexOf[lists.list[from + i]]);\n\t\t\t\tmarkMembers(lists, otherFrom, otherCount, indexOf, true);\n\t\t\t}\n\t\t}\n\t}\n\tsameStart[slots] = same.length;\n\n\treturn { upStart, up: Uint16Array.from(up), sameStart, same: Int32Array.from(same) };\n}\n\n/**\n * Values at a fold, in hand space, exact under card removal: each of my hands\n * wins or loses `payoff` against every opposing hand it does not collide with.\n *\n * @param oppReach the opponent's reach, over their list\n * @param oppCombos their list's combinations, from `oppFrom`\n * @param myCombos mine, from `myFrom`\n * @param same for each of my hands, its index in their list or -1\n * @param sums 52 doubles of scratch, all zero; left zero\n * @param out my values, `myCount` of them\n */\nexport function foldValuesHands(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tsame: Int32Array,\n\tsameFrom: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet total = 0;\n\tfor (let j = 0; j < oppCount; j++) {\n\t\tconst value = oppReach[j];\n\t\ttotal += value;\n\t\tsums[cardA[oppFrom + j]] += value;\n\t\tsums[cardB[oppFrom + j]] += value;\n\t}\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst twin = same[sameFrom + i];\n\t\t// The pair term: the one opposing hand holding both my cards.\n\t\tconst both = twin >= 0 ? oppReach[twin] : 0;\n\t\tout[i] = payoff * (total - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]] - both));\n\t}\n\tsums.fill(0, 0, DECK);\n}\n\n/**\n * Values at a showdown, in hand space, exact under card removal.\n *\n * On a final board both lists are sorted by strength, so this is two\n * contiguous sweeps. Ascending, the opponent's hands strictly weaker than\n * each of mine are added to running totals before mine is read, so its own\n * tie group and its own cards fall out; descending, the same for hands\n * strictly stronger. A hand's value is what it beats minus what beats it,\n * times `payoff`.\n *\n * @param sums 52 doubles of scratch, all zero; left zero\n */\nexport function showdownValuesHands(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\tstrength: Int32Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet running = 0;\n\tlet j = 0;\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j < oppCount && strength[oppFrom + j] < level) {\n\t\t\tconst value = oppReach[j];\n\t\t\trunning += value;\n\t\t\tsums[cardA[oppFrom + j]] += value;\n\t\t\tsums[cardB[oppFrom + j]] += value;\n\t\t\tj++;\n\t\t}\n\t\tout[i] = running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]]);\n\t}\n\tsums.fill(0, 0, DECK);\n\n\trunning = 0;\n\tj = oppCount - 1;\n\tfor (let i = myCount - 1; i >= 0; i--) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j >= 0 && strength[oppFrom + j] > level) {\n\t\t\tconst value = oppReach[j];\n\t\t\trunning += value;\n\t\t\tsums[cardA[oppFrom + j]] += value;\n\t\t\tsums[cardB[oppFrom + j]] += value;\n\t\t\tj--;\n\t\t}\n\t\tout[i] = payoff * (out[i] - (running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]])));\n\t}\n\tsums.fill(0, 0, DECK);\n}\n\n/**\n * Packed lists' card-removal sums: each entry's reach counted once per hand it\n * stands for, on that hand's own cards. Returns the reach-weighted total.\n */\nfunction addMembers(\n\treach: number,\n\tentry: number,\n\tmemberStart: Int32Array,\n\tmemberA: Uint8Array,\n\tmemberB: Uint8Array,\n\tsums: Float64Array,\n): number {\n\tconst to = memberStart[entry + 1];\n\tfor (let m = memberStart[entry]; m < to; m++) {\n\t\tsums[memberA[m]] += reach;\n\t\tsums[memberB[m]] += reach;\n\t}\n\treturn reach * (to - memberStart[entry]);\n}\n\n/** `foldValuesHands` over packed lists: every hand an opposing entry stands for counts. */\nexport function foldValuesPacked(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\tmemberStart: Int32Array,\n\tmemberA: Uint8Array,\n\tmemberB: Uint8Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tsame: Int32Array,\n\tsameFrom: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet total = 0;\n\tfor (let j = 0; j < oppCount; j++) total += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst twin = same[sameFrom + i];\n\t\tconst both = twin >= 0 ? oppReach[twin] : 0;\n\t\tout[i] = payoff * (total - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]] - both));\n\t}\n\tsums.fill(0, 0, DECK);\n}\n\n/** `showdownValuesHands` over packed lists: every hand an opposing entry stands for counts. */\nexport function showdownValuesPacked(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\tmemberStart: Int32Array,\n\tmemberA: Uint8Array,\n\tmemberB: Uint8Array,\n\tstrength: Int32Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet running = 0;\n\tlet j = 0;\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j < oppCount && strength[oppFrom + j] < level) {\n\t\t\trunning += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);\n\t\t\tj++;\n\t\t}\n\t\tout[i] = running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]]);\n\t}\n\tsums.fill(0, 0, DECK);\n\n\trunning = 0;\n\tj = oppCount - 1;\n\tfor (let i = myCount - 1; i >= 0; i--) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j >= 0 && strength[oppFrom + j] > level) {\n\t\t\trunning += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);\n\t\t\tj--;\n\t\t}\n\t\tout[i] = payoff * (out[i] - (running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]])));\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 { storedStrategy } from './cfr.ts';\nimport { markMembers } from './hands.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\t/** A combination's position in the current decision's hand list; -1 between uses. */\n\treadonly position: Int32Array;\n\t/** Each opposing hand's position in the acting list, or -1, per depth: deeper walks reuse `position`. */\n\treadonly at: 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\tposition: new Int32Array(COMBOS).fill(-1),\n\t\tat: make(() => new Int32Array(width)),\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\t\tconst starts = runouts.childStart[nextRound];\n\n\t\tfor (let childBoard = starts[board]; childBoard < starts[board + 1]; childBoard++) {\n\t\t\tconst stored = dealtCards[childBoard * width + width - 1];\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] ? stored : runouts.orbitCard[nextRound][m];\n\t\t\t\tconst map = runouts.maps.combo[runouts.orbitMap[nextRound][m]];\n\t\t\t\tconst blocked = (combo: number): boolean => cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt;\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 (blocked(combo)) 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 (!blocked(hands[k])) 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 (blocked(combo)) 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 lists = ctx.active;\n\tconst listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;\n\tconst activeFrom = lists.start[listSlot];\n\tconst activeCount = lists.count[listSlot];\n\t// Storage, and so the strategy, is laid out by position in this list.\n\tconst stride = activeCount;\n\tconst slotBase = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];\n\tconst strategy = buffers.strategy[depth];\n\tstoredStrategy(ctx, node, slotBase, actions, stride, strategy);\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 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\t// A packed entry's strategy is every hand's it stands for.\n\t\t\t\t\tconst share = strategy[a * stride + i];\n\t\t\t\t\tfor (let m = lists.memberStart[activeFrom + i]; m < lists.memberStart[activeFrom + i + 1]; m++) {\n\t\t\t\t\t\tconst combo = lists.memberCombo[m];\n\t\t\t\t\t\tout[row + combo] += share * value[row + 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// 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\t// Each opposing hand's position in the acting player's list here.\n\tconst position = buffers.position;\n\tmarkMembers(lists, activeFrom, activeCount, position, false);\n\tconst at = buffers.at[depth];\n\tfor (let c = 0; c < colCount; c++) at[cols[c]] = position[hands[cols[c]]];\n\tmarkMembers(lists, activeFrom, activeCount, position, true);\n\tfor (let a = 0; a < actions; a++) {\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// A hand not in the list here cannot be holding it.\n\t\t\tconst r = at[k] < 0 ? 0 : colReach[k] * strategy[a * stride + at[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/Ur9Uv0LBAAgAEECaiEADAELCwNAIAAgBEgEQCAAQQN0IgYgASAFamoiCSACIAZqKwMAIgxEAAAAAAAAAABkBHwgCSsDAC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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 { makeTerminalScratch } from './showdown.ts';\nimport type { HandSpace } from './hands.ts';\nimport { foldValuesHands, foldValuesPacked, showdownValuesHands, showdownValuesPacked } from './hands.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/**\n * Whether a combination is the one stored for its mirror orbit on a board:\n * the lowest combination the board's own symmetries send it to. A board\n * without symmetry stores every hand.\n */\nexport function orbitLeader(runouts: Runouts, round: number, board: number, combo: number): boolean {\n\tconst from = runouts.stabiliserStart[round][board];\n\tconst to = runouts.stabiliserStart[round][board + 1];\n\tfor (let k = from + 1; k < to; k++) {\n\t\tif (runouts.maps.combo[runouts.stabiliserMap[round][k]][combo] < combo) return false;\n\t}\n\treturn true;\n}\n\nconst INT32_MAX = 2 ** 31 - 1;\n\n/** Slot offsets for every decision node. */\nexport interface Layout {\n\t/**\n\t * Where each decision node's storage starts. Its block on a board is\n\t * `actions` rows of the owner's hands live there, in hand-list order —\n\t * entry `i` of their active list — so a row is as long as that list and\n\t * blocked hands take no room. See `blockBase`. Int32 while every slot\n\t * fits one, which keeps the traversal's indexing on integers; Float64,\n\t * exact to 2^53, for a tree past 2^31 slots, where Int32 would wrap.\n\t * With compact storage, a node of a compact round's offset is into its\n\t * chunk of the compact arrays instead.\n\t */\n\treadonly offset: Int32Array | Float64Array;\n\t/** For each list slot `(roundBase[r] + board) * 2 + p`: rows before this board's. */\n\treadonly rowStart: Int32Array;\n\t/** First list index of each round, as `ActiveLists.roundBase`. */\n\treadonly roundBase: 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\t/** Slots one iteration walks: `totalSlots`, and with shared storage what it would be unshared. */\n\treadonly walkedSlots: number;\n\treadonly maxActions: number;\n\treadonly bytes: number;\n\t/**\n\t * Whether some nodes share another's storage (`SpotConfig.shareHistories`):\n\t * a block may then be visited more than once an iteration.\n\t */\n\treadonly shared: boolean;\n\t/**\n\t * Per node, 1 where regret updates are weighted by the actor's own reach:\n\t * nodes whose storage more than one history shares, under\n\t * `shareHistories`. Null otherwise.\n\t */\n\treadonly reachWeighted: Uint8Array | null;\n\t/**\n\t * The first round stored compactly (see `CompactStorage`); the round\n\t * count when none is, so `round >= compactFrom` says whether a node is.\n\t */\n\treadonly compactFrom: number;\n\t/** Slots of compactly stored regrets; 0 without compact storage. */\n\treadonly compactSlots: number;\n\t/** Per node of a compact round: where its hands' scales start in its chunk, else -1. */\n\treadonly handOffset: Float64Array | null;\n\treadonly compactHands: number;\n\t/**\n\t * Compact storage comes in chunks, each its own buffer, because browsers\n\t * refuse an ArrayBuffer of 2 GiB or more. A node's storage is all in one\n\t * chunk: per node of a compact round, which (else -1); its `offset` and\n\t * `handOffset` count from that chunk's start.\n\t */\n\treadonly compactChunk: Int32Array | null;\n\t/** Per chunk: its slots, its hands, and the slots of every chunk before it. */\n\treadonly chunkSlots: readonly number[];\n\treadonly chunkHands: readonly number[];\n\treadonly chunkStart: readonly number[];\n}\n\n/**\n * Compact storage, for `SpotConfig.compactStorage`: from round `from` on,\n * regrets and (with `sums`) strategy sums as 8-bit integers; without sums,\n * each hand's strategy there is read as the current profile.\n */\nexport interface CompactPlan {\n\t/** First round stored compactly, counted from the spot's first. */\n\treadonly from: number;\n\t/** Largest magnitude stored: 127 for 8 bits. */\n\treadonly steps: number;\n\t/** One power-of-two scale per hand per block, else one float64 per block. */\n\treadonly perHand: boolean;\n\t/** Round at random, unbiased, rather than to nearest. */\n\treadonly stochastic: boolean;\n\t/** Keep the regrets as float32: only the sums are dropped. */\n\treadonly float: boolean;\n\t/** Largest buffer to allocate; compact storage is split in chunks no bigger. */\n\treadonly chunkBytes: number;\n\t/**\n\t * Keep 8-bit strategy sums too, with their own per-hand scale, so these\n\t * nodes keep the average strategy. Per-hand scale only.\n\t */\n\treadonly sums: boolean;\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 * @param alias each node's storage owner, from `aliasHistories`: a node\n * owned by another takes its owner's blocks and adds none. Unset, every\n * node owns its own.\n * @param compact compact storage's plan, for `SpotConfig.compactStorage`\n */\nexport function buildLayout(\n\ttree: Tree,\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tbytesPerElement: number,\n\talias?: Int32Array,\n\tcompact?: CompactPlan,\n): Layout {\n\t// How many of each player's hands each board leaves live: a block's rows.\n\tconst roundBase = new Int32Array(runouts.rounds + 1);\n\tfor (let round = 0; round < runouts.rounds; round++) roundBase[round + 1] = roundBase[round] + runouts.counts[round];\n\tconst rowStart = new Int32Array(roundBase[runouts.rounds] * 2);\n\tconst totals = new Int32Array(runouts.rounds * 2);\n\tconst onBoard = new Uint8Array(DECK);\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\tlet live = 0;\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\tif (!orbitLeader(runouts, round, board, combo)) continue;\n\t\t\t\t\tlive++;\n\t\t\t\t}\n\t\t\t\trowStart[(roundBase[round] + board) * 2 + player] = totals[round * 2 + player];\n\t\t\t\ttotals[round * 2 + player] += live;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst offset = new Float64Array(tree.nodeCount).fill(-1);\n\tconst blockOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tconst compactFrom = compact ? compact.from : runouts.rounds;\n\tconst handOffset = compact ? new Float64Array(tree.nodeCount).fill(-1) : null;\n\tconst compactChunk = compact ? new Int32Array(tree.nodeCount).fill(-1) : null;\n\tconst chunkSlots: number[] = [];\n\tconst chunkHands: number[] = [];\n\tconst chunkStart: number[] = [];\n\tconst width = compact?.float ? 4 : 1;\n\tlet total = 0;\n\tlet compactSlots = 0;\n\tlet compactHands = 0;\n\tlet blocks = 0;\n\tlet maxActions = 0;\n\tlet shared = false;\n\tlet walked = 0;\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\tconst hands = totals[tree.round[node] * 2 + tree.player[node]];\n\t\t// An owner always comes before the nodes it owns, so its blocks are placed.\n\t\twalked += actions * hands;\n\t\tif (alias !== undefined && alias[node] !== node) {\n\t\t\tconst owner = alias[node];\n\t\t\tif (owner > node) throw new Error('buildLayout: a storage owner must come before the nodes it owns');\n\t\t\toffset[node] = offset[owner];\n\t\t\tblockOffset[node] = blockOffset[owner];\n\t\t\tif (compact) {\n\t\t\t\thandOffset![node] = handOffset![owner];\n\t\t\t\tcompactChunk![node] = compactChunk![owner];\n\t\t\t}\n\t\t\tshared = true;\n\t\t\tcontinue;\n\t\t}\n\t\tblockOffset[node] = blocks;\n\t\tblocks += runouts.counts[tree.round[node]];\n\t\tif (tree.round[node] >= compactFrom) {\n\t\t\tconst slots = actions * hands;\n\t\t\tlet chunk = chunkSlots.length - 1;\n\t\t\tif (slots * width > compact!.chunkBytes) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`compactStorage.chunkBytes is ${compact!.chunkBytes}, but one decision needs ${slots * width} bytes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (chunk < 0 || (chunkSlots[chunk] + slots) * width > compact!.chunkBytes || chunkHands[chunk] + hands > compact!.chunkBytes) {\n\t\t\t\tchunk++;\n\t\t\t\tchunkSlots.push(0);\n\t\t\t\tchunkHands.push(0);\n\t\t\t\tchunkStart.push(compactSlots);\n\t\t\t}\n\t\t\tcompactChunk![node] = chunk;\n\t\t\toffset[node] = chunkSlots[chunk];\n\t\t\thandOffset![node] = chunkHands[chunk];\n\t\t\tchunkSlots[chunk] += slots;\n\t\t\tchunkHands[chunk] += hands;\n\t\t\tcompactSlots += slots;\n\t\t\tcompactHands += hands;\n\t\t} else {\n\t\t\toffset[node] = total;\n\t\t\ttotal += actions * hands;\n\t\t}\n\t}\n\tconst scales = bytesPerElement === 2 ? blocks * 8 * 2 : 0;\n\tconst compactBytes = !compact\n\t\t? 0\n\t\t: compact.float\n\t\t\t? compactSlots * 4\n\t\t\t: (compactSlots + (compact.perHand ? compactHands : blocks * 8)) * (compact.sums ? 2 : 1);\n\treturn {\n\t\toffset: Math.max(total, ...chunkSlots) <= INT32_MAX ? Int32Array.from(offset) : offset,\n\t\tblockOffset, blocks, totalSlots: total, walkedSlots: walked, maxActions, rowStart, roundBase,\n\t\tbytes: total * bytesPerElement * 2 + scales + compactBytes,\n\t\tshared,\n\t\treachWeighted: shared ? sharedNodes(tree, alias!) : null,\n\t\tcompactFrom, compactSlots, handOffset, compactHands, compactChunk, chunkSlots, chunkHands, chunkStart,\n\t};\n}\n\n/** 1 for every node whose storage more than one node uses, owner included. */\nfunction sharedNodes(tree: Tree, alias: Int32Array): Uint8Array {\n\tconst marks = new Uint8Array(tree.nodeCount);\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (alias[node] !== node) marks[node] = marks[alias[node]] = 1;\n\t}\n\treturn marks;\n}\n\n/**\n * Where a node's block on a board starts: `actions` rows of the owner's hands\n * live on that board, in their hand-list order.\n */\nexport function blockBase(layout: Layout, tree: Tree, node: number, board: number): number {\n\t// Into the compact regrets for a node of a compact round.\n\tconst slot = (layout.roundBase[tree.round[node]] + board) * 2 + tree.player[node];\n\treturn layout.offset[node] + tree.numEdges[node] * layout.rowStart[slot];\n}\n\n/** Accumulated regrets: float, or 16-bit integers scaled per block. */\nexport type RegretStore = Float64Array | Float32Array | Int16Array;\n/** Regrets as one of the stores, or compact storage's 8-bit ones. */\nexport type AnyRegrets = RegretStore | Int8Array;\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\t/**\n\t * Compact storage (`Approximations.compactStorage`), else unset: nodes of\n\t * rounds from `compact.from` on keep only `compactRegret`, one array per\n\t * chunk (`layout.compactChunk`) laid out by `layout.offset` as other\n\t * nodes' regrets are, and each hand's scale in\n\t * `handShift` — a stored integer `q` means `q * 2^(shift - SHIFT_BIAS)`,\n\t * and a shift of 0 means the hand's regrets are all zero. With a block\n\t * scale instead, `compactScale` holds it as `regretScale` does for 16-bit\n\t * storage.\n\t */\n\treadonly compact?: CompactPlan | null;\n\treadonly compactRegret?: readonly (Int8Array | Float32Array)[] | null;\n\treadonly handShift?: readonly Uint8Array[] | null;\n\t/**\n\t * With `compact.sums`: 8-bit strategy sums, laid out as `compactRegret`,\n\t * and their per-hand scales, as `handShift` is for regrets.\n\t */\n\treadonly compactSum?: readonly Uint8Array[] | null;\n\treadonly sumShift?: readonly Uint8Array[] | null;\n\t/** Compact storage's per-block scales, when it keeps one per block rather than per hand. */\n\treadonly compactScale?: 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/** How hand-space vectors move between boards and meet at terminals. */\n\treadonly hands: HandSpace;\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\t/**\n\t * Chance sampling with baselines, for `Approximations.chanceSampling`;\n\t * unset or null for the exact traversal.\n\t */\n\tsampling?: Sampling | null;\n\t/**\n\t * With shared storage (`Layout.shared`), per block the iteration DCFR\n\t * last discounted it in. A shared block is visited once per history that\n\t * reaches it, and only the first visit of an iteration discounts. Unset or\n\t * null for unshared storage, where every block is visited once.\n\t */\n\tdiscounted?: Int32Array | null;\n}\n\n/** How chance sampling picks deals; see `Approximations.chanceSampling`. */\nexport interface SamplingOptions {\n\t/**\n\t * Probability of walking each deal on a training iteration, chosen at\n\t * random per deal and iteration. Default 0.35. Ignored with `every`.\n\t */\n\treadonly p?: number;\n\t/**\n\t * Walk every deal exactly once every this many iterations, in rotation,\n\t * instead of at random. Measured, it converges worse than random at the\n\t * same rate; kept for comparison.\n\t */\n\treadonly every?: number;\n\t/**\n\t * Betting rounds whose deals are sampled, counted from the spot's first:\n\t * from a flop, 1 is the turn and 2 the river. Default every round after\n\t * the first.\n\t */\n\treadonly rounds?: readonly number[];\n\t/**\n\t * How a walked deal's fresh value meets its baseline: 'unbiased' adds\n\t * `(v - b) / p` to the baseline, the VR-MCCFR estimator; 'latest' uses\n\t * `v` itself, the freshest value without the correction.\n\t */\n\treadonly estimator?: 'unbiased' | 'latest';\n\t/** Apply the DCFR discounts a skipped subtree missed when it is next walked. Default true. */\n\treadonly catchUp?: boolean;\n}\n\n/** Where sampling keeps what, for a spot; see `makeSampling`. */\nexport interface SamplingPlan {\n\treadonly rounds: Uint8Array;\n\treadonly p: number;\n\treadonly every: number;\n\treadonly unbiased: boolean;\n\treadonly catchUp: boolean;\n\t/** Per chance node into a sampled round: where its baselines start, else -1. */\n\treadonly baseOffset: Int32Array;\n\t/** Per list slot of a sampled round: offset of that board and player's baseline within a node's. */\n\treadonly boardOffset: Int32Array;\n\t/** Per chance node: where its last-walk entries start, two per child board. */\n\treadonly walkOffset: Int32Array;\n\t/** Baseline values, last-walk entries and blocks the state holds. */\n\treadonly values: number;\n\treadonly walks: number;\n\treadonly blocks: number;\n}\n\n/** Sampling state: baselines, when each was last walked, when each block was last updated. */\nexport interface Sampling extends SamplingPlan {\n\treadonly baseline: Float32Array;\n\treadonly lastWalk: Int32Array;\n\t/** Per block: the iteration it was last updated in, for DCFR catch-up. */\n\treadonly lastUpdate: Int32Array;\n\t/** Memory the state takes. */\n\treadonly bytes: number;\n}\n\n/** The rounds chance sampling samples, of a spot with `rounds` betting rounds. */\nexport function sampledRounds(options: SamplingOptions, rounds: number): number[] {\n\tconst asked = options.rounds ?? Array.from({ length: rounds }, (_, r) => r);\n\treturn asked.filter((r) => r > 0 && r < rounds);\n}\n\n/** Lay out sampling state for a spot. */\nexport function planSampling(\n\ttree: Tree,\n\trunouts: Runouts,\n\tactive: ActiveLists,\n\tlayout: Layout,\n\toptions: SamplingOptions,\n): SamplingPlan {\n\tconst rounds = new Uint8Array(runouts.rounds);\n\tfor (const r of sampledRounds(options, runouts.rounds)) rounds[r] = 1;\n\tconst boardOffset = new Int32Array(active.roundBase[runouts.rounds] * 2);\n\tconst perNode = new Float64Array(runouts.rounds);\n\tfor (let r = 1; r < runouts.rounds; r++) {\n\t\tif (!rounds[r]) continue;\n\t\tlet total = 0;\n\t\tfor (let b = 0; b < runouts.counts[r]; b++) {\n\t\t\tfor (let p = 0; p < 2; p++) {\n\t\t\t\tconst slot = (active.roundBase[r] + b) * 2 + p;\n\t\t\t\tboardOffset[slot] = total;\n\t\t\t\ttotal += active.count[slot];\n\t\t\t}\n\t\t}\n\t\tperNode[r] = total;\n\t}\n\tconst baseOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tconst walkOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tlet values = 0;\n\tlet walks = 0;\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (tree.kind[node] !== NodeKind.Chance) continue;\n\t\tconst next = tree.round[node] + 1;\n\t\tif (next >= runouts.rounds || !rounds[next]) continue;\n\t\tbaseOffset[node] = values;\n\t\twalkOffset[node] = walks;\n\t\tvalues += perNode[next];\n\t\twalks += runouts.counts[next] * 2;\n\t}\n\tif (values > 0x3fffffff) throw new Error('chanceSampling: too many baseline values for this spot');\n\tconst every = options.every ?? 0;\n\tconst p = every > 0 ? 1 / every : (options.p ?? 0.35);\n\tif (!(p > 0 && p <= 1)) throw new Error(`chanceSampling: p must be in (0, 1], got ${p}`);\n\treturn {\n\t\trounds, p, every,\n\t\tunbiased: (options.estimator ?? 'unbiased') === 'unbiased',\n\t\tcatchUp: options.catchUp ?? true,\n\t\tbaseOffset, boardOffset, walkOffset,\n\t\tvalues, walks, blocks: layout.blocks,\n\t};\n}\n\n/** Bytes sampling state takes beyond its plan's small offset tables. */\nexport function samplingBytes(plan: SamplingPlan): number {\n\treturn (plan.values + plan.walks + plan.blocks) * 4;\n}\n\n/**\n * Sampling state over the given storage, or freshly allocated by `allocate`\n * (plain buffers by default; shared ones for a threaded solve, whose threads\n * each keep the state of their own runouts in it).\n */\nexport function makeSampling(\n\tplan: SamplingPlan,\n\tstorage?: { baseline: Float32Array; lastWalk: Int32Array; lastUpdate: Int32Array },\n\tallocate: (bytes: number) => ArrayBuffer | SharedArrayBuffer = (bytes) => new ArrayBuffer(bytes),\n): Sampling {\n\treturn {\n\t\t...plan,\n\t\tbaseline: storage?.baseline ?? new Float32Array(allocate(plan.values * 4)),\n\t\tlastWalk: storage?.lastWalk ?? new Int32Array(allocate(plan.walks * 4)),\n\t\tlastUpdate: storage?.lastUpdate ?? new Int32Array(allocate(plan.blocks * 4)),\n\t\tbytes: samplingBytes(plan),\n\t};\n}\n\n/** Whether a deal is walked on an iteration. */\nfunction sampled(s: Sampling, node: number, board: number, t: number): boolean {\n\tlet h = Math.imul(node ^ Math.imul(board, 0x9e3779b1), 0x85ebca6b);\n\tif (s.every > 0) {\n\t\th ^= h >>> 13;\n\t\th = Math.imul(h, 0xc2b2ae35);\n\t\th ^= h >>> 16;\n\t\treturn ((h >>> 0) + t) % s.every === 0;\n\t}\n\th ^= Math.imul(t, 0x27d4eb2f);\n\th ^= h >>> 15;\n\th = Math.imul(h, 0xc2b2ae35);\n\th ^= h >>> 13;\n\th = Math.imul(h, 0x165667b1);\n\th ^= h >>> 16;\n\treturn (h >>> 0) / 4294967296 < s.p;\n}\n\nconst factorCache: { keepPositive: number; keepNegative: number; keepSum: number }[] = [];\nfunction cachedFactors(t: number): { keepPositive: number; keepNegative: number; keepSum: number } {\n\tlet f = factorCache[t];\n\tif (f === undefined) factorCache[t] = f = dcfrFactors(t);\n\treturn f;\n}\n\n/**\n * What DCFR has a block keep as iteration `iterWeight` (counted from 1)\n * updates it, for every storage the update runs at. The order matters:\n * first, a shared block another history already discounted this iteration\n * keeps everything; then, with chance sampling, the discounts of the\n * iterations a skipped block missed are multiplied in. Marks the block\n * discounted and updated at `iterWeight`. DCFR only: callers check\n * `ctx.dcfr` first, where assembly/engine.ts's `blockFactors` checks it\n * itself and passes CFR+'s factors through.\n */\nfunction blockFactors(\n\tctx: Context,\n\tblock: number,\n\titerWeight: number,\n): { keepPositive: number; keepNegative: number; keepSum: number } {\n\tlet { keepPositive, keepNegative, keepSum } = cachedFactors(iterWeight);\n\tconst discounted = ctx.discounted;\n\tif (discounted !== undefined && discounted !== null) {\n\t\t// Another history already discounted this shared block this iteration.\n\t\tif (discounted[block] === iterWeight) keepPositive = keepNegative = keepSum = 1;\n\t\tdiscounted[block] = iterWeight;\n\t}\n\tconst sampling = ctx.sampling;\n\tif (sampling !== undefined && sampling !== null) {\n\t\t// A subtree chance sampling skipped missed those iterations'\n\t\t// discounts; nothing was added meanwhile, so each sign held.\n\t\tif (sampling.catchUp) {\n\t\t\tfor (let s = sampling.lastUpdate[block] + 1; s < iterWeight; s++) {\n\t\t\t\tconst f = cachedFactors(s);\n\t\t\t\tkeepPositive *= f.keepPositive;\n\t\t\t\tkeepNegative *= f.keepNegative;\n\t\t\t\tkeepSum *= f.keepSum;\n\t\t\t}\n\t\t}\n\t\tsampling.lastUpdate[block] = iterWeight;\n\t}\n\treturn { keepPositive, keepNegative, keepSum };\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 */\nexport interface 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/** Each entry's two cards, beside `list`. */\n\treadonly cardA: Uint8Array;\n\treadonly cardB: Uint8Array;\n\t/**\n\t * Each entry's strength on its final board, beside `list`; final-board\n\t * lists are sorted by it. Zero elsewhere.\n\t */\n\treadonly strength: Int32Array;\n\t/**\n\t * On a board with symmetry left, a list holds one hand per mirror orbit —\n\t * the lowest combination, see `orbitLeader` — standing for the whole\n\t * orbit. Mirrored hands play alike, since the board and both ranges look\n\t * the same after swapping suits, so one hand's strategy, reach and value\n\t * are all of theirs; storing them once is exact, and shortens every vector\n\t * there. Whether a list holds any orbit of more than one hand, beside\n\t * `start`: only those need the weighted deal and terminal kernels.\n\t */\n\treadonly packed: Uint8Array;\n\t/** How many hands each entry stands for, beside `list`: 1 unpacked. */\n\treadonly multiplicity: Float64Array;\n\t/**\n\t * The hands each entry stands for, itself first: `memberCombo` and their\n\t * cards from `memberStart[e]` to `memberStart[e + 1]`.\n\t */\n\treadonly memberStart: Int32Array;\n\treadonly memberCombo: Uint16Array;\n\treadonly memberA: Uint8Array;\n\treadonly memberB: Uint8Array;\n}\n\nfunction buildActiveLists(\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tshowdown: ShowdownTable | null = null,\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 packedSlot = new Uint8Array(slots);\n\tconst entries: number[] = [];\n\tconst entrySlots: number[] = [];\n\tconst memberStart: number[] = [];\n\tconst members: number[] = [];\n\tconst onBoard = new Uint8Array(DECK);\n\tconst seen = new Uint8Array(COMBOS);\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\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\tonBoard.fill(0);\n\t\t\tfor (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;\n\t\t\tconst symmetric = stabStart[board + 1] - stabStart[board] > 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\tconst here: number[] = [];\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\tif (symmetric && !orbitLeader(runouts, round, board, combo)) continue;\n\t\t\t\t\there.push(i);\n\t\t\t\t}\n\t\t\t\t// On a final board, hands in order of strength: a showdown is\n\t\t\t\t// then one contiguous sweep. Order is free everywhere else.\n\t\t\t\tif (showdown !== null && round === runouts.rounds - 1) {\n\t\t\t\t\tconst group = strengthOn(showdown, board);\n\t\t\t\t\there.sort((x, y) => group[index.combos[x]] - group[index.combos[y]] || x - y);\n\t\t\t\t}\n\t\t\t\tfor (const i of here) {\n\t\t\t\t\tconst combo = index.combos[i];\n\t\t\t\t\tentries.push(combo);\n\t\t\t\t\tentrySlots.push(i);\n\t\t\t\t\tmemberStart.push(members.length);\n\t\t\t\t\tmembers.push(combo);\n\t\t\t\t\tif (!symmetric) continue;\n\t\t\t\t\t// The rest of its orbit, which it stands for.\n\t\t\t\t\tseen[combo] = 1;\n\t\t\t\t\tfor (let k = stabStart[board] + 1; k < stabStart[board + 1]; k++) {\n\t\t\t\t\t\tconst image = runouts.maps.combo[stabMap[k]][combo];\n\t\t\t\t\t\tif (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\tpackedSlot[slot] = 1;\n\t\t\t\t\t}\n\t\t\t\t\tfor (let m = memberStart[memberStart.length - 1]; m < members.length; m++) seen[members[m]] = 0;\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\tmemberStart.push(members.length);\n\n\tconst list = Uint16Array.from(entries);\n\tconst cardA = new Uint8Array(list.length);\n\tconst cardB = new Uint8Array(list.length);\n\tconst multiplicity = new Float64Array(list.length);\n\tfor (let e = 0; e < list.length; e++) {\n\t\tcardA[e] = COMBO_CARDS[list[e] * 2];\n\t\tcardB[e] = COMBO_CARDS[list[e] * 2 + 1];\n\t\tmultiplicity[e] = memberStart[e + 1] - memberStart[e];\n\t}\n\tconst memberCombo = Uint16Array.from(members);\n\tconst memberA = new Uint8Array(members.length);\n\tconst memberB = new Uint8Array(members.length);\n\tfor (let m = 0; m < members.length; m++) {\n\t\tmemberA[m] = COMBO_CARDS[members[m] * 2];\n\t\tmemberB[m] = COMBO_CARDS[members[m] * 2 + 1];\n\t}\n\t// Each entry's strength on its final board, for the showdown sweep.\n\tconst strength = new Int32Array(list.length);\n\tif (showdown !== null) {\n\t\tconst last = runouts.rounds - 1;\n\t\tfor (let board = 0; board < runouts.counts[last]; board++) {\n\t\t\tconst group = strengthOn(showdown, board);\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst slot = (roundBase[last] + board) * 2 + player;\n\t\t\t\tfor (let e = start[slot]; e < start[slot] + count[slot]; e++) strength[e] = group[list[e]];\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tstart, count, list, slot: Uint16Array.from(entrySlots), roundBase,\n\t\tcardA, cardB, strength, packed: packedSlot, multiplicity, memberStart: Int32Array.from(memberStart), memberCombo, memberA, memberB,\n\t};\n}\n\nconst strengthScratch = new Int32Array(COMBOS);\n\n/** Each combination's tie-group index on a final board: higher is stronger. Shared scratch. */\nfunction strengthOn(table: ShowdownTable, board: number): Int32Array {\n\tconst orderBase = board * table.stride;\n\tconst groupBase = board * (table.stride + 1);\n\tfor (let g = 0; g < table.groupCount[board]; g++) {\n\t\tfor (let i = table.groupStart[groupBase + g]; i < table.groupStart[groupBase + g + 1]; i++) {\n\t\t\tstrengthScratch[table.order[orderBase + i]] = g;\n\t\t}\n\t}\n\treturn strengthScratch;\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\t/** 52 doubles for the terminal kernels' per-card sums, kept zero between uses. */\n\treadonly cardSums: Float64Array;\n}\n\nexport function 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\tcardSums: new Float64Array(DECK),\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\nexport function 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). Before iteration `t` adds its\n * regrets, accumulated positive regret is scaled by `s^α / (s^α + 1)` with\n * `s = t - 2` (see `dcfrFactors`) and negative regret by `s^β / (s^β + 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 *\n * Each iteration adds its strategy to the sum as it is, not weighted by the\n * hand's own reach (as postflop-solver does). A hand that equilibrium play\n * stops sending to a node then still averages to what its regrets settled on\n * there; with own-reach weighting the near-uniform early iterations swamped\n * it, so play continued off the path was close to random (issue #8). This\n * holds at every precision, here and in assembly/engine.ts. CFR+ keeps the\n * own-reach weighting: its iterates oscillate, and unweighted they averaged\n * to 2–3× the exploitability at the same iteration count.\n */\n// assembly/engine.ts repeats these in its sampling catch-up; keep in step.\nconst DCFR_ALPHA = 1.5;\nconst DCFR_BETA = 0;\nconst DCFR_GAMMA = 3;\n\n/**\n * DCFR's three factors before iteration `t` (counted from 1) adds its own\n * values: what positive regret, negative regret and the strategy sum keep.\n *\n * The positive factor counts iterations from the second, so iteration 2\n * keeps none of iteration 1's positive regret: that came from the uniform\n * starting strategy and says little. Measured against counting from the\n * first, it reaches 0.3% of pot in 10–15% fewer iterations on flop and turn\n * spots and is never worse; with γ 3 rather than 2, on top, it is better\n * still on most and never worse. A restart of the average at powers of 4 was\n * tried too and was worse on the turn.\n */\nexport function dcfrFactors(t: number): { keepPositive: number; keepNegative: number; keepSum: number } {\n\tconst age = t > 2 ? t - 2 : 0;\n\tconst grown = age ** DCFR_ALPHA;\n\tconst shrunk = age ** DCFR_BETA;\n\treturn {\n\t\tkeepPositive: grown / (grown + 1),\n\t\tkeepNegative: shrunk / (shrunk + 1),\n\t\tkeepSum: ((t - 1) / t) ** DCFR_GAMMA,\n\t};\n}\n\n/**\n * What a traversal plays and does. Train plays the current (regret-matched)\n * profile and updates the traverser's regrets and sums; Current plays that\n * same profile and updates nothing, for reading its values; Average plays the\n * average profile; BestResponse has the traverser best-respond to it.\n */\nexport const Mode = { Train: 0, BestResponse: 1, Average: 2, Current: 3 } 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 * Storage and strategy share a layout: `actions` rows of `count` hands.\n *\n * @param source regrets, for the current strategy\n */\nfunction normalise(\n\tsource: AnyRegrets | SumStore,\n\tbase: number,\n\tactions: 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 at = base + i;\n\t\tlet total = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst value = source[at + a * count];\n\t\t\tconst positive = value > 0 ? value : 0;\n\t\t\tstrategy[a * count + i] = 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 * count + i] /= total;\n\t\t} else {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * count + i] = uniform;\n\t\t}\n\t}\n}\n\n/**\n * How near, relative to the larger of the two, an action's value must be to\n * the hand's value at the node to count as tied with it: 2^-20, 8 to 16\n * float32 ulps of the larger. One tolerance for both engines, so they snap\n * alike; under `precision: 'f64'` it also drops real gaps that small, which\n * moves an answer by at most a millionth of the hand's value. Mirrored in\n * assembly/engine.ts. See `snapTies`.\n */\nexport const TIE_TOLERANCE = 2 ** -20;\n\n/**\n * Snap each action value that ties the hand's node value onto it, so the\n * regret it adds is exactly 0 (issue #117).\n *\n * Where a hand's actions are worth the same, its regrets are analytically\n * zero, but the node value is a strategy-weighted sum of the action values\n * and comes out an ulp or so off them, by a sign that depends on the order\n * of every sum beneath: thread count, engine, float width. Regret matching is\n * discontinuous at zero — one positive ulp plays that action purely, none\n * plays uniformly — so those ulps grew into percents of the strategy. A\n * difference within `TIE_TOLERANCE` of the values is rounding, not regret:\n * snapped, tied actions stay uniform whatever the summation order. Both\n * engines snap the same way, before any update reads the values.\n *\n * Laid out as `traverse` keeps them: `actionValues[a * count + i]`.\n */\nexport function snapTies(actionValues: Float64Array, out: Float64Array, actions: number, count: number): void {\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * count;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst v = actionValues[offset + i];\n\t\t\tconst value = out[i];\n\t\t\tconst gap = v < value ? value - v : v - value;\n\t\t\tconst size = v < 0 ? -v : v;\n\t\t\tconst valueSize = value < 0 ? -value : value;\n\t\t\tif (gap <= TIE_TOLERANCE * (size > valueSize ? size : valueSize)) actionValues[offset + i] = value;\n\t\t}\n\t}\n}\n\n/** Current strategy from positive regrets; uniform where there is none. */\nexport function regretMatch(regret: AnyRegrets, base: number, actions: number, count: number, strategy: Float64Array): void {\n\tnormalise(regret, base, actions, count, strategy);\n}\n\n/**\n * Average strategy from accumulated sums, which are never negative.\n *\n * A hand whose sum is zero here has no average to give: under CFR+, whose\n * sums follow the hand's own reach, it never reached this node on its own;\n * under DCFR, whose sums do not (issue #8), only a loaded strategy with gaps,\n * a warm start or 16-bit rounding leaves one. 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 | Uint8Array,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tstrategy: Float64Array,\n\tregret?: AnyRegrets,\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 at = base + i;\n\t\tlet total = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst value = strategySum[at + a * count];\n\t\t\tstrategy[a * count + i] = 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 * count + i] /= 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 * count];\n\t\t\t\tconst positive = value > 0 ? value : 0;\n\t\t\t\tstrategy[a * count + i] = 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 * count + i] /= total;\n\t\t} else {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * count + i] = uniform;\n\t\t}\n\t}\n}\n\n/**\n * One walk of the subtree below `node`, for `traverser`, returning their\n * counterfactual values.\n *\n * Vectors are in hand space: `reachMe`, the result and every buffer for the\n * traverser hold one entry per hand of theirs live on `board` — entry `i` of\n * their active list there — and `reachOpp` likewise for the opponent. The\n * result is valid for the traverser's `count` hands on this board.\n */\nexport function 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\tdepth: number,\n): Float64Array {\n\tconst { tree, runouts } = ctx;\n\tconst out = buffers.value[depth];\n\tconst kind = tree.kind[node];\n\tconst round = tree.round[node];\n\tconst lists = ctx.active;\n\tconst opponent = (1 - traverser) as 0 | 1;\n\tconst mySlot = (lists.roundBase[round] + board) * 2 + traverser;\n\tconst oppSlot = (lists.roundBase[round] + board) * 2 + opponent;\n\tconst myFrom = lists.start[mySlot];\n\tconst myCount = lists.count[mySlot];\n\tconst oppFrom = lists.start[oppSlot];\n\tconst oppCount = lists.count[oppSlot];\n\n\tif (kind === NodeKind.TerminalFold) {\n\t\tconst signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];\n\t\tconst weight = ctx.runoutWeight[round] / ctx.chipScale;\n\t\tconst hands = ctx.hands;\n\t\tif (lists.packed[oppSlot]) {\n\t\t\tfoldValuesPacked(\n\t\t\t\treachOpp, lists.cardA, lists.cardB, lists.memberStart, lists.memberA, lists.memberB,\n\t\t\t\toppFrom, oppCount, myFrom, myCount, hands.same, hands.sameStart[mySlot], signed * weight, buffers.cardSums, out,\n\t\t\t);\n\t\t\treturn out;\n\t\t}\n\t\tfoldValuesHands(\n\t\t\treachOpp, lists.cardA, lists.cardB, oppFrom, oppCount, myFrom, myCount,\n\t\t\thands.same, hands.sameStart[mySlot], signed * weight, buffers.cardSums, out,\n\t\t);\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.TerminalShowdown) {\n\t\tconst weight = ctx.runoutWeight[round] / ctx.chipScale;\n\t\tif (lists.packed[oppSlot]) {\n\t\t\tshowdownValuesPacked(\n\t\t\t\treachOpp, lists.cardA, lists.cardB, lists.memberStart, lists.memberA, lists.memberB, lists.strength,\n\t\t\t\toppFrom, oppCount, myFrom, myCount, tree.payoff[node] * weight, buffers.cardSums, out,\n\t\t\t);\n\t\t\treturn out;\n\t\t}\n\t\tshowdownValuesHands(\n\t\t\treachOpp, lists.cardA, lists.cardB, lists.strength, oppFrom, oppCount, myFrom, myCount,\n\t\t\ttree.payoff[node] * weight, buffers.cardSums, out,\n\t\t);\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.Chance) {\n\t\tfor (let i = 0; i < myCount; i++) out[i] = 0;\n\t\tconst nextRound = round + 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 < myCount; i++) out[i] = ctx.chanceOverride[base + 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 orbitStart = runouts.orbitStart[nextRound];\n\t\tconst upStart = ctx.hands.upStart[nextRound];\n\t\tconst up = ctx.hands.up;\n\t\tconst childMe = buffers.reachFor[traverser][depth];\n\t\tconst childOpp = buffers.reachFor[opponent][depth];\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 starts = runouts.childStart[nextRound];\n\t\tconst first = starts[board];\n\t\tconst last = starts[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\t// Chance sampling decides how each deal's values are had; how they\n\t\t// spread over the deal's mirror images is the same either way.\n\t\tconst sampling = ctx.sampling ?? null;\n\t\tconst sampleHere =\n\t\t\tsampling !== null && mode === Mode.Train && ctx.applyUpdates && !ctx.expandOrbits && sampling.rounds[nextRound] === 1;\n\n\t\tfor (let childBoard = from; childBoard < to; childBoard++) {\n\t\t\tconst childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;\n\t\t\tconst childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;\n\t\t\tconst nMe = lists.count[childMySlot];\n\t\t\tconst nOpp = lists.count[childOppSlot];\n\t\t\tconst firstMember = orbitStart[childBoard];\n\t\t\tconst membersEnd = orbitStart[childBoard + 1];\n\n\t\t\t// Every real deal this board stands for, the stored one first. A\n\t\t\t// child hand's parent is `up`, through the deal's relabelling.\n\t\t\t// Without `expandOrbits`, reach is symmetric under the relabelling,\n\t\t\t// so one walk serves every member and only the values are spread.\n\t\t\tlet value: Float64Array | Float32Array | null = null;\n\t\t\tfor (let m = firstMember; m < membersEnd; m++) {\n\t\t\t\tconst upMe = upStart[m * 2 + traverser];\n\t\t\t\tif (sampleHere && value === null) {\n\t\t\t\t\tvalue = sampledValue(\n\t\t\t\t\t\tctx, sampling!, buffers, traverser, iterWeight, node, child, nextRound, childBoard,\n\t\t\t\t\t\treachMe, reachOpp, childMe, childOpp, depth,\n\t\t\t\t\t);\n\t\t\t\t} else if (value === null || ctx.expandOrbits) {\n\t\t\t\t\tconst upOpp = upStart[m * 2 + opponent];\n\t\t\t\t\tfor (let k = 0; k < nMe; k++) childMe[k] = reachMe[up[upMe + k]];\n\t\t\t\t\tfor (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp[up[upOpp + k]];\n\t\t\t\t\tvalue = traverse(ctx, buffers, mode, traverser, iterWeight, child, childBoard, childMe, childOpp, depth + 1);\n\t\t\t\t}\n\t\t\t\tif (lists.packed[childMySlot]) {\n\t\t\t\t\t// An entry stands for its whole orbit: weight it so, and\n\t\t\t\t\t// share the parent's total among its own orbit below.\n\t\t\t\t\tconst childFrom = lists.start[childMySlot];\n\t\t\t\t\tfor (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k] * lists.multiplicity[childFrom + k];\n\t\t\t\t} else {\n\t\t\t\t\tfor (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (lists.packed[mySlot]) {\n\t\t\tfor (let i = 0; i < myCount; i++) out[i] /= lists.multiplicity[myFrom + i];\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 isTraverser = owner === traverser;\n\n\t// The acting player's hands here: their active list on this board, which\n\t// is also how their storage block is laid out — `actions` rows of\n\t// `activeCount` hands from `slotBase`.\n\tconst listSlot = isTraverser ? mySlot : oppSlot;\n\tconst activeCount = lists.count[listSlot];\n\tconst stride = activeCount;\n\tconst slotBase = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];\n\n\t// Laid out as storage is: `strategy[a * stride + i]`.\n\tconst strategy = buffers.strategy[depth];\n\tconst length = actions * stride;\n\t// A compactly stored node without sums has no average: it plays the\n\t// current profile wherever a strategy is read.\n\tconst compactNode = round >= ctx.layout.compactFrom;\n\tconst chunk = compactNode ? ctx.layout.compactChunk![node] : 0;\n\tconst regrets: AnyRegrets = compactNode ? ctx.compactRegret![chunk] : ctx.regret;\n\tconst compactSums = compactNode && ctx.compact!.sums;\n\tconst current = mode === Mode.Train || mode === Mode.Current || (compactNode && !compactSums);\n\tif (current && buffers.kernels !== null) {\n\t\tconst kernels = buffers.kernels;\n\t\tkernels.input.set(regrets.subarray(slotBase, slotBase + length));\n\t\tkernels.regretMatch(strategy, actions, stride);\n\t} else if (current) {\n\t\tregretMatch(regrets, slotBase, actions, stride, strategy);\n\t} else if (compactSums) {\n\t\taverageStrategy(ctx.compactSum![chunk], slotBase, actions, stride, strategy, regrets);\n\t} else if (buffers.kernels !== null) {\n\t\tconst kernels = buffers.kernels;\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, strategy, ctx.regret);\n\t}\n\n\tif (isTraverser && mode === Mode.BestResponse) {\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, depth + 1,\n\t\t\t);\n\t\t\tif (a === 0) {\n\t\t\t\tfor (let i = 0; i < myCount; i++) out[i] = value[i];\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < myCount; i++) if (value[i] > out[i]) out[i] = value[i];\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tfor (let i = 0; i < myCount; i++) out[i] = 0;\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 row = a * stride;\n\t\tconst source = isTraverser ? reachMe : reachOpp;\n\t\tfor (let i = 0; i < activeCount; i++) childReach[i] = source[i] * strategy[row + i];\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\tdepth + 1,\n\t\t);\n\n\t\tif (isTraverser) {\n\t\t\tconst offset = a * myCount;\n\t\t\tfor (let i = 0; i < myCount; i++) {\n\t\t\t\tactionValues[offset + i] = value[i];\n\t\t\t\tout[i] += strategy[row + i] * value[i];\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 < myCount; i++) out[i] += value[i];\n\t\t}\n\t}\n\n\tif (isTraverser && mode === Mode.Train && ctx.applyUpdates) snapTies(actionValues, out, actions, myCount);\n\tconst weighted = ctx.layout.reachWeighted;\n\tif (weighted !== null && weighted[node] && isTraverser && mode === Mode.Train && ctx.applyUpdates) {\n\t\t// Each history's regret counts as often as this hand plays into it.\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst offset = a * myCount;\n\t\t\tfor (let i = 0; i < myCount; i++) {\n\t\t\t\tactionValues[offset + i] = out[i] + reachMe[i] * (actionValues[offset + i] - out[i]);\n\t\t\t}\n\t\t}\n\t}\n\tif (isTraverser && mode === Mode.Train && ctx.applyUpdates && compactNode) {\n\t\tupdateCompact(\n\t\t\tctx, node, chunk, ctx.layout.blockOffset[node] + board, slotBase,\n\t\t\tctx.layout.handOffset![node] + ctx.layout.rowStart[listSlot], actions, stride, iterWeight,\n\t\t\treachMe, strategy, actionValues, out,\n\t\t);\n\t} else if (isTraverser && mode === Mode.Train && ctx.applyUpdates && ctx.regretScale !== null) {\n\t\tupdateQuantised(\n\t\t\tctx, node, ctx.layout.blockOffset[node] + board, slotBase, actions, stride,\n\t\t\titerWeight, 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 { keepPositive, keepNegative, keepSum } = blockFactors(ctx, ctx.layout.blockOffset[node] + board, iterWeight);\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 * activeCount;\n\t\t\tconst slotRow = slotBase + a * stride;\n\t\t\tconst row = a * stride;\n\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\tconst at = slotRow + i;\n\t\t\t\tconst accumulated = regret[at];\n\t\t\t\tregret[at] = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[offset + i] - out[i];\n\t\t\t\tstrategySum[at] = strategySum[at] * keepSum + strategy[row + 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 * activeCount;\n\t\t\tconst slotRow = slotBase + a * stride;\n\t\t\tconst row = a * stride;\n\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\tconst at = slotRow + 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 + i] - out[i];\n\t\t\t\tregret[at] = updated > 0 ? updated : 0;\n\t\t\t\tstrategySum[at] += iterWeight * reachMe[i] * strategy[row + i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * One deal's values in a sampled chance node's training walk. A deal not\n * walked gives its baseline, the values it returned when last walked; a\n * walked deal gives `b + (v - b) / p` and its `v` becomes the new baseline\n * (with the 'latest' estimator, `v` itself). A deal never walked yet is\n * always walked. Returned in the child's hand space, as a walk's are.\n */\nfunction sampledValue(\n\tctx: Context,\n\ts: Sampling,\n\tbuffers: Buffers,\n\ttraverser: 0 | 1,\n\tt: number,\n\tnode: number,\n\tchild: number,\n\tnextRound: number,\n\tchildBoard: number,\n\treachMe: Float64Array,\n\treachOpp: Float64Array,\n\tchildMe: Float64Array,\n\tchildOpp: Float64Array,\n\tdepth: number,\n): Float64Array | Float32Array {\n\tconst lists = ctx.active;\n\tconst opponent = (1 - traverser) as 0 | 1;\n\tconst childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;\n\tconst nMe = lists.count[childMySlot];\n\tconst at = s.baseOffset[node] + s.boardOffset[childMySlot];\n\tconst walkAt = s.walkOffset[node] + childBoard * 2 + traverser;\n\tconst fresh = s.lastWalk[walkAt] === 0;\n\tif (!fresh && !sampled(s, node, childBoard, t)) return s.baseline.subarray(at, at + nMe);\n\n\tconst childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;\n\tconst nOpp = lists.count[childOppSlot];\n\tconst member = ctx.runouts.orbitStart[nextRound][childBoard];\n\tconst upStart = ctx.hands.upStart[nextRound];\n\tconst up = ctx.hands.up;\n\tconst upMe = upStart[member * 2 + traverser];\n\tconst upOpp = upStart[member * 2 + opponent];\n\tfor (let k = 0; k < nMe; k++) childMe[k] = reachMe[up[upMe + k]];\n\tfor (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp[up[upOpp + k]];\n\tconst value = traverse(ctx, buffers, Mode.Train, traverser, t, child, childBoard, childMe, childOpp, depth + 1);\n\t// The child's buffer is free again, so the estimate goes in place.\n\tconst weight = s.unbiased ? 1 / s.p : 1;\n\tconst baseline = s.baseline;\n\tfor (let k = 0; k < nMe; k++) {\n\t\tconst v = value[k];\n\t\tconst b = baseline[at + k];\n\t\tbaseline[at + k] = v;\n\t\t// `v + (w - 1)(v - b)` is `b + w(v - b)`, and exactly `v` at w = 1.\n\t\tif (!fresh) value[k] = v + (weight - 1) * (v - b);\n\t}\n\ts.lastWalk[walkAt] = t;\n\treturn value;\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. With\n * shared storage it is salted with the history's `node` (else 0): every\n * history that reaches a shared block re-encodes it in an iteration, and with\n * one stream for all of them their roundings would push the same way\n * (issue #94). The node is fixed by the tree, so the salt does not depend on\n * threads or on the order histories are visited in.\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\tnode: number,\n\tblock: number,\n\tslotBase: number,\n\tactions: number,\n\tcount: 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\t({ keepPositive, keepNegative, keepSum } = blockFactors(ctx, block, iterWeight));\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 * count;\n\t\tconst slotRow = slotBase + a * count;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst at = slotRow + 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 + i] - out[i];\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 + i] = updated;\n\n\t\t\t// DCFR adds the strategy unweighted by own reach (issue #8); CFR+ keeps the weight.\n\t\t\tconst added = clamp ? weight * reachMe[i] * strategy[a * count + i] : weight * strategy[a * count + i];\n\t\t\tconst sum = strategySum[at] * oldSum * keepSum + added;\n\t\t\tif (sum > largestSum) largestSum = sum;\n\t\t\tstrategy[a * count + 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\t// Which history is re-encoding a shared block; 0 keeps unshared streams as they were.\n\tconst salt = ctx.layout.shared ? node : 0;\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * count;\n\t\tconst slotRow = slotBase + a * count;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst at = slotRow + i;\n\t\t\tconst r = actionValues[offset + i] * regretStep;\n\t\t\tregret[at] = r < 0 ? r - 0.5 : r + 0.5;\n\t\t\tconst s = strategy[a * count + i] * sumStep + dither(at, iterWeight, salt);\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/** Bias of a compact hand's scale exponent; see `Context.handShift`. */\nconst SHIFT_BIAS = 160;\n/** `2^(shift - SHIFT_BIAS)` for every shift, 0 for a shift of 0. */\nexport const SHIFT_SCALE = Float64Array.from({ length: 256 }, (_, e) => (e === 0 ? 0 : 2 ** (e - SHIFT_BIAS)));\n\n/**\n * The update for a compactly stored node: decode, update in float as the rule\n * says, re-encode; with `sums`, the strategy sum too. Each hand is scaled by\n * its own power of two, chosen so its largest value uses the top of the\n * range; regret matching and the average only compare a hand's own values,\n * so a hand whose values are small beside the block's keeps all its\n * precision. Rounding is at random with odds set by the remainder (unless\n * `stochastic` is off), so each stored value is right on average; the\n * randomness is a hash of the slot's place in all of compact storage and the\n * iteration, so it does not depend on threads or chunks. With shared storage\n * the history's `node` goes into the hash too: every history reaching a\n * shared block re-encodes it, and the same random numbers each time would\n * push its rounding errors the same way instead of letting them cancel\n * (issue #88).\n */\nexport function updateCompact(\n\tctx: Context,\n\tnode: number,\n\tchunk: number,\n\tblock: number,\n\tslotBase: number,\n\thandBase: number,\n\tactions: number,\n\tcount: number,\n\titerWeight: number,\n\treachMe: Float64Array,\n\tstrategy: Float64Array,\n\tactionValues: Float64Array,\n\tout: Float64Array,\n): void {\n\tconst plan = ctx.compact!;\n\tconst q = ctx.compactRegret![chunk];\n\t// Rounding hashes the slot's place in all of compact storage, so how it\n\t// is chunked changes nothing.\n\tconst hashBase = ctx.layout.chunkStart[chunk] + slotBase;\n\t// Which history is re-encoding a shared block; 0 keeps unshared streams as they were.\n\tconst salt = ctx.layout.shared ? node : 0;\n\tconst steps = plan.steps;\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\t({ keepPositive, keepNegative, keepSum } = blockFactors(ctx, block, iterWeight));\n\t\tweight = 1;\n\t}\n\n\tif (plan.float) {\n\t\tfor (let k = 0; k < actions * count; k++) {\n\t\t\tconst accumulated = q[slotBase + k];\n\t\t\tconst updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[k % count];\n\t\t\tq[slotBase + k] = clamp && updated < 0 ? 0 : updated;\n\t\t}\n\t\treturn;\n\t}\n\n\tif (!plan.perHand) {\n\t\t// One scale for the block, as 16-bit storage keeps.\n\t\tconst scales = ctx.compactScale!;\n\t\tconst old = scales[block];\n\t\tlet largest = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst row = a * count;\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\tconst accumulated = q[slotBase + row + i] * old;\n\t\t\t\tlet updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[row + i] - out[i];\n\t\t\t\tif (clamp && updated < 0) updated = 0;\n\t\t\t\tactionValues[row + i] = updated;\n\t\t\t\tconst magnitude = updated < 0 ? -updated : updated;\n\t\t\t\tif (magnitude > largest) largest = magnitude;\n\t\t\t}\n\t\t}\n\t\tconst step = largest > 0 ? steps / largest : 0;\n\t\tconst stochastic = plan.stochastic;\n\t\t// One hash per row, stepped on for each hand.\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst row = a * count;\n\t\t\tlet h = stochastic ? streamSeed(hashBase + row, iterWeight, salt) : 0;\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\tconst value = actionValues[row + i] * step;\n\t\t\t\tlet rounded: number;\n\t\t\t\tif (stochastic) {\n\t\t\t\t\th = nextState(h);\n\t\t\t\t\trounded = Math.floor(value + (h >>> 0) / 4294967296);\n\t\t\t\t} else {\n\t\t\t\t\trounded = Math.round(value);\n\t\t\t\t}\n\t\t\t\tq[slotBase + row + i] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;\n\t\t\t}\n\t\t}\n\t\tscales[block] = largest / steps;\n\t\treturn;\n\t}\n\n\tconst shifts = ctx.handShift![chunk];\n\tconst stochastic = plan.stochastic;\n\tconst sums = plan.sums ? ctx.compactSum![chunk] : null;\n\tconst sumShifts = plan.sums ? ctx.sumShift![chunk] : null;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst scale = SHIFT_SCALE[shifts[handBase + i]];\n\t\tlet largest = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\tconst accumulated = q[slotBase + k] * scale;\n\t\t\tlet updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[i];\n\t\t\tif (clamp && updated < 0) updated = 0;\n\t\t\tactionValues[k] = updated;\n\t\t\tconst magnitude = updated < 0 ? -updated : updated;\n\t\t\tif (magnitude > largest) largest = magnitude;\n\t\t}\n\t\tconst exponent = scaleExponent(largest, steps);\n\t\tshifts[handBase + i] = exponent;\n\t\tconst inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];\n\t\t// One hash per hand, stepped on for each action.\n\t\tlet h = stochastic || sums !== null ? streamSeed(hashBase + i, iterWeight, salt) : 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\tconst value = actionValues[k] * inverse;\n\t\t\tlet rounded: number;\n\t\t\tif (stochastic) {\n\t\t\t\th = nextState(h);\n\t\t\t\trounded = Math.floor(value + (h >>> 0) / 4294967296);\n\t\t\t} else {\n\t\t\t\trounded = Math.round(value);\n\t\t\t}\n\t\t\tq[slotBase + k] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;\n\t\t}\n\n\t\tif (sums === null) continue;\n\t\t// The strategy sum, as 16-bit storage keeps it but scaled per hand:\n\t\t// the average divides each hand's sums by their own total, so the\n\t\t// scale cancels there just as it does for regret matching.\n\t\tconst sumScale = SHIFT_SCALE[sumShifts![handBase + i]];\n\t\tlet largestSum = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\t// DCFR adds the strategy unweighted by own reach (issue #8); CFR+ keeps the weight.\n\t\t\tconst added = clamp ? weight * reachMe[i] * strategy[k] : weight * strategy[k];\n\t\t\tconst sum = sums[slotBase + k] * sumScale * keepSum + added;\n\t\t\tstrategy[k] = sum;\n\t\t\tif (sum > largestSum) largestSum = sum;\n\t\t}\n\t\tconst sumExponent = scaleExponent(largestSum, COMPACT_SUM_STEPS);\n\t\tsumShifts![handBase + i] = sumExponent;\n\t\tconst sumInverse = sumExponent === 0 ? 0 : 1 / SHIFT_SCALE[sumExponent];\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\th = nextState(h);\n\t\t\tconst rounded = Math.floor(strategy[k] * sumInverse + (h >>> 0) / 4294967296);\n\t\t\tsums[slotBase + k] = rounded < COMPACT_SUM_STEPS ? rounded : COMPACT_SUM_STEPS;\n\t\t}\n\t}\n}\n\n/** Largest strategy sum compact storage keeps per hand: the top of a byte. */\nexport const COMPACT_SUM_STEPS = 255;\n\n/**\n * A hand's scale exponent: the smallest power of two that brings `largest`\n * within `steps`, read off the float's exponent bits, biased by\n * `SHIFT_BIAS`; 0, for all zeros, below the smallest scale there is.\n */\nexport function scaleExponent(largest: number, steps: number): number {\n\tif (!(largest > 0)) return 0;\n\tEXPONENT_FLOAT[0] = largest / steps;\n\tconst high = EXPONENT_BITS[1];\n\tlet exponent = ((high >>> 20) & 0x7ff) - 1023 + SHIFT_BIAS;\n\tif ((high & 0xfffff) !== 0 || EXPONENT_BITS[0] !== 0) exponent++;\n\treturn exponent < 1 ? 0 : exponent > 255 ? 255 : exponent;\n}\n\n/**\n * Start of a slot's random stream on an iteration, for rounding a run of\n * values with `nextState`; `salt` tells apart histories sharing the slot\n * (0 when none do). Never zero, the stream's fixed point.\n */\nfunction streamSeed(slot: number, iteration: number, salt: number): number {\n\treturn Math.imul(slot ^ Math.imul(iteration, 0x9e3779b1) ^ Math.imul(salt, 0x7feb352d) ^ 0x5bd1e995, 0x85ebca6b) | 1;\n}\n\n/** One step of a random stream: the next state, whose `(h >>> 0) / 2^32` is uniform in [0, 1). */\nfunction nextState(h: number): number {\n\th ^= h >>> 15;\n\th = Math.imul(h, 0x2c1b3c6d);\n\treturn h ^ (h >>> 12);\n}\n\n/** Scratch for reading a float's exponent bits (little-endian: the high word second). */\nconst EXPONENT_FLOAT = new Float64Array(1);\nconst EXPONENT_BITS = new Uint32Array(EXPONENT_FLOAT.buffer);\n\n/**\n * The strategy a block's storage stands for, outside training: the average,\n * or the current profile where compact storage keeps no average.\n */\nexport function storedStrategy(\n\tctx: Context,\n\tnode: number,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tstrategy: Float64Array,\n): void {\n\tif (ctx.tree.round[node] >= ctx.layout.compactFrom && ctx.compact!.sums) {\n\t\tconst chunk = ctx.layout.compactChunk![node];\n\t\taverageStrategy(ctx.compactSum![chunk], base, actions, count, strategy, ctx.compactRegret![chunk]);\n\t} else if (ctx.tree.round[node] >= ctx.layout.compactFrom) {\n\t\tregretMatch(ctx.compactRegret![ctx.layout.compactChunk![node]], base, actions, count, strategy);\n\t} else {\n\t\taverageStrategy(ctx.strategySum, base, actions, count, strategy, ctx.regret);\n\t}\n}\n\n/**\n * A deterministic uniform value in [0, 1) for a slot on an iteration, from\n * the stream `salt` picks; salt 0 is the stream unshared storage has always\n * used. Distinct salts give a slot distinct hash inputs on every iteration.\n */\nexport function dither(slot: number, iteration: number, salt = 0): number {\n\tlet h = Math.imul(slot ^ Math.imul(iteration, 0x9e3779b1) ^ Math.imul(salt, 0x27d4eb2f), 0x85ebca6b);\n\th ^= h >>> 13;\n\th = Math.imul(h, 0xc2b2ae35);\n\th ^= h >>> 16;\n\treturn (h >>> 0) / 4294967296;\n}\n\n/** See `Solver.rootValues`. */\nexport interface RootValues {\n\treadonly totals: readonly [number, number];\n\treadonly values: readonly [Float64Array, Float64Array];\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\t/**\n\t * One root pass per player under the average profile (`Mode.Average`) or\n\t * the current one (`Mode.Current`): each player's chips per hand, as\n\t * `expectedValue` gives them for the average, and a copy of their root\n\t * counterfactual values, one per hand of their root active list.\n\t */\n\trootValues(mode: typeof Mode.Average | typeof Mode.Current): RootValues;\n\t/**\n\t * Root EV in chips for each combination, indexed like `COMBO_CARDS`, from\n\t * root counterfactual values `rootValues` returned for `player`: each\n\t * hand's value over the opponent mass it can be dealt against. Zero for a\n\t * combination off the root list or with no opponent hand to face.\n\t */\n\thandEvs(player: 0 | 1, values: Float64Array): Float64Array;\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 * The whole-tree traversal `iterate` and the other passes run now: this\n\t * thread's own, or what `useRoot` routed them to. For wrapping it.\n\t */\n\treadonly root: RootTraversal;\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\t// Hand-space vectors for a round and board, from combination-indexed\n\t// arrays, and back.\n\tconst lists = ctx.active;\n\tconst listOf = (round: number, board: number, player: 0 | 1): [number, number] => {\n\t\tconst slot = (lists.roundBase[round] + board) * 2 + player;\n\t\treturn [lists.start[slot], lists.count[slot]];\n\t};\n\tconst gather = (source: Float64Array, round: number, board: number, player: 0 | 1, into: Float64Array): void => {\n\t\tconst [from, count] = listOf(round, board, player);\n\t\tfor (let i = 0; i < count; i++) into[i] = source[lists.list[from + i]];\n\t};\n\n\tconst run = (mode: Mode, traverser: 0 | 1, iterWeight: number): Float64Array => {\n\t\tgather(ctx.players[0].weights, 0, 0, 0, reach0);\n\t\tgather(ctx.players[1].weights, 0, 0, 1, reach1);\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, 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\tconst [from, count] = listOf(0, 0, traverser);\n\t\tlet sum = 0;\n\t\tfor (let i = 0; i < count; i++) sum += weights[lists.list[from + i]] * lists.multiplicity[from + i] * values[i];\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\tget root() {\n\t\t\treturn root;\n\t\t},\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\t// Hand-space vectors for the chance node's own board, which at the\n\t\t\t// shard boundary is always board 0 of its round.\n\t\t\treturn traverse(ctx, buffers, mode, traverser, iterWeight, node, 0, me, opp, 0);\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\trootValues(mode) {\n\t\t\tif (mode === Mode.Current && ctx.regret.length === 0 && !ctx.compactRegret) {\n\t\t\t\tthrow new Error('The current profile needs regrets, and an analysis-only run has none');\n\t\t\t}\n\t\t\t// Each root vector is a buffer the next traversal reuses, so it is\n\t\t\t// read and copied before the other player's pass.\n\t\t\tconst one = (player: 0 | 1): [number, Float64Array] => {\n\t\t\t\tconst values = root(mode, player, 0);\n\t\t\t\treturn [total(values, player), values.slice(0, listOf(0, 0, player)[1])];\n\t\t\t};\n\t\t\tconst [total0, values0] = one(0);\n\t\t\tconst [total1, values1] = one(1);\n\t\t\treturn { totals: [total0, total1], values: [values0, values1] };\n\t\t},\n\t\thandEvs(player, values) {\n\t\t\tconst opponent = ctx.players[1 - player];\n\t\t\tconst evs = new Float64Array(COMBOS);\n\t\t\tconst [from, count] = listOf(0, 0, player);\n\t\t\tif (values.length !== count) {\n\t\t\t\tthrow new Error(`Player ${player} has ${count} root hands, but ${values.length} values were given`);\n\t\t\t}\n\t\t\tconst scale = ctx.runoutWeight[0];\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t// A packed entry's value is each of its mirrored hands' own.\n\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\t\t\tconst combo = lists.memberCombo[m];\n\t\t\t\t\tconst a = COMBO_CARDS[combo * 2];\n\t\t\t\t\tconst b = COMBO_CARDS[combo * 2 + 1];\n\t\t\t\t\t// Summed directly rather than by inclusion-exclusion over\n\t\t\t\t\t// cards, so a hand with nothing to face gets exactly zero\n\t\t\t\t\t// mass, not a rounding residue to divide by. Board-blocked\n\t\t\t\t\t// opponent hands already weigh zero.\n\t\t\t\t\tlet mass = 0;\n\t\t\t\t\tfor (let j = 0; j < opponent.count; j++) {\n\t\t\t\t\t\tconst other = opponent.combos[j];\n\t\t\t\t\t\tconst c = COMBO_CARDS[other * 2];\n\t\t\t\t\t\tconst d = COMBO_CARDS[other * 2 + 1];\n\t\t\t\t\t\tif (c !== a && c !== b && d !== a && d !== b) mass += opponent.weights[other];\n\t\t\t\t\t}\n\t\t\t\t\tevs[combo] = mass > 0 ? values[i] / (mass * scale) : 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn evs;\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\tvoid live;\n\t\t\tvoid liveCount;\n\t\t\tconst round = ctx.tree.round[node];\n\t\t\tconst opponent = (1 - traverser) as 0 | 1;\n\t\t\t// Values depend on the opponent's reach alone. A packed list can\n\t\t\t// carry it only when mirrored hands hold equally much, as they do\n\t\t\t// for any reach the solve itself produces.\n\t\t\tconst [oppFrom, oppCount] = listOf(round, board, opponent);\n\t\t\tlet symmetric = true;\n\t\t\tfor (let j = 0; j < oppCount && symmetric; j++) {\n\t\t\t\tconst own = reachOpp[lists.list[oppFrom + j]];\n\t\t\t\tfor (let m = lists.memberStart[oppFrom + j] + 1; m < lists.memberStart[oppFrom + j + 1]; m++) {\n\t\t\t\t\tif (reachOpp[lists.memberCombo[m]] !== own) symmetric = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst members = (player: 0 | 1): Uint16Array => {\n\t\t\t\tconst [from, count] = listOf(round, board, player);\n\t\t\t\treturn lists.memberCombo.slice(lists.memberStart[from], lists.memberStart[from + count]);\n\t\t\t};\n\t\t\tif (!symmetric) {\n\t\t\t\t// Values are linear in the opponent's reach, so they are the\n\t\t\t\t// sum of the values against each opposing hand alone, which\n\t\t\t\t// are walked with every hand apart. Slower, by about the\n\t\t\t\t// number of opposing hands over 64.\n\t\t\t\tconst theirs = members(opponent).filter((combo) => reachOpp[combo] !== 0);\n\t\t\t\tconst mine = members(traverser);\n\t\t\t\tconst handReach = Float64Array.from(theirs, (combo) => reachOpp[combo]);\n\t\t\t\tconst rows = pairValues(ctx, node, board, traverser, theirs, handReach, mine, mine.length);\n\t\t\t\tconst result = new Float64Array(COMBOS);\n\t\t\t\tfor (let k = 0; k < theirs.length; k++) {\n\t\t\t\t\tfor (const combo of mine) result[combo] += rows[k * COMBOS + combo];\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t// Mirrored deals below need not see symmetric reach, so they 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 me = new Float64Array(COMBOS);\n\t\t\t\tconst opp = new Float64Array(COMBOS);\n\t\t\t\tgather(reachMe, round, board, traverser, me);\n\t\t\t\tgather(reachOpp, round, board, opponent, opp);\n\t\t\t\tconst value = traverse(ctx, buffers, Mode.Average, traverser, 0, node, board, me, opp, 0);\n\t\t\t\tconst result = new Float64Array(COMBOS);\n\t\t\t\tconst [from, count] = listOf(round, board, traverser);\n\t\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\t\t\t\tresult[lists.memberCombo[m]] = value[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\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\t// In range order, as callers read it: hands the board blocks play\n\t\t\t// uniformly, as they always have.\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 slot = (lists.roundBase[ctx.tree.round[node]] + board) * 2 + owner;\n\t\t\tconst from = lists.start[slot];\n\t\t\tconst count = lists.count[slot];\n\t\t\tconst base = ctx.layout.offset[node] + actions * ctx.layout.rowStart[slot];\n\t\t\tconst strategy = new Float64Array(actions * count);\n\t\t\tstoredStrategy(ctx, node, base, actions, count, strategy);\n\t\t\tconst probs = new Float64Array(index.count * actions).fill(1 / actions);\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t// A packed entry's strategy is its whole orbit's.\n\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\t\t\tconst at = index.slot[lists.memberCombo[m]];\n\t\t\t\t\tfor (let a = 0; a < actions; a++) probs[at * actions + a] = strategy[a * count + i];\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","// Generated by scripts/build-wasm.ts from assembly/engine.ts. Do not edit.\n/** The traversal engine, 7342 bytes of WebAssembly. */\nexport const ENGINE_WASM = 'AGFzbQEAAAABcAtgBH9/f38AYAd/f39/f3x/AGADf39/AGACf38AYAF/AGAGf39/f39/AX9gCH9/f39/f39/AGAMf3x/f39/f39/f39/AGAMf39/f39/f39/f39/AX9gCn9/f39/fX19fX8Bf2AJf39/f319fX1/AX8CDwEDZW52Bm1lbW9yeQIAAAMREAUGAAEBAgIHAwQDAAgJCgQGmwNIfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AU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IAIAxBAWohDAwBCwsDQCABIA1KBEAgCiANQQJ0aiAIIAYgDUEBdGovAQBBAnRqKgIAOAIAIA1BAWohDQwBCwsgACACIAQgCSAKIAtBAWoQACEAA0AgDiAPSARAIA5BAnQiASAAaiICKgIAIRQgASAQaiIBKgIAIRUgASAUOAIAIBJFBEAgAiAUIzFDAACAv5IgFCAVk5SSOAIACyAOQQFqIQ4MAQsLIBEjOjYCACAACysAIAAkQSAFJEIgBiRDIAckRCAIJEUgCUEARyRGIAEgAkEAIAMgBEEAEAALKwAgACRBIAQkQiAFJEMgBiREIAckRSAIQQBHJEYgAUEAQQAgAiADQQAQAAuOAgAgACgCACQAIAAoAgQkASAAKAIIJAIgACgCDCQDIAAoAhAkBCAAKAIUJAUgACgCGCQGIAAoAhwkByAAKAIgJAggACgCJCQJIAAoAigkCiAAKAIsJAsgACgCMCQMIAAoAjQkDSAAKAI4JA4gACgCPCQPIABBQGsoAgAkECAAKAJEJBEgACgCSCQSIAAoAkwkEyAAKAJQJBQgACgCVCQVIAAoAlgkFiAAKAJcJBcgACgCYCQYIAAoAmQkGSAAKAJoJBogACgCbCQbIAAoAnAkHCAAKAJ0JB0gACgCeCQeIAAoAnwkHyAAKAKAASQgIAAoAoQBJCEgACgCiAEkIiAAKAKMASQjIAAoApABuCQkCw==';\n","// Generated by scripts/build-wasm.ts from assembly/engine.ts. Do not edit.\n/** The traversal engine over shared memory, 7345 bytes of WebAssembly. */\nexport const ENGINE_SHARED_WASM = 'AGFzbQEAAAABcAtgBH9/f38AYAd/f39/f3x/AGADf39/AGACf38AYAF/AGAGf39/f39/AX9gCH9/f39/f39/AGAMf3x/f39/f39/f39/AGAMf39/f39/f39/f39/AX9gCn9/f39/fX19fX8Bf2AJf39/f319fX1/AX8CEgEDZW52Bm1lbW9yeQIDAICABAMREAUGAAEBAgIHAwQDAAgJCgQGmwNIfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEA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IA1KBEAgCiANQQJ0aiAIIAYgDUEBdGovAQBBAnRqKgIAOAIAIA1BAWohDQwBCwsgACACIAQgCSAKIAtBAWoQACEAA0AgDiAPSARAIA5BAnQiASAAaiICKgIAIRQgASAQaiIBKgIAIRUgASAUOAIAIBJFBEAgAiAUIzFDAACAv5IgFCAVk5SSOAIACyAOQQFqIQ4MAQsLIBEjOjYCACAACysAIAAkQSAFJEIgBiRDIAckRCAIJEUgCUEARyRGIAEgAkEAIAMgBEEAEAALKwAgACRBIAQkQiAFJEMgBiREIAckRSAIQQBHJEYgAUEAQQAgAiADQQAQAAuOAgAgACgCACQAIAAoAgQkASAAKAIIJAIgACgCDCQDIAAoAhAkBCAAKAIUJAUgACgCGCQGIAAoAhwkByAAKAIgJAggACgCJCQJIAAoAigkCiAAKAIsJAsgACgCMCQMIAAoAjQkDSAAKAI4JA4gACgCPCQPIABBQGsoAgAkECAAKAJEJBEgACgCSCQSIAAoAkwkEyAAKAJQJBQgACgCVCQVIAAoAlgkFiAAKAJcJBcgACgCYCQYIAAoAmQkGSAAKAJoJBogACgCbCQbIAAoAnAkHCAAKAJ0JB0gACgCeCQeIAAoAnwkHyAAKAKAASQgIAAoAoQBJCEgACgCiAEkIiAAKAKMASQjIAAoApABuCQkCw==';\n","/**\n * The browser build's engine threads: started ahead of time, borrowed by solves.\n *\n * Purpose: everything behind `enableThreads` (`poker-flopsolve/threads`), kept\n * out of `platform/browser.ts` so the main browser build carries none of it.\n * See that file for why the threads must be started before a solve.\n */\n\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { ENGINE_CONTROL } from '../engine.ts';\nimport { serveEngine } from '../engine-thread.ts';\n\n/** A spawned solver thread. */\ninterface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The parts of the Web Worker API used here, typed locally: the project builds without DOM typings. */\ninterface WebWorker {\n\tpostMessage(message: unknown, transfer?: unknown[]): void;\n\tterminate(): void;\n\tonmessage: ((event: { data: unknown }) => void) | null;\n\tonerror: ((event: { message?: string; preventDefault?(): void }) => void) | null;\n}\n\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n}\n\ninterface BrowserGlobals {\n\tWorker?: new (url: string) => WebWorker;\n\tMessageChannel?: new () => { port1: MessagePortLike; port2: unknown };\n\tBlob?: new (parts: string[], options: { type: string }) => object;\n\tURL: { createObjectURL(blob: object): string; revokeObjectURL(url: string): void };\n\tcrossOriginIsolated?: boolean;\n\tnavigator?: { hardwareConcurrency?: number };\n\tWebAssembly?: { Memory: new (descriptor: { initial: number; maximum: number; shared: boolean }) => object };\n}\n\n/** One pre-started engine thread. */\ninterface Thread {\n\treadonly worker: WebWorker;\n\t/**\n\t * Where its solves are posted. A message posted on the Worker object\n\t * itself does not reach a running child while the parent is blocked in\n\t * `Atomics.wait` (Chromium), and a solve blocks right after posting; a\n\t * transferred MessagePort delivers regardless.\n\t */\n\treadonly port: MessagePortLike;\n\tbusy: boolean;\n}\n\n/** Where the pool is published on `globalThis`. */\nexport const THREADS_KEY = Symbol.for('poker-flopsolve.browser-threads');\n\n/** What the main build sees of the pool. */\nexport interface ThreadProvider {\n\tidle(): number;\n\ttotal(): number;\n\tspawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle;\n}\n\ntype Holder = Record<symbol, (ThreadProvider & { threads: Thread[] }) | undefined>;\n\n/** The engine threads started so far, shared by every copy of this module. */\nfunction pool(): Thread[] {\n\tconst holder = globalThis as unknown as Holder;\n\tholder[THREADS_KEY] ??= {\n\t\tthreads: [],\n\t\tidle: () => idleThreads(),\n\t\ttotal: () => pool().length,\n\t\tspawn: (setup, onError) => spawn(setup, onError),\n\t};\n\treturn holder[THREADS_KEY]!.threads;\n}\n\nfunction idleThreads(): number {\n\treturn pool().filter((thread) => !thread.busy).length;\n}\n\n/** Stop a thread for good and forget it. */\nfunction drop(thread: Thread): void {\n\tthread.worker.terminate();\n\tthread.busy = true;\n\tconst threads = pool();\n\tconst at = threads.indexOf(thread);\n\tif (at >= 0) threads.splice(at, 1);\n}\n\n/** `ENGINE_CONTROL.command`'s value that ends a thread's solve. */\nconst COMMAND_EXIT = 1;\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nfunction spawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst thread = pool().find((candidate) => !candidate.busy);\n\tif (!thread) throw new Error('No idle engine thread; call enableThreads() from poker-flopsolve/threads first');\n\tthread.busy = true;\n\tthread.worker.onerror = (event) => {\n\t\tevent.preventDefault?.();\n\t\tdrop(thread);\n\t\tonError(new Error(`Engine thread failed: ${event.message ?? 'unknown error'}`));\n\t};\n\tthread.port.postMessage(setup);\n\tconst control = new Int32Array(setup.control);\n\tlet released = false;\n\treturn {\n\t\tterminate() {\n\t\t\t// A run may be closed twice; by then the thread may serve another.\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tif (!pool().includes(thread)) return;\n\t\t\t// A solve a thread failed: its error event is still queued, and\n\t\t\t// would fail whichever solve borrowed the thread next. Which thread\n\t\t\t// failed is not recorded, so every one of that solve's goes;\n\t\t\t// `prepareThreads` starts replacements.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.failed) !== 0) {\n\t\t\t\tdrop(thread);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Whether this solve finished or gave up on starting, tell the\n\t\t\t// thread its solve is over: it returns to waiting for the next\n\t\t\t// setup, having started this one or not (serveEngine checks for\n\t\t\t// exit before it first waits). A thread that died is dropped by\n\t\t\t// its error handler instead.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.command) !== COMMAND_EXIT) {\n\t\t\t\tAtomics.store(control, ENGINE_CONTROL.command, COMMAND_EXIT);\n\t\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\t}\n\t\t\tthread.busy = false;\n\t\t\tthread.worker.onerror = () => drop(thread);\n\t\t},\n\t};\n}\n\n/** Why threads cannot run here, or null if they can. */\nexport function threadsUnavailableReason(): string | null {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tif (typeof g.Worker !== 'function' || typeof g.Blob !== 'function' || typeof g.MessageChannel !== 'function') {\n\t\treturn 'no Web Workers here';\n\t}\n\tif (g.crossOriginIsolated !== true) {\n\t\treturn 'the page is not cross-origin isolated (serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp)';\n\t}\n\tif (typeof SharedArrayBuffer !== 'function') return 'no SharedArrayBuffer here';\n\ttry {\n\t\t// Throws where blocking is not allowed: a page's main thread.\n\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);\n\t} catch {\n\t\treturn 'Atomics.wait is not allowed on this thread; solve inside a Web Worker';\n\t}\n\ttry {\n\t\tnew g.WebAssembly!.Memory({ initial: 1, maximum: 1, shared: true });\n\t} catch {\n\t\treturn 'no shared WebAssembly memory here';\n\t}\n\treturn null;\n}\n\n/** How long a thread may take to start before it is given up on. */\nconst START_MS = 30_000;\n\nfunction startThread(url: string): Promise<Thread | null> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\treturn new Promise((resolve) => {\n\t\tlet worker: WebWorker;\n\t\ttry {\n\t\t\tworker = new g.Worker!(url);\n\t\t} catch {\n\t\t\tresolve(null);\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t}, START_MS);\n\t\tconst channel = new g.MessageChannel!();\n\t\tworker.onmessage = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tworker.onmessage = null;\n\t\t\tworker.onerror = null;\n\t\t\tresolve({ worker, port: channel.port1, busy: false });\n\t\t};\n\t\tworker.postMessage(null, [channel.port2]);\n\t\tworker.onerror = (event) => {\n\t\t\tevent.preventDefault?.();\n\t\t\tclearTimeout(timer);\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t};\n\t});\n}\n\n/**\n * Start engine threads so that solves can use up to `count` threads, this one\n * included, and resolve to how many a solve can use now. Threads already\n * started are kept; idle ones beyond `count` are stopped, so `prepareThreads(1)`\n * stops every thread no open run is holding. Resolves to 1 where threads cannot run; see\n * {@link threadsUnavailableReason}.\n * @param count threads wanted, this one included; defaults to `navigator.hardwareConcurrency`\n */\nexport function prepareThreads(count?: number): Promise<number> {\n\t// One call at a time, so two calls in a row cannot both start the missing threads.\n\tconst next = pending.then(() => resize(count));\n\tpending = next.catch(() => undefined);\n\treturn next;\n}\n\nlet pending: Promise<unknown> = Promise.resolve();\n\nasync function resize(count?: number): Promise<number> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tconst wanted = Math.max(1, Math.floor(count ?? g.navigator?.hardwareConcurrency ?? 1));\n\tconst threads = pool();\n\tfor (let i = threads.length - 1; i >= 0 && threads.length > wanted - 1; i--) {\n\t\tif (!threads[i].busy) drop(threads[i]);\n\t}\n\tconst missing = wanted - 1 - threads.length;\n\tif (missing > 0 && threadsUnavailableReason() === null) {\n\t\t// The worker is this module's own loop, as source: there is no file\n\t\t// to point a worker at that every bundler would ship.\n\t\tconst source =\n\t\t\t`const serveEngine = ${serveEngine.toString()};\\n` +\n\t\t\t'onmessage = (event) => {\\n' +\n\t\t\t'\\tevent.ports[0].onmessage = (solve) => serveEngine(solve.data);\\n' +\n\t\t\t\"\\tpostMessage('ready');\\n\" +\n\t\t\t'};\\n';\n\t\tconst url = g.URL.createObjectURL(new g.Blob!([source], { type: 'text/javascript' }));\n\t\ttry {\n\t\t\tconst started = await Promise.all(Array.from({ length: missing }, () => startThread(url)));\n\t\t\tfor (const thread of started) if (thread) threads.push(thread);\n\t\t} finally {\n\t\t\tg.URL.revokeObjectURL(url);\n\t\t}\n\t}\n\treturn threadsUnavailableReason() === null ? Math.min(wanted, 1 + idleThreads()) : 1;\n}\n","/**\n * Browser platform.\n *\n * Purpose: stand in for `node.ts` in a browser build, with the same exports.\n *\n * Out of the box the browser build is single-threaded: no worker threads, no\n * SharedArrayBuffer, and so no cross-origin isolation headers needed on the\n * page. Run the solve inside a Web Worker to keep the page responsive; see\n * `examples/browser-worker.ts`.\n *\n * Threads are opt-in, through `enableThreads` in `poker-flopsolve/threads`\n * (`prepareThreads` here). A browser starts a Web Worker only asynchronously —\n * a worker spawned and then waited on with `Atomics.wait` never starts, as\n * the thread that would start it is the one blocked — while a solve is\n * synchronous. So the workers are started ahead of time, once, and wait idle\n * between solves; a solve with `workers: n` hands n − 1 of them its setup and\n * takes them back on `close()`. Only the WebAssembly engine is threaded here:\n * its workers share the engine's memory exactly as Node's do and run the same\n * loop (`serveEngine`), so a fixed thread count gives the same answer as Node\n * at that count.\n *\n * The pool lives in `browser-threads.ts` and is found through `globalThis`\n * under a registered symbol, so the threads entry and the main build share\n * it even when bundled separately, and the main build carries none of it.\n */\n\nimport type { WorkerSetup } from '../parallel.ts';\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { compiledEngine } from '../engine.ts';\nimport type { ThreadProvider } from './browser-threads.ts';\nimport { THREADS_KEY } from './browser-threads.ts';\n\nexport { prepareThreads, threadsUnavailableReason } from './browser-threads.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'browser';\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/** The engine threads `prepareThreads` started, if any. */\nfunction provider(): ThreadProvider | undefined {\n\treturn (globalThis as unknown as Record<symbol, ThreadProvider | undefined>)[THREADS_KEY];\n}\n\n/**\n * The most threads a solve can use now: one, plus the idle engine threads\n * when the WebAssembly engine is to run and can run over shared memory here.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadLimit(engine: boolean): number {\n\tconst threads = provider();\n\tif (!engine || !threads || threads.idle() === 0) return 1;\n\treturn compiledEngine('shared') ? 1 + threads.idle() : 1;\n}\n\n/** One, plus every idle engine thread `prepareThreads` started. */\nexport function defaultWorkerCount(): number {\n\treturn 1 + (provider()?.idle() ?? 0);\n}\n\n/**\n * Why a solve gets fewer threads than it asked for, for the one warning.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadAdvice(engine: boolean): string {\n\tif (!provider()) return 'call enableThreads() from poker-flopsolve/threads first, in a cross-origin isolated Web Worker';\n\tif (!engine) return 'browser threads run only the WebAssembly engine (default engine, f32 precision)';\n\treturn 'the other threads are held by open runs; close() a run to free its threads';\n}\n\n/** Never called: the browser build threads only the WebAssembly engine; see `threadLimit`. */\nexport function spawnWorker(_setup: WorkerSetup, _onError: (error: Error) => void): WorkerHandle {\n\tthrow new Error('The browser build threads only the WebAssembly engine; use workers: 1 with this solve');\n}\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nexport function spawnEngineWorker(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst threads = provider();\n\tif (!threads) throw new Error('No engine threads; call enableThreads() from poker-flopsolve/threads first');\n\treturn threads.spawn(setup, onError);\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\n/** How a pool starts its workers; the platform's `spawnWorker` unless a test swaps it. */\nexport type SpawnWorker = (setup: WorkerSetup, onError: (error: Error) => void) => WorkerHandle;\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\t/** Set, never cleared, once any thread's part of a step threw; see src/worker.ts. */\n\tfailed: 7,\n\tsize: 8,\n} as const;\n\n/** What a threaded step throws once a thread has failed mid-iteration, here or in src/engine.ts. */\nexport const THREAD_FAILED_ERROR =\n\t'A solver thread failed mid-iteration; this run cannot continue. Close it and solve again, or use workers: 1.';\n\n/**\n * What a threaded step throws once another thread has gone silent past the\n * backstop, here or in src/engine.ts.\n */\nexport const THREAD_LOST_ERROR =\n\t'A solver thread stopped answering mid-iteration; it may have run out of memory or been killed. ' +\n\t'This run cannot continue. Close it and solve again, or use workers: 1.';\n\n/**\n * The backstop on how long the main thread waits for the others in one step.\n *\n * A thread that throws reports itself in shared memory, but one killed\n * without unwinding (a Node worker out of V8 heap, a worker the browser\n * kills) runs no `catch` or `finally`, and its error event cannot reach a\n * main thread waiting in `Atomics.wait`. Every thread's shard is the same\n * size as the main thread's own and runs under the same load, so the wait is\n * bounded at a multiple of the main thread's own shard time, and never under\n * the floor: it only fires with one thread both 20× slower than the main\n * thread and over a minute late.\n */\nexport const THREAD_BACKSTOP_FLOOR_MS = 60_000;\nexport const THREAD_BACKSTOP_FACTOR = 20;\n\n/**\n * How long, from the step's dispatch, the main thread waits for the others.\n * @param ownMs the main thread's own shard time this step\n * @param floorMs the shortest wait; tests shorten it\n */\nexport function backstopMs(ownMs: number, floorMs: number = THREAD_BACKSTOP_FLOOR_MS): number {\n\treturn Math.max(floorMs, THREAD_BACKSTOP_FACTOR * ownMs);\n}\n\n/** How long one `Atomics.wait` of {@link awaitThreads} sleeps before looking again. */\nconst WAIT_SLICE_MS = 50;\n/** A wait that overruns its slice by more than this was a stopped process, not a slow thread. */\nconst STOPPED_MS = 1_000;\n\n/**\n * Wait, after this thread's own shard, for the other threads to count\n * themselves done in `control[slot]`, or until the backstop passes.\n *\n * Time the whole process spends stopped mid-wait (a debugger, Ctrl-Z, a VM\n * pause, a sleep the clock counts) stops every thread alike, so it extends\n * the backstop rather than counting against the others.\n *\n * @param control the pool's control slots\n * @param slot the slot the other threads count themselves done in\n * @param target how many other threads there are\n * @param dispatched `performance.now()` when the step was dispatched\n * @param floorMs the backstop's floor; see {@link backstopMs}\n * @param stopped whether to stop waiting for some other reason\n * @returns {@link THREAD_LOST_ERROR} once the backstop passes, else null\n */\nexport function awaitThreads(\n\tcontrol: Int32Array,\n\tslot: number,\n\ttarget: number,\n\tdispatched: number,\n\tfloorMs: number | undefined,\n\tstopped: () => boolean,\n): Error | null {\n\t// Monotonic, so a change to the wall clock is not taken for a silent thread.\n\tlet giveUp = dispatched + backstopMs(performance.now() - dispatched, floorMs);\n\tfor (;;) {\n\t\tconst done = Atomics.load(control, slot);\n\t\tif (done >= target || stopped()) return null;\n\t\tconst before = performance.now();\n\t\tif (before > giveUp) return new Error(THREAD_LOST_ERROR);\n\t\tAtomics.wait(control, slot, done, WAIT_SLICE_MS);\n\t\tconst overrun = performance.now() - before - WAIT_SLICE_MS;\n\t\tif (overrun > STOPPED_MS) giveUp += overrun;\n\t}\n}\n\nexport const COMMAND = { work: 0, exit: 1 } as const;\n\n/** How long worker threads may take to start before a solve gives up on them. */\nexport const WORKER_START_MS = 30_000;\nexport const WORKER_START_ERROR =\n\t'Worker threads did not start within 30 s. Run with workers: 1, or check that worker threads can load this package.';\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\t/** Compact storage's regrets and hand scales, else null. */\n\treadonly compactRegret: SharedArrayBuffer[] | null;\n\treadonly handShift: SharedArrayBuffer[] | null;\n\treadonly compactSum: SharedArrayBuffer[] | null;\n\treadonly sumShift: SharedArrayBuffer[] | null;\n\treadonly compactScale: SharedArrayBuffer | null;\n\t/**\n\t * Chance sampling's baselines, last walks and last updates, else null.\n\t * Each thread reads and writes only its own runouts' entries.\n\t */\n\treadonly sampling: readonly [SharedArrayBuffer, SharedArrayBuffer, 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 * @param spawn how each worker is started\n * @param backstopFloorMs the shortest a step waits for the workers; see {@link backstopMs}\n */\nexport function startPool(\n\tctx: Context,\n\tsolver: Solver,\n\tplan: ShardPlan,\n\tpayload: unknown,\n\tworkers: number,\n\tspawn: SpawnWorker = spawnWorker,\n\tbackstopFloorMs: number = THREAD_BACKSTOP_FLOOR_MS,\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\t// Workers wrap each of sampling's buffers whole, so each must be its own shared buffer.\n\tconst samplingBuffers = ctx.sampling\n\t\t? ([ctx.sampling.baseline, ctx.sampling.lastWalk, ctx.sampling.lastUpdate] as const).map((view) => {\n\t\t\t\tif (!(view.buffer instanceof SharedArrayBuffer) || view.byteOffset !== 0 || view.byteLength !== view.buffer.byteLength) {\n\t\t\t\t\tthrow new Error('chanceSampling on worker threads needs its state in shared buffers of its own');\n\t\t\t\t}\n\t\t\t\treturn view.buffer;\n\t\t\t})\n\t\t: 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\tcompactRegret: ctx.compactRegret?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\thandShift: ctx.handShift?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\tcompactSum: ctx.compactSum?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\tsumShift: ctx.sumShift?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\tcompactScale: (ctx.compactScale?.buffer as SharedArrayBuffer | undefined) ?? null,\n\t\t\tsampling: samplingBuffers ? [samplingBuffers[0], samplingBuffers[1], samplingBuffers[2]] : 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 = spawn(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\t// A worker that fails to start reports it by an event, which cannot be\n\t// delivered while this thread waits here, so the wait is bounded.\n\tconst deadline = Date.now() + WORKER_START_MS;\n\tfor (;;) {\n\t\tconst ready = Atomics.load(control, CONTROL.ready);\n\t\tif (ready >= spawned || failure) break;\n\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\telse Atomics.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 failed = (): Error | null =>\n\t\tfailure ?? (Atomics.load(control, CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);\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\t\tconst dispatched = performance.now();\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\t// A worker whose walk throws says so in `failed` and counts itself\n\t\t// done, as its error event cannot reach this thread while it waits.\n\t\t// One killed without unwinding does neither, hence the backstop.\n\t\tfailure ??= awaitThreads(control, CONTROL.done, spawned, dispatched, backstopFloorMs, () => failure !== null);\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t};\n\n\tconst traverseAll: RootTraversal = (mode, traverser, iterWeight) => {\n\t\t// Pass A: walk the round above the split to capture what each worker\n\t\t// needs, applying nothing.\n\t\tctx.applyUpdates = false;\n\t\tctx.chanceOverride = null;\n\t\tctx.chanceCollect = (node, reachMe, reachOpp) => {\n\t\t\tconst entry = plan.entryIndexOf[node];\n\t\t\texchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);\n\t\t\texchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);\n\t\t};\n\t\ttry {\n\t\t\tsolver.traverseRoot(mode, traverser, iterWeight);\n\t\t} finally {\n\t\t\tctx.chanceCollect = null;\n\t\t}\n\n\t\t// Leaves this thread's own partial in `chanceValues`.\n\t\tdispatch(mode, traverser, iterWeight);\n\n\t\tfor (let w = 0; w < spawned; w++) {\n\t\t\tconst base = reachFloats + w * entryCount * COMBOS;\n\t\t\tfor (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];\n\t\t}\n\n\t\t// Pass B: finish that round from the totals, now applying updates.\n\t\tctx.chanceOverride = chanceValues;\n\t\tctx.applyUpdates = true;\n\t\ttry {\n\t\t\tconst value = solver.traverseRoot(mode, traverser, iterWeight);\n\t\t\ttotal.set(value.subarray(0, COMBOS));\n\t\t} finally {\n\t\t\tctx.chanceOverride = null;\n\t\t}\n\t\treturn total;\n\t};\n\n\treturn {\n\t\tworkers,\n\t\ttraverse(mode, traverser, iterWeight) {\n\t\t\t// Once any thread has failed, so does every step after, before it\n\t\t\t// touches anything.\n\t\t\tconst dead = failed();\n\t\t\tif (dead) throw dead;\n\t\t\ttry {\n\t\t\t\treturn traverseAll(mode, traverser, iterWeight);\n\t\t\t} catch (error) {\n\t\t\t\t// This thread's own part may have thrown with the workers still\n\t\t\t\t// walking; no later step may run over them.\n\t\t\t\tAtomics.store(control, CONTROL.failed, 1);\n\t\t\t\tthrow error;\n\t\t\t}\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 * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs where WebAssembly SIMD is available,\n * on one thread or several; otherwise the JavaScript traversal in cfr.ts\n * runs. A second build, which only `poker-flopsolve/wasm-storage` carries,\n * keeps 16-bit and compact storage the same way (`EngineInput.storage`).\n *\n * WebAssembly memory is one buffer, but Chromium lets it reach wasm32's full\n * 4 GiB, plain or shared, made at that size or grown to it, where it refuses\n * any ArrayBuffer over 2 GiB less 2 MiB (measured in Chromium 153 by\n * bin/memory-ceiling.ts; issue #84). So compact storage needs no chunks of\n * its own in the engine: its chunks are regions of the one memory, laid out\n * as the JavaScript engine's buffers are.\n */\n\nimport { COMBOS } from './cards.ts';\nimport type { ActiveLists, CompactPlan, Layout, PlayerIndex, RegretStore, RootTraversal, SamplingPlan, SumStore } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\nimport { awaitThreads, THREAD_FAILED_ERROR, WORKER_START_ERROR, WORKER_START_MS } from './parallel.ts';\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; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\treturn compileInto(modules, kind, kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM);\n}\n\n/** Compile base64 WebAssembly into `cache[kind]` once; null there where unavailable. */\nfunction compileInto(cache: Record<'plain' | 'shared', object | null | undefined>, kind: 'plain' | 'shared', text: string): object | null {\n\tif (cache[kind] !== undefined) return cache[kind]!;\n\tcache[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tcache[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tcache[kind] = null;\n\t}\n\treturn cache[kind]!;\n}\n\n/**\n * The engine with 16-bit and compact storage (issue #84), as base64 for plain\n * and shared memory. Only `poker-flopsolve/wasm-storage` holds the bytes, so\n * a build that never imports it carries none of them; a solve opts in by\n * passing it as `SolveOptions.wasmStorage`.\n */\nexport interface WasmStorage {\n\treadonly plain: string;\n\treadonly shared: string;\n}\n\nconst storageModules = new WeakMap<WasmStorage, Record<'plain' | 'shared', object | null | undefined>>();\n\n/** The storage engine compiled, over plain or shared memory; null where unavailable. */\nfunction compiledStorage(source: WasmStorage, kind: 'plain' | 'shared'): object | null {\n\tlet cache = storageModules.get(source);\n\tif (!cache) storageModules.set(source, (cache = { plain: undefined, shared: undefined }));\n\treturn compileInto(cache, kind, source[kind]);\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n\t/** Chance sampling's layout, for `Approximations.chanceSampling`; unset for none. */\n\treadonly sampling?: SamplingPlan;\n\t/** Bytes left unused below the layout, rounded up to 16; tests set it to place every pointer past 2 GiB. */\n\treadonly lowBytes?: number;\n\t/**\n\t * 16-bit or compact storage, run by the storage engine `source` holds;\n\t * unset for 32-bit storage on the default engine. `quantised` keeps\n\t * the nodes before `compact.from` (all of them without `compact`) at 16\n\t * bits, as `precision: 'i16'` does.\n\t */\n\treadonly storage?: { readonly source: WasmStorage; readonly quantised: boolean; readonly compact: CompactPlan | null };\n}\n\n/** Compact storage's arrays, per chunk, as `Context` holds them; views onto the engine's memory. */\nexport interface EngineCompact {\n\treadonly regret: (Int8Array | Float32Array)[];\n\treadonly handShift: Uint8Array[] | null;\n\treadonly sum: Uint8Array[] | null;\n\treadonly sumShift: Uint8Array[] | null;\n\treadonly scale: Float64Array | null;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory: 32-bit, or 16-bit with `EngineInput.storage`. */\n\treadonly regret: RegretStore;\n\treadonly strategySum: SumStore;\n\t/** With 16-bit storage, the per-block scales `Context.regretScale` and `sumScale` hold; else null. */\n\treadonly regretScale: Float64Array | null;\n\treadonly sumScale: Float64Array | null;\n\t/** With compact storage, its arrays; else null. */\n\treadonly compact: EngineCompact | null;\n\t/** Chance sampling's state, as views onto the engine's memory; null without sampling. */\n\treadonly sampling: { baseline: Float32Array; lastWalk: Int32Array; lastUpdate: Int32Array } | null;\n\t/** With shared storage, `Context.discounted` as a view onto the engine's memory; else null. */\n\treadonly discounted: Int32Array | null;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\treadonly shard: readonly [number, number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\treadonly partial: number;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n\t/** With shared storage: where the discount marks, the block table and the weighted nodes (or 0) sit. */\n\treadonly shared?: readonly [number, number, number];\n\t/** Set for the storage engine, whose updates need the iteration on every walk. */\n\treadonly storage?: boolean;\n\t/**\n\t * With chance sampling, `setSampling`'s arguments as the main thread\n\t * passed them: its state is in the shared memory, and each thread walks\n\t * and marks only its own runouts' deals.\n\t */\n\treadonly sampling?: SamplingArgs;\n}\n\n/** `EngineExports.setSampling`'s arguments, in order. */\nexport type SamplingArgs = Parameters<EngineExports['setSampling']>;\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** The most memory the engine lays out: just under wasm32's 4 GB. */\nconst MAX_MEMORY = 0xffff0000;\n\n/**\n * Control slots shared with engine workers. `failed` is set, never cleared,\n * once any thread's part of a step threw: the main thread waits in\n * `Atomics.wait` and so never sees a worker's error event while a step runs.\n */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the runouts at the plan's round, as src/parallel.ts does for\n * the JavaScript engine.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: {\n\t\tplan: ShardPlan;\n\t\tthreads: number;\n\t\tspawn: SpawnEngineWorker;\n\t\t/** The shortest a step waits for the other threads; see `awaitThreads` in src/parallel.ts. */\n\t\tbackstopFloorMs?: number;\n\t},\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst storage = input.storage ?? null;\n\tconst compiledModule = storage\n\t\t? compiledStorage(storage.source, shared ? 'shared' : 'plain')\n\t\t: compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst compact = storage?.compact ?? null;\n\tconst quantised = storage?.quantised ?? false;\n\t// Its accumulators alone would pass wasm32's 4 GB, so no engine; checked\n\t// before anything is built. Such a layout is also the only kind that\n\t// holds offsets as Float64, which the engine's 32-bit offset table could\n\t// not take.\n\tconst width = quantised ? 2 : 4;\n\tconst compactBytes = !compact\n\t\t? 0\n\t\t: compact.float\n\t\t\t? layout.compactSlots * 4\n\t\t\t: (layout.compactSlots + (compact.perHand ? layout.compactHands : 0)) * (compact.sums ? 2 : 1);\n\tif (layout.totalSlots * width * 2 + compactBytes > MAX_MEMORY || !(layout.offset instanceof Int32Array)) return null;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tconst maxCount = Math.max(4, ...active.count);\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\tconst pieces: { data: ArrayBufferView | null; bytes: number }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16 });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(Int32Array.from(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.packed), add(Float32Array.from(active.multiplicity)), add(active.memberStart),\n\t\tadd(active.memberA), add(active.memberB), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * width), // regret\n\t\tadd(null, layout.totalSlots * width), // strategy sums\n\t];\n\tconst REGRET = common[common.length - 2];\n\tconst SUMS = common[common.length - 1];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\tconst partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;\n\t// Chance sampling, only when asked for.\n\tconst plan = input.sampling;\n\tconst sample = plan\n\t\t? {\n\t\t\t\tbaseOffset: add(plan.baseOffset), boardOffset: add(plan.boardOffset), walkOffset: add(plan.walkOffset),\n\t\t\t\tblockOffset: add(layout.blockOffset), baseline: add(null, plan.values * 4), lastWalk: add(null, plan.walks * 4),\n\t\t\t\tlastUpdate: add(null, plan.blocks * 4),\n\t\t\t}\n\t\t: null;\n\t// History sharing's once-an-iteration discount marks, only when storage is shared.\n\tconst share = layout.shared\n\t\t? {\n\t\t\t\tmarks: add(null, layout.blocks * 4),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : add(layout.blockOffset),\n\t\t\t\tweighted: layout.reachWeighted ? add(layout.reachWeighted) : -1,\n\t\t\t}\n\t\t: null;\n\t// 16-bit and compact storage's settings, scales and chunks, only on the storage engine.\n\tconst chunks = compact ? layout.chunkSlots.length : 0;\n\tconst stored = storage\n\t\t? {\n\t\t\t\tblock: add(null, 128),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),\n\t\t\t\tregretScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tsumScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tcompactChunk: compact ? add(layout.compactChunk) : -1,\n\t\t\t\thandOffset: compact ? add(Int32Array.from(layout.handOffset!)) : -1,\n\t\t\t\ttables: compact ? add(null, chunks * 4 * 5) : -1,\n\t\t\t\tregrets: layout.chunkSlots.map((slots) => add(null, slots * (compact!.float ? 4 : 1))),\n\t\t\t\tshifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tsums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],\n\t\t\t\tsumShifts: compact?.sums ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tcompactScale: compact && !compact.perHand && !compact.float ? add(null, layout.blocks * 8) : -1,\n\t\t\t}\n\t\t: null;\n\n\tconst offsets: number[] = [];\n\tlet total = 64 + Math.ceil(Math.max(input.lowBytes ?? 0, 0) / 16) * 16;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > MAX_MEMORY) return null;\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[common.length] = offsets[mine.buffers];\n\t\thead[common.length + 1] = depthBytes;\n\t\thead[common.length + 2] = rowBytes;\n\t\thead[common.length + 3] = offsets[mine.cardSums];\n\t\thead[common.length + 4] = input.chipScale;\n\t\tif (stored) head[common.length + 5] = offsets[stored.block];\n\t}\n\tif (stored) {\n\t\tconst at = (slot: number): number => (slot >= 0 ? offsets[slot] : 0);\n\t\tconst block = new Uint32Array(memory.buffer, offsets[stored.block], 20);\n\t\tblock.set([\n\t\t\tquantised ? 1 : 0, compact ? compact.from : 255, !compact ? 0 : compact.float ? 3 : compact.perHand ? 1 : 2,\n\t\t\tcompact?.sums ? 1 : 0, compact?.stochastic ? 1 : 0, compact?.steps ?? 127,\n\t\t\tat(stored.regretScale), at(stored.sumScale), offsets[stored.blockOffset], at(stored.compactChunk),\n\t\t\tat(stored.handOffset),\n\t\t]);\n\t\tif (compact) {\n\t\t\t// Per chunk: where its regrets, hand scales, sums and sum scales sit, and its first slot.\n\t\t\tconst tables = offsets[stored.tables];\n\t\t\tconst table = new Uint32Array(memory.buffer, tables, chunks * 5);\n\t\t\tfor (let c = 0; c < chunks; c++) {\n\t\t\t\ttable[c] = offsets[stored.regrets[c]];\n\t\t\t\ttable[chunks + c] = stored.shifts.length ? offsets[stored.shifts[c]] : 0;\n\t\t\t\ttable[2 * chunks + c] = stored.sums.length ? offsets[stored.sums[c]] : 0;\n\t\t\t\ttable[3 * chunks + c] = stored.sumShifts.length ? offsets[stored.sumShifts[c]] : 0;\n\t\t\t\ttable[4 * chunks + c] = layout.chunkStart[c] >>> 0;\n\t\t\t}\n\t\t\tblock.set([tables, tables + chunks * 4, tables + chunks * 8, tables + chunks * 12, tables + chunks * 16, at(stored.compactScale)], 11);\n\t\t}\n\t}\n\t// The update rule's factors, as float64, which the storage engine reads before each walk.\n\tconst factors = stored ? new Float64Array(memory.buffer, offsets[stored.block] + 80, 4) : null;\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\tlet samplingViews: Engine['sampling'] = null;\n\tlet samplingArgs: SamplingArgs | null = null;\n\tif (plan && sample) {\n\t\tlet mask = 0;\n\t\tfor (let r = 0; r < plan.rounds.length; r++) if (plan.rounds[r]) mask |= 1 << r;\n\t\tsamplingArgs = [\n\t\t\tmask, plan.p, plan.every, plan.unbiased ? 1 : 0, plan.catchUp ? 1 : 0,\n\t\t\toffsets[sample.baseOffset], offsets[sample.boardOffset], offsets[sample.walkOffset],\n\t\t\toffsets[sample.baseline], offsets[sample.lastWalk], offsets[sample.lastUpdate], offsets[sample.blockOffset],\n\t\t];\n\t\tconst a = samplingArgs;\n\t\texports.setSampling(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]);\n\t\tsamplingViews = {\n\t\t\tbaseline: new Float32Array(memory.buffer, offsets[sample.baseline], plan.values),\n\t\t\tlastWalk: new Int32Array(memory.buffer, offsets[sample.lastWalk], plan.walks),\n\t\t\tlastUpdate: new Int32Array(memory.buffer, offsets[sample.lastUpdate], plan.blocks),\n\t\t};\n\t}\n\n\tconst weightedAt = share && share.weighted >= 0 ? offsets[share.weighted] : 0;\n\tif (share) exports.setShared(offsets[share.marks], offsets[share.blockOffset], weightedAt);\n\tconst discounted = share ? new Int32Array(memory.buffer, offsets[share.marks], layout.blocks) : null;\n\n\tconst regret: RegretStore = quantised\n\t\t? new Int16Array(memory.buffer, offsets[REGRET], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum: SumStore = quantised\n\t\t? new Uint16Array(memory.buffer, offsets[SUMS], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst scaleView = (slot: number): Float64Array | null =>\n\t\tslot >= 0 ? new Float64Array(memory.buffer, offsets[slot], layout.blocks) : null;\n\tconst compactViews: EngineCompact | null = stored && compact\n\t\t? {\n\t\t\t\tregret: stored.regrets.map((slot, c) =>\n\t\t\t\t\tcompact.float\n\t\t\t\t\t\t? new Float32Array(memory.buffer, offsets[slot], layout.chunkSlots[c])\n\t\t\t\t\t\t: new Int8Array(memory.buffer, offsets[slot], layout.chunkSlots[c]),\n\t\t\t\t),\n\t\t\t\thandShift: compact.perHand ? stored.shifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tsum: compact.sums ? stored.sums.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkSlots[c])) : null,\n\t\t\t\tsumShift: compact.sums ? stored.sumShifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tscale: scaleView(stored.compactScale),\n\t\t\t}\n\t\t: null;\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.bounds[w], plan.bounds[w + 1]],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tpartial: offsets[partials] + (w - 1) * entries * rowBytes,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t\t...(share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] as const } : {}),\n\t\t\t\t...(stored ? { storage: true } : {}),\n\t\t\t\t...(samplingArgs ? { sampling: samplingArgs } : {}),\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\t// A worker that fails to start reports it by an event, which cannot\n\t\t// be delivered while this thread waits here, so the wait is bounded.\n\t\tconst deadline = Date.now() + WORKER_START_MS;\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\t\telse Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst failed = (): Error | null =>\n\t\tfailure ?? (control && Atomics.load(control, ENGINE_CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);\n\n\t// The iteration a step is for, and its rule, which shared storage's threads need.\n\tlet iteration = 0;\n\tlet dcfrRule = 0;\n\tconst run = (asked: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\t// Once any thread has failed, so does every step after, before it\n\t\t// touches anything.\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\t// The engine knows three modes; the current profile is its Train\n\t\t// with updates off.\n\t\tconst apply = asked === Mode.Current ? 0 : 1;\n\t\tconst mode = asked === Mode.Current ? Mode.Train : asked;\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\titeration = mode === Mode.Train ? iterWeight : 0;\n\t\tdcfrRule = dcfr ? 1 : 0;\n\t\tif (plan || share || stored) exports.setIteration(iteration, dcfrRule);\n\t\t// CFR+ at 16 bits or compact floors a negative regret, as `updateQuantised`\n\t\t// and `updateCompact` do (one only a warm start could bring); 32-bit storage keeps it.\n\t\tfactors?.set([positive, mode === Mode.Train && !dcfr ? 0 : negative, sum, weight]);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tif (apply === 0) exports.setPhase(0, 0);\n\t\t\ttry {\n\t\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\t\t} finally {\n\t\t\t\tif (apply === 0) exports.setPhase(0, 1);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tat = runThreaded(mode, traverser, apply, positive, negative, sum, weight, clamp);\n\t\t\t} catch (error) {\n\t\t\t\t// This thread's own part may have thrown with the workers still\n\t\t\t\t// walking; no later step may run over them.\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.failed, 1);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\t/** One threaded traversal, returning where the root values are. */\n\tconst runThreaded = (\n\t\tmode: number, traverser: 0 | 1, apply: number,\n\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t): number => {\n\t\tconst plan = pool!.plan;\n\t\t// Collect: walk above the split, recording what the workers need.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(1, 0);\n\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t// Every thread walks its slice of the split round.\n\t\tsettings!.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);\n\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\tconst dispatched = performance.now();\n\t\texports.setShard(plan.round, plan.bounds[0], plan.bounds[1]);\n\t\texports.setPhase(0, apply);\n\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 0;\n\t\t\tvalueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);\n\t\t}\n\t\t// A thread whose walk throws says so in `failed` and counts itself\n\t\t// done, as its error event cannot reach this thread while it waits.\n\t\t// One killed without unwinding does neither, hence the backstop.\n\t\tfailure ??= awaitThreads(\n\t\t\tcontrol!, ENGINE_CONTROL.done, threads - 1, dispatched, pool!.backstopFloorMs, () => failure !== null,\n\t\t);\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\tconst partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);\n\t\tfor (let w = 0; w < threads - 1; w++) {\n\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];\n\t\t}\n\t\t// Finish above the split from the totals, now applying updates\n\t\t// unless this is a current-profile read.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(2, apply);\n\t\tconst at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\texports.setPhase(0, 1);\n\t\texports.setShard(-1, 0, 0);\n\t\treturn at;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tregretScale: stored ? scaleView(stored.regretScale) : null,\n\t\tsumScale: stored ? scaleView(stored.sumScale) : null,\n\t\tcompact: compactViews,\n\t\tsampling: samplingViews,\n\t\tdiscounted,\n\t\tthreads,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/**\n * The engine's exports. A pointer one returns is a wasm32 `usize`, which\n * JavaScript receives as a signed 32-bit integer: read it with `>>> 0`, or\n * any address past 2 GiB comes back negative (#62).\n */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\tsetSampling(\n\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t): void;\n\tsetIteration(t: number, dcfr: number): void;\n\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\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 * A solve of another board can seed this one through a card relabelling — a\n * permutation of the deck taking one board onto the other, a rank swap for a\n * nearby flop — through which its runouts and hands are read.\n */\n\nimport type { Context, RegretStore, SumStore } from './cfr.ts';\nimport { COMPACT_SUM_STEPS, regretMatch, scaleExponent, SHIFT_SCALE } from './cfr.ts';\nimport { COMBO_CARDS, COMBOS, DECK, comboIndex } from './cards.ts';\nimport { markMembers } from './hands.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. */\nexport const SIZE_TOLERANCE = 1.35;\n\nexport const REGRET_STEPS = 32767;\nexport const 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, tolerance = SIZE_TOLERANCE): 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, tolerance);\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, tolerance: 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(tolerance) ? best : -1;\n}\n\n/** Read one block — a node on a board — as plain numbers, `actions * count` of them. */\nexport function 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. */\nexport function 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/**\n * Read a compactly stored block as plain numbers: the regrets, unless\n * `regrets` is null, and the strategy sums. Where compact storage keeps no\n * sums its strategy is the current profile, so that is what comes back as\n * the sums: any positive multiple of a strategy averages to it.\n */\nexport function readCompactBlock(\n\tctx: Context,\n\tnode: number,\n\tlistSlot: number,\n\tblock: number,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tregrets: Float64Array | null,\n\tsums: Float64Array,\n): void {\n\tconst plan = ctx.compact!;\n\tconst chunk = ctx.layout.compactChunk![node];\n\tconst q = ctx.compactRegret![chunk];\n\tconst handBase = ctx.layout.handOffset![node] + ctx.layout.rowStart[listSlot];\n\tconst shifts = plan.perHand ? ctx.handShift![chunk] : null;\n\tconst blockScale = !plan.perHand && !plan.float ? ctx.compactScale![block] : 1;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst scale = shifts ? SHIFT_SCALE[shifts[handBase + i]] : blockScale;\n\t\tif (regrets) for (let a = 0; a < actions; a++) regrets[a * count + i] = q[base + a * count + i] * scale;\n\t\tif (!plan.sums) continue;\n\t\tconst sumScale = SHIFT_SCALE[ctx.sumShift![chunk][handBase + i]];\n\t\tconst stored = ctx.compactSum![chunk];\n\t\tfor (let a = 0; a < actions; a++) sums[a * count + i] = stored[base + a * count + i] * sumScale;\n\t}\n\tif (!plan.sums) regretMatch(q, base, actions, count, sums);\n}\n\n/**\n * Write a compactly stored block, encoding it as compact storage does but\n * rounded to nearest: the regrets unless `regrets` is null, the sums where it\n * keeps them unless `sums` is null.\n */\nexport function writeCompactBlock(\n\tctx: Context,\n\tnode: number,\n\tlistSlot: number,\n\tblock: number,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tregrets: Float64Array | null,\n\tsums: Float64Array | null,\n): void {\n\tconst plan = ctx.compact!;\n\tconst chunk = ctx.layout.compactChunk![node];\n\tconst q = ctx.compactRegret![chunk];\n\tconst handBase = ctx.layout.handOffset![node] + ctx.layout.rowStart[listSlot];\n\tconst steps = plan.steps;\n\tconst fit = (value: number, top: number, bottom: number): number => {\n\t\tconst rounded = Math.round(value);\n\t\treturn rounded > top ? top : rounded < bottom ? bottom : rounded;\n\t};\n\tif (regrets && plan.float) {\n\t\tfor (let k = 0; k < actions * count; k++) q[base + k] = regrets[k];\n\t} else if (regrets && !plan.perHand) {\n\t\tlet largest = 0;\n\t\tfor (let k = 0; k < actions * count; k++) largest = Math.max(largest, Math.abs(regrets[k]));\n\t\tconst step = largest > 0 ? steps / largest : 0;\n\t\tfor (let k = 0; k < actions * count; k++) q[base + k] = fit(regrets[k] * step, steps, -steps);\n\t\tctx.compactScale![block] = largest / steps;\n\t} else if (regrets) {\n\t\tconst shifts = ctx.handShift![chunk];\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tlet largest = 0;\n\t\t\tfor (let a = 0; a < actions; a++) largest = Math.max(largest, Math.abs(regrets[a * count + i]));\n\t\t\tconst exponent = scaleExponent(largest, steps);\n\t\t\tshifts[handBase + i] = exponent;\n\t\t\tconst inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];\n\t\t\tfor (let a = 0; a < actions; a++) q[base + a * count + i] = fit(regrets[a * count + i] * inverse, steps, -steps);\n\t\t}\n\t}\n\tif (!sums || !plan.sums) return;\n\tconst stored = ctx.compactSum![chunk];\n\tconst shifts = ctx.sumShift![chunk];\n\tfor (let i = 0; i < count; i++) {\n\t\tlet largest = 0;\n\t\tfor (let a = 0; a < actions; a++) largest = Math.max(largest, sums[a * count + i]);\n\t\tconst exponent = scaleExponent(largest, COMPACT_SUM_STEPS);\n\t\tshifts[handBase + i] = exponent;\n\t\tconst inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];\n\t\tfor (let a = 0; a < actions; a++) stored[base + a * count + i] = fit(sums[a * count + i] * inverse, COMPACT_SUM_STEPS, 0);\n\t}\n}\n\n/** The real cards of a stored board. */\nexport function 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, unless `cards`\n * relabels one onto the other.\n *\n * @param cards for a solve of a different board: each card of `to` to the card\n * of `from` it plays as, a permutation of the deck taking `to`'s board onto\n * `from`'s. Hands and dealt cards map through it too. Unset, the identity.\n * @param tolerance largest ratio between two bet sizes still matched; unset,\n * `SIZE_TOLERANCE`. `Infinity` maps every bet to the nearest one of its kind,\n * which seeds a size the old tree lacked from its neighbour.\n * @returns what matched\n * @throws if the boards differ, or `cards` does not take one onto the other\n */\nexport function warmStart(\n\tto: Context,\n\tfrom: Context,\n\taverages: boolean,\n\tcards?: Uint8Array,\n\ttolerance = SIZE_TOLERANCE,\n): WarmStartReport {\n\tif (!(tolerance >= 1)) throw new Error(`warmStart: the size tolerance is a ratio of at least 1, not ${tolerance}`);\n\t// Each node is copied on its own, so into shared storage every history of\n\t// a group would overwrite the same block and the last would win. From\n\t// shared storage the copy is exact: each node takes its owner's block.\n\tif (to.layout.shared && !from.layout.shared) {\n\t\tthrow new Error('A spot with shareHistories can only warm-start from a solve that shares histories too');\n\t}\n\tconst a = to.runouts.initial;\n\tconst b = from.runouts.initial;\n\tif (cards) checkRelabelling(cards, a, b);\n\telse if (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, unless `warmCards` relabels one onto the other');\n\t}\n\t// A real board of `to` as `from` sees it: its own given board first, in\n\t// its order, then the dealt cards relabelled.\n\tconst asSource = (real: number[]): number[] =>\n\t\tcards ? [...b, ...real.slice(a.length).map((card) => cards[card])] : real;\n\t// Each hand of `to` as the hand of `from` it plays as.\n\tconst comboOf = new Uint16Array(COMBOS);\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tcomboOf[combo] = cards ? comboIndex(cards[COMBO_CARDS[combo * 2]], cards[COMBO_CARDS[combo * 2 + 1]]) : combo;\n\t}\n\tconst match = matchNodes(to.tree, from.tree, tolerance);\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\t// An analysis-only run has none; compact storage may keep all of its regrets compactly.\n\tconst keepsRegrets = (ctx: Context): boolean => ctx.regret.length > 0 || (ctx.compactRegret ?? null) !== null;\n\tconst hasRegret = keepsRegrets(to) && keepsRegrets(from);\n\n\t// A combination's position in the old board's hand list, or -1.\n\tconst position = new Int32Array(COMBOS).fill(-1);\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\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, tolerance);\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, asSource(realCards(to.runouts, round, board)));\n\t\t\t// Blocks are laid out by position in each board's hand list.\n\t\t\tconst oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;\n\t\t\tconst oldFrom = from.active.start[oldSlot];\n\t\t\tconst oldCount = from.active.count[oldSlot];\n\t\t\tconst oldBlock = from.layout.blockOffset[old] + resolved.board;\n\t\t\tconst oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];\n\t\t\tconst oldLength = oldActions * oldCount;\n\t\t\tif (round >= from.layout.compactFrom) {\n\t\t\t\treadCompactBlock(from, old, oldSlot, oldBlock, oldBase, oldActions, oldCount, hasRegret ? oldRegret : null, oldSum);\n\t\t\t} else {\n\t\t\t\tif (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);\n\t\t\t\treadBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);\n\t\t\t}\n\t\t\t// Every hand an old entry stands for is at that entry.\n\t\t\tmarkMembers(from.active, oldFrom, oldCount, position, false);\n\n\t\t\tconst newSlot = (to.active.roundBase[round] + board) * 2 + owner;\n\t\t\tconst newFrom = to.active.start[newSlot];\n\t\t\tconst count = to.active.count[newSlot];\n\t\t\tconst length = actions * 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 < count; i++) {\n\t\t\t\t// An entry stands for its mirror orbit here, which the old solve\n\t\t\t\t// may have stored apart and not played alike: it takes their mean.\n\t\t\t\tconst firstMember = to.active.memberStart[newFrom + i];\n\t\t\t\tconst membersEnd = to.active.memberStart[newFrom + i + 1];\n\t\t\t\tconst share = 1 / (membersEnd - firstMember);\n\t\t\t\tfor (let m = firstMember; m < membersEnd; m++) {\n\t\t\t\t\tconst j = position[resolved.combos[comboOf[to.active.memberCombo[m]]]];\n\t\t\t\t\tif (j < 0) continue;\n\t\t\t\t\tfor (let e = 0; e < actions; e++) {\n\t\t\t\t\t\tconst action = actionOf[e];\n\t\t\t\t\t\tif (action < 0) continue;\n\t\t\t\t\t\tnewRegret[e * count + i] += share * oldRegret[action * oldCount + j];\n\t\t\t\t\t\tnewSum[e * count + i] += share * oldSum[action * oldCount + j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmarkMembers(from.active, oldFrom, oldCount, position, true);\n\n\t\t\tconst block = to.layout.blockOffset[node] + board;\n\t\t\tconst base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];\n\t\t\tif (round >= to.layout.compactFrom) {\n\t\t\t\twriteCompactBlock(to, node, newSlot, block, base, actions, count, hasRegret ? newRegret : null, averages ? newSum : null);\n\t\t\t} else {\n\t\t\t\tif (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS, block, base, length, newRegret);\n\t\t\t\tif (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS, block, base, length, newSum);\n\t\t\t}\n\t\t}\n\t}\n\treturn { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };\n}\n\n/** Throw unless `cards` is a permutation of the deck taking board `a` onto board `b`. */\nfunction checkRelabelling(cards: Uint8Array, a: readonly number[], b: readonly number[]): void {\n\tconst seen = new Uint8Array(DECK);\n\tif (cards.length !== DECK) throw new Error(`A card relabelling maps all ${DECK} cards; got ${cards.length}`);\n\tfor (const card of cards) {\n\t\tif (card >= DECK || seen[card]) throw new Error('A card relabelling must be a permutation of the deck');\n\t\tseen[card] = 1;\n\t}\n\tconst target = new Set(b);\n\tif (a.length !== b.length || a.some((card) => !target.has(cards[card]))) {\n\t\tthrow new Error('The card relabelling must take the board onto the warm start\\'s board');\n\t}\n}\n","/**\n * A stopping rule for solves that never reach an exploitability target: stop\n * once the root play stops moving (issue #100).\n *\n * Purpose: a blueprint with `shareHistories` plateaus several percent of the\n * pot from equilibrium, so `targetPercent` cannot end it, yet its first\n * decisions go on settling and are what a caller reads (issue #85). This\n * reads them cheaply: the average strategy at two nodes, with no\n * best-response pass, so a check costs a tiny fraction of an iteration.\n *\n * The root play is the decision opening the spot (out of position) and, after\n * a check there, in position's: neither player has acted before them, so each\n * decision is played by the whole range and is weighted by it. Its movement\n * between two strategies is, per decision, the total variation of each hand's\n * action mix (half the summed absolute change), averaged over the range by\n * weight; the larger of the two decisions counts. 0.01 means the range's\n * play moved by 1% of its mass. #85 called the root play still once both\n * decisions moved under 1% between checks 20 iterations apart.\n */\n\nimport type { Solution, StrategyView } from './index.ts';\nimport { ActionKind, NodeKind } from './tree.ts';\n\n/** See `SolveOptions.settle`. */\nexport interface SettleOptions {\n\t/** Iterations between checks. Default 20. */\n\treadonly every?: number;\n\t/**\n\t * Movement between consecutive checks, as a share of the range, under\n\t * which the root play counts as still: see `rootPlayMovement`. Default\n\t * 0.01.\n\t */\n\treadonly tolerance?: number;\n\t/** Consecutive still checks before stopping. Default 2. */\n\treadonly patience?: number;\n\t/** Iterations before which no check counts toward `patience`. Default 0. */\n\treadonly minIterations?: number;\n}\n\n/** The strategies `rootPlayMovement` compares; see `rootPlay`. */\nexport interface RootPlay {\n\t/** The root, then in position's decision after a check there, when there is one. */\n\treadonly views: readonly StrategyView[];\n\t/** Range weight per combination of each view's player, indexed like `COMBO_CARDS`. */\n\treadonly weights: readonly Float64Array[];\n}\n\n/** The decisions that make up the root play of a solved spot. */\nexport function rootPlayNodes(solution: Solution): number[] {\n\tconst { tree } = solution.spot;\n\tif (tree.kind[0] !== NodeKind.Decision) return [];\n\tconst nodes = [0];\n\tfor (let e = 0; e < tree.numEdges[0]; e++) {\n\t\tconst edge = tree.firstEdge[0] + e;\n\t\tconst child = tree.edgeChild[edge];\n\t\tif (tree.edgeAction[edge] === ActionKind.Check && tree.kind[child] === NodeKind.Decision) nodes.push(child);\n\t}\n\treturn nodes;\n}\n\n/**\n * The root play of a solution as it stands: the average strategy at the\n * root and at in position's decision after a check. Cheap: two strategy\n * reads, no best-response pass.\n */\nexport function rootPlay(solution: Solution): RootPlay {\n\tconst views = rootPlayNodes(solution).map((node) => solution.strategyAt(node, 0));\n\treturn { views, weights: views.map((view) => solution.spot.players[view.player].weights) };\n}\n\n/**\n * How far the root play moved from `before` to `after`, two readings of the\n * same spot: per decision, the range-weighted mean of each hand's total\n * variation, and the larger over the decisions. 0 is unmoved, 1 is every\n * hand switching to actions it never took.\n */\nexport function rootPlayMovement(before: RootPlay, after: RootPlay): number {\n\tif (before.views.length !== after.views.length) throw new Error('Root plays of different spots cannot be compared');\n\tlet worst = 0;\n\tfor (let d = 0; d < after.views.length; d++) {\n\t\tconst a = before.views[d];\n\t\tconst b = after.views[d];\n\t\tconst actions = b.actions.length;\n\t\tif (a.node !== b.node || a.actions.length !== actions || a.combos.length !== b.combos.length) {\n\t\t\tthrow new Error('Root plays of different spots cannot be compared');\n\t\t}\n\t\tconst weights = after.weights[d];\n\t\tlet moved = 0;\n\t\tlet mass = 0;\n\t\tfor (let i = 0; i < b.combos.length; i++) {\n\t\t\tconst w = weights[b.combos[i]];\n\t\t\tif (!(w > 0)) continue;\n\t\t\tlet tv = 0;\n\t\t\tfor (let k = 0; k < actions; k++) tv += Math.abs(b.probs[i * actions + k] - a.probs[i * actions + k]);\n\t\t\tmoved += (w * tv) / 2;\n\t\t\tmass += w;\n\t\t}\n\t\tif (mass > 0) worst = Math.max(worst, moved / mass);\n\t}\n\treturn worst;\n}\n\n/** Validated settle settings, defaults filled in. */\nexport function settlePlan(options: SettleOptions): Required<SettleOptions> {\n\tconst plan = {\n\t\tevery: options.every ?? 20,\n\t\ttolerance: options.tolerance ?? 0.01,\n\t\tpatience: options.patience ?? 2,\n\t\tminIterations: options.minIterations ?? 0,\n\t};\n\tif (!(Number.isInteger(plan.every) && plan.every > 0)) throw new Error(`settle.every must be a positive whole number; got ${plan.every}`);\n\tif (!(plan.tolerance >= 0)) throw new Error(`settle.tolerance must be 0 or more; got ${plan.tolerance}`);\n\tif (!(Number.isInteger(plan.patience) && plan.patience > 0)) {\n\t\tthrow new Error(`settle.patience must be a positive whole number; got ${plan.patience}`);\n\t}\n\tif (!(plan.minIterations >= 0)) throw new Error(`settle.minIterations must be 0 or more; got ${plan.minIterations}`);\n\treturn plan;\n}\n\n/**\n * A running settle check for a caller that steps a run itself. Feed it a\n * snapshot after each `every` iterations; it says when the root play has\n * stayed still for `patience` checks in a row.\n */\nexport interface SettleTracker {\n\t/** Record a snapshot taken after `iterations` in all; true once settled. */\n\tcheck(solution: Solution, iterations: number): boolean;\n\t/** Movement at the last check, or NaN before the second. */\n\treadonly movement: number;\n\t/** Whether the last check settled it. */\n\treadonly settled: boolean;\n}\n\n/** Start a settle check; see `SettleTracker`. */\nexport function trackSettle(options: SettleOptions = {}): SettleTracker {\n\tconst plan = settlePlan(options);\n\tlet previous: RootPlay | null = null;\n\tlet still = 0;\n\tlet movement = Number.NaN;\n\tlet settled = false;\n\treturn {\n\t\tcheck(solution, iterations) {\n\t\t\tconst play = rootPlay(solution);\n\t\t\tmovement = previous ? rootPlayMovement(previous, play) : Number.NaN;\n\t\t\tprevious = play;\n\t\t\t// A check before `minIterations` does not count toward patience.\n\t\t\tstill = iterations >= plan.minIterations && movement <= plan.tolerance ? still + 1 : 0;\n\t\t\tsettled = still >= plan.patience;\n\t\t\treturn settled;\n\t\t},\n\t\tget movement() {\n\t\t\treturn movement;\n\t\t},\n\t\tget settled() {\n\t\t\treturn settled;\n\t\t},\n\t};\n}\n","/**\n * History merging: turn and river storage shared between betting histories\n * (issue #49). An imperfect-recall abstraction of the betting history.\n *\n * Purpose: decide which decision nodes share one block of storage.\n *\n * Every flop line gets its own copy of the turn and river below it, but a\n * round's subtree depends only on where the round starts: the pot and stacks.\n * Lines that reach the same start — check, bet 33%, call against bet 33%,\n * call — have identical subtrees. Aliasing their nodes' storage lets every\n * history keep its own walk (its own reach, its own values) while regrets and\n * strategy sums accumulate in one place.\n *\n * A round root is the first decision of a later round, the child of a chance\n * node. Only the last round's roots share. Roots with identical subtrees form\n * a group; within a group every root is walked in step with the first one and\n * each node is aliased to its counterpart.\n */\n\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { NodeKind } from './tree.ts';\n\nexport interface HistoryShareOptions {\n\t/** Nodes marked 1 never share: a marked round root keeps its own subtree. */\n\treadonly keep?: Uint8Array;\n}\n\nexport interface HistoryShare {\n\t/** Each node's storage owner: itself, or the node it shares with. */\n\treadonly alias: Int32Array;\n\t/** Round roots per round, and how many groups the shared round formed. */\n\treadonly roots: Int32Array;\n\treadonly groups: Int32Array;\n}\n\n/** Intern strings as small integers. */\nfunction interner(): (key: string) => number {\n\tconst ids = new Map<string, number>();\n\treturn (key) => {\n\t\tlet id = ids.get(key);\n\t\tif (id === undefined) ids.set(key, (id = ids.size));\n\t\treturn id;\n\t};\n}\n\n/**\n * Subtree signatures: equal exactly when two subtrees are identical, amounts\n * included, so nothing below the nodes changes the game.\n */\nfunction signatures(tree: Tree): Int32Array {\n\tconst exact = new Int32Array(tree.nodeCount);\n\tconst exactId = interner();\n\t// Children always come after their parent, so a reverse sweep sees them first.\n\tfor (let node = tree.nodeCount - 1; node >= 0; node--) {\n\t\tlet e = `${tree.kind[node]},${tree.player[node]},${tree.round[node]},${tree.pot[node]},${tree.payoff[node]}`;\n\t\tconst first = tree.firstEdge[node];\n\t\tfor (let i = 0; i < tree.numEdges[node]; i++) {\n\t\t\tconst edge = first + i;\n\t\t\te += `|${tree.edgeAction[edge]}:${tree.edgeTarget[edge]}:${exact[tree.edgeChild[edge]]}`;\n\t\t}\n\t\texact[node] = exactId(e);\n\t}\n\treturn exact;\n}\n\n/** Decide which nodes share storage. */\nexport function aliasHistories(tree: Tree, runouts: Runouts, options: HistoryShareOptions = {}): HistoryShare {\n\tconst exact = signatures(tree);\n\tconst alias = new Int32Array(tree.nodeCount);\n\tfor (let node = 0; node < tree.nodeCount; node++) alias[node] = node;\n\n\t// Round roots, by round. Children come after parents, so these are in tree order.\n\tconst rootsByRound: number[][] = Array.from({ length: runouts.rounds }, () => []);\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (tree.kind[node] !== NodeKind.Chance) continue;\n\t\tconst child = tree.edgeChild[tree.firstEdge[node]];\n\t\tif (tree.kind[child] === NodeKind.Decision) rootsByRound[tree.round[child]].push(child);\n\t}\n\n\tconst walk = (rep: number, member: number): void => {\n\t\talias[member] = rep;\n\t\tconst a = tree.firstEdge[rep];\n\t\tconst b = tree.firstEdge[member];\n\t\tfor (let i = 0; i < tree.numEdges[rep]; i++) walk(tree.edgeChild[a + i], tree.edgeChild[b + i]);\n\t};\n\n\tconst roots = new Int32Array(runouts.rounds);\n\tconst groups = new Int32Array(runouts.rounds);\n\tconst last = runouts.rounds - 1;\n\tif (last >= 1) {\n\t\tconst reps = new Map<number, number>();\n\t\tfor (const root of rootsByRound[last]) {\n\t\t\tif (options.keep?.[root]) continue;\n\t\t\tconst rep = reps.get(exact[root]);\n\t\t\tif (rep === undefined) reps.set(exact[root], root);\n\t\t\telse walk(rep, root);\n\t\t}\n\t\tgroups[last] = reps.size;\n\t}\n\tfor (let round = 1; round < runouts.rounds; round++) roots[round] = rootsByRound[round].length;\n\n\treturn { alias, roots, groups };\n}\n","/**\n * The betting tree from a spot's settings (issue #115).\n *\n * Purpose: one place that turns `SpotConfig`'s betting into the tree\n * builder's settings, for `defineSpot` and for the presets, which compare the\n * caller's tree with their own to report the sizes they cut.\n */\n\nimport { parseCards } from './cards.ts';\nimport type { SpotConfig } from './index.ts';\nimport type { BetSize, PerPlayer, Tree } from './tree.ts';\nimport { buildTree, isPerPlayer } from './tree.ts';\n\n/** Sub-chip resolution, so pot-fraction sizing is exact: units per chip unless `SpotConfig.chipScale` says otherwise. */\nexport const DEFAULT_CHIP_SCALE = 100;\n\n/** `config.betSizes` as one row per round for each player, checked against the board's rounds. */\nexport function betRows(config: SpotConfig, rounds: number): PerPlayer<readonly (readonly BetSize[])[]> {\n\tconst rowsFor = (sizes: readonly (readonly BetSize[])[], who: string): readonly (readonly BetSize[])[] => {\n\t\tconst expanded = sizes.length === 1 ? Array.from({ length: rounds }, () => sizes[0]) : sizes;\n\t\tif (expanded.length !== rounds) {\n\t\t\tthrow new Error(\n\t\t\t\t`${who}betSizes has ${sizes.length} rows but this board has ${rounds} ` +\n\t\t\t\t\t'betting rounds; give one row per round, or a single row for all of them',\n\t\t\t);\n\t\t}\n\t\treturn expanded;\n\t};\n\treturn isPerPlayer(config.betSizes)\n\t\t? { oop: rowsFor(config.betSizes.oop, 'oop '), ip: rowsFor(config.betSizes.ip, 'ip ') }\n\t\t: rowsFor(config.betSizes, '');\n}\n\n/** The tree builder's settings for `config`, sizes given as `betRows` gives them. */\nexport function treeConfig(config: SpotConfig, rows: PerPlayer<readonly (readonly BetSize[])[]>): Parameters<typeof buildTree>[0] {\n\tconst chipScale = config.chipScale ?? DEFAULT_CHIP_SCALE;\n\treturn {\n\t\tpotUnits: Math.round(config.pot * chipScale),\n\t\tstackUnits: Math.round(config.stack * chipScale),\n\t\tbetSizes: rows,\n\t\traiseSizes: config.raiseSizes,\n\t\tmaxRaises: config.maxRaises ?? 1,\n\t\tallowAllIn: config.allowAllIn ?? false,\n\t\tallInThreshold: config.allInThreshold,\n\t\tnoDonk: config.noDonk,\n\t\tmergeSizes: config.mergeSizes,\n\t\tremoveActions: config.removeActions,\n\t\tthinSizes: config.thinSizes,\n\t\tchipScale,\n\t\tminRaiseUnits: chipScale,\n\t};\n}\n\n/**\n * The betting tree `defineSpot(config)` would build, alone: no ranges,\n * runouts or storage, so it is cheap for any tree, and `maxBytes` is not\n * checked.\n */\nexport function bettingTree(config: SpotConfig): Tree {\n\tconst rounds = 6 - parseCards(config.board).length;\n\tif (rounds < 1 || rounds > 3) throw new Error(`A postflop board has 3, 4 or 5 cards; got ${config.board}`);\n\treturn buildTree(treeConfig(config, betRows(config, rounds)), { rounds });\n}\n","/**\n * Nested subgame re-solving (issue #47).\n *\n * Purpose: refine one player's strategy below a node of a solved spot — a\n * blueprint whose later streets were simplified to fit — by solving that\n * subgame again with a richer tree. Opt-in: nothing else in the solver calls\n * this.\n *\n * `Solution.subgameAt` already builds the subgame; this solves it with the\n * ranges the blueprint brings to the node held fixed (unsafe re-solving), and\n * can measure what each opponent hand gets against the result next to what it\n * had against the blueprint.\n *\n * Nested: a re-solved subgame is a `Solution` like any other, so a node below\n * it can be re-solved from it in turn.\n *\n * Measured (issue #47; Ks 9s 4s, a flop blueprint with three flop sizes and\n * one turn/river size, its turns re-solved at three sizes with raises,\n * against a full-tree reference): an opponent's best response under the\n * reference's ranges gained, weighted by how often each turn is reached,\n * about 3.5–4% of the subgame's pot against plain re-solving, and more\n * against every safe gadget tried (4.2–6.2%: Burch, Johanson & Bowling's\n * re-solve gadget and Moravčík et al.'s and Brown & Sandholm's maxmargin\n * ones). Most of what is left is the refined player's own range at the node,\n * which comes from the blueprint and which no gadget changes, so the gadgets\n * were removed before 0.5.0 (issue #125). To make re-solves from a shared\n * blueprint trustworthy, keep the busiest lines unshared\n * (`ShareHistories.keepLines` with `linesWithin`).\n */\n\nimport { COMBO_CARDS, COMBOS } from './cards.ts';\nimport type { Solution, SolveOptions, SubgameBetting } from './index.ts';\nimport { createRun, defineSpot } from './index.ts';\nimport type { Context } from './cfr.ts';\nimport { makeBuffers, Mode, traverse } from './cfr.ts';\n\n/** Settings for {@link resolveSubgame}. */\nexport interface ResolveOptions {\n\t/** The player whose strategy is refined. */\n\treadonly player: 0 | 1;\n\t/** The subgame's betting; unset, the blueprint's carries over. */\n\treadonly betting?: SubgameBetting;\n\t/** Iterations to run. Default 200. */\n\treadonly iterations?: number;\n\t/**\n\t * Also report `alternative` and `entered`, at the cost of a best-response\n\t * pass over the blueprint below the node and one over the subgame.\n\t */\n\treadonly measure?: boolean;\n\t/** Solver settings for the subgame; `iterations` and warm starts are this function's. */\n\treadonly solve?: Pick<SolveOptions, 'workers' | 'precision' | 'algorithm' | 'engine' | 'simd' | 'wasmStorage'>;\n}\n\n/** A re-solved subgame. */\nexport interface ResolvedSubgame {\n\t/**\n\t * The subgame's solution. Its ranges are the ones the blueprint brings to\n\t * the node; read the refined player's strategy from it.\n\t */\n\treadonly solution: Solution;\n\treadonly player: 0 | 1;\n\t/**\n\t * Each opponent hand's best-response value at the node against the\n\t * blueprint, in chips, indexed like `COMBO_CARDS`; NaN off its range.\n\t * Null unless `measure`.\n\t */\n\treadonly alternative: Float64Array | null;\n\t/**\n\t * Each opponent hand's best-response value in the re-solved subgame\n\t * against the refined strategy, in chips; NaN off its range. Where it\n\t * exceeds `alternative` the re-solve gave that hand more than the\n\t * blueprint did. Null unless `measure`.\n\t */\n\treadonly entered: Float64Array | null;\n\treadonly iterations: number;\n}\n\n/**\n * Re-solve the subgame at a node of `blueprint` for one player.\n *\n * @param blueprint a solved spot\n * @param node a decision opening a betting round (see `Solution.subgameAt`)\n * @param board the board index at that node's round\n */\nexport function resolveSubgame(blueprint: Solution, node: number, board: number, options: ResolveOptions): ResolvedSubgame {\n\tconst { player } = options;\n\tconst opponent = (1 - player) as 0 | 1;\n\tconst iterations = options.iterations ?? 200;\n\tif (!(Number.isInteger(iterations) && iterations > 0)) {\n\t\tthrow new Error(`iterations must be a positive whole number; got ${iterations}`);\n\t}\n\tconst spot = defineSpot(blueprint.subgameAt(node, board, options.betting));\n\tconst base = spot.players[opponent].weights;\n\tconst mine = spot.players[player].weights;\n\t// Mass of the refined player's range each opponent hand does not block.\n\tconst open = options.measure === true ? openMass(mine) : null;\n\n\t// The blueprint's values below the node, worked out before the\n\t// subgame's storage and threads are taken.\n\tconst live = liveCombos(spot.players);\n\tconst blueprintValues = open ? bestResponseAt(blueprint.solver.ctx, node, board, opponent, base, mine) : null;\n\n\tconst run = createRun(spot, { ...options.solve });\n\ttry {\n\t\trun.step(iterations);\n\t\tlet alternative: Float64Array | null = null;\n\t\tlet entered: Float64Array | null = null;\n\t\tif (open && blueprintValues) {\n\t\t\tconst { ctx } = run.solver;\n\t\t\tconst deals = ctx.runoutWeight[0];\n\t\t\talternative = new Float64Array(COMBOS).fill(Number.NaN);\n\t\t\tfor (const combo of live) {\n\t\t\t\tif (base[combo] > 0 && open[combo] > 0) alternative[combo] = blueprintValues[combo] / (open[combo] * deals);\n\t\t\t}\n\t\t\t// Each opponent hand's best response to the refined strategy, by\n\t\t\t// the traversal's root hands.\n\t\t\tconst lists = ctx.active;\n\t\t\tconst slot = lists.roundBase[0] * 2 + opponent;\n\t\t\tconst from = lists.start[slot];\n\t\t\tconst response = run.solver.root(Mode.BestResponse, opponent, 0);\n\t\t\tentered = new Float64Array(COMBOS).fill(Number.NaN);\n\t\t\tfor (let i = 0; i < lists.count[slot]; i++) {\n\t\t\t\tconst combo = lists.list[from + i];\n\t\t\t\tif (!Number.isFinite(alternative[combo])) continue;\n\t\t\t\tconst chips = response[i] / (open[combo] * deals);\n\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) entered[lists.memberCombo[m]] = chips;\n\t\t\t}\n\t\t}\n\t\treturn { solution: run.snapshot(), player, alternative, entered, iterations };\n\t} finally {\n\t\trun.close();\n\t}\n}\n\n/**\n * Best-response values below `node`, as `Solver.valuesAt` gives average\n * ones. A best response is not linear in the opponent's reach, so the reach\n * must be the same for mirrored hands, as any reach a solve produces is.\n */\nexport function bestResponseAt(ctx: Context, node: number, board: number, traverser: 0 | 1, reachMe: Float64Array, reachOpp: Float64Array): Float64Array {\n\tconst lists = ctx.active;\n\tconst round = ctx.tree.round[node];\n\tconst listOf = (player: 0 | 1): [number, number] => {\n\t\tconst slot = (lists.roundBase[round] + board) * 2 + player;\n\t\treturn [lists.start[slot], lists.count[slot]];\n\t};\n\tconst gather = (source: Float64Array, player: 0 | 1): Float64Array => {\n\t\tconst [from, count] = listOf(player);\n\t\tconst into = new Float64Array(COMBOS);\n\t\tfor (let i = 0; i < count; i++) into[i] = source[lists.list[from + i]];\n\t\treturn into;\n\t};\n\tconst opponent = (1 - traverser) as 0 | 1;\n\tconst [oppFrom, oppCount] = listOf(opponent);\n\tfor (let j = 0; j < oppCount; j++) {\n\t\tconst own = reachOpp[lists.list[oppFrom + j]];\n\t\tfor (let m = lists.memberStart[oppFrom + j] + 1; m < lists.memberStart[oppFrom + j + 1]; m++) {\n\t\t\tif (reachOpp[lists.memberCombo[m]] !== own) throw new Error('Best-response values need reach that mirrored hands share');\n\t\t}\n\t}\n\t// Mirrored deals below need not see symmetric reach, so they are walked.\n\tconst expanded = ctx.expandOrbits;\n\tctx.expandOrbits = true;\n\ttry {\n\t\tconst buffers = makeBuffers(ctx.tree, ctx.layout.maxActions, ctx.simd);\n\t\tconst value = traverse(ctx, buffers, Mode.BestResponse, traverser, 0, node, board, gather(reachMe, traverser), gather(reachOpp, opponent), 0);\n\t\tconst result = new Float64Array(COMBOS);\n\t\tconst [from, count] = listOf(traverser);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) result[lists.memberCombo[m]] = value[i];\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\tctx.expandOrbits = expanded;\n\t}\n}\n\n/** Combinations either player holds. */\nfunction liveCombos(players: readonly { readonly weights: Float64Array }[]): Uint16Array {\n\tconst live: number[] = [];\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tif (players[0].weights[combo] > 0 || players[1].weights[combo] > 0) live.push(combo);\n\t}\n\treturn Uint16Array.from(live);\n}\n\n/**\n * For each combination, the mass of `range` it does not block. Summed\n * directly rather than by inclusion-exclusion over cards, so a hand with\n * nothing to face gets exactly zero, not a rounding residue that passes a\n * `> 0` check and is then divided by.\n */\nexport function openMass(range: Float64Array): Float64Array {\n\tconst held: number[] = [];\n\tfor (let h = 0; h < COMBOS; h++) if (range[h] > 0) held.push(h);\n\tconst open = new Float64Array(COMBOS);\n\tfor (let h = 0; h < COMBOS; h++) {\n\t\tconst a = COMBO_CARDS[h * 2];\n\t\tconst b = COMBO_CARDS[h * 2 + 1];\n\t\tlet mass = 0;\n\t\tfor (const other of held) {\n\t\t\tconst c = COMBO_CARDS[other * 2];\n\t\t\tconst d = COMBO_CARDS[other * 2 + 1];\n\t\t\tif (c !== a && c !== b && d !== a && d !== b) mass += range[other];\n\t\t}\n\t\topen[h] = mass;\n\t}\n\treturn open;\n}\n","/**\n * Hybrid history sharing (issue #101): share later-street storage between\n * histories except along the lines most often played.\n *\n * Purpose: a solve with `shareHistories` keeps its flop play, but the ranges\n * it brings to a turn are trained against river values that several\n * histories share, so a turn re-solved from it starts from distorted ranges.\n * `ShareHistories.keepLines` gives named lines storage of their own, and\n * `turnLineReach` ranks the flop lines by how often they are reached, and\n * `linesWithin` picks the most-reached ones a storage budget allows.\n */\n\nimport type { Precision, Solution, SpotConfig } from './index.ts';\nimport { defineSpot, storageCost } from './index.ts';\nimport { matchupMass } from './cfr.ts';\nimport { NodeKind } from './tree.ts';\n\n/** A flop line opening the turn, and its share of the root's hand pairs. */\nexport interface LineReach {\n\t/** The turn's first decision, as `Solution.path` names it, e.g. `\"check check /\"`. */\n\treadonly line: string;\n\t/** The turn's first decision node. */\n\treadonly node: number;\n\t/** Weighted hand pairs reaching the turn by this line over those at the root, 0 to 1. */\n\treadonly share: number;\n}\n\n/**\n * Every line from the spot's first round into the next, most reached first.\n * Reach comes from the average strategy, so take it from a solve that has\n * run a while; the order settles long before the strategy does.\n */\nexport function turnLineReach(solution: Solution): LineReach[] {\n\tconst { tree, players } = solution.spot;\n\tif (solution.spot.runouts.rounds < 2) return [];\n\tconst rootMass = matchupMass(players[0].weights, players[1].weights);\n\tconst lines: LineReach[] = [];\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (tree.kind[node] !== NodeKind.Chance || tree.round[node] !== 0) continue;\n\t\tconst child = tree.edgeChild[tree.firstEdge[node]];\n\t\tif (tree.kind[child] !== NodeKind.Decision) continue;\n\t\t// Only the first round's decisions lie on the path, so any board serves.\n\t\tconst share = matchupMass(solution.reachAt(child, 0, 0), solution.reachAt(child, 0, 1)) / rootMass;\n\t\tlines.push({ line: solution.path(child), node: child, share });\n\t}\n\treturn lines.sort((a, b) => b.share - a.share);\n}\n\n/**\n * The most-reached lines of `solution` (`turnLineReach`) that\n * `ShareHistories.keepLines` can keep in `options.config` with its storage\n * at `options.precision` (compact storage included) at most `maxBytes`: the\n * longest prefix of the ranking that fits, with any lines the config already\n * keeps. Throws if the spot is over budget keeping only those. Keeping a line never shrinks storage, so the\n * prefix is found by bisection.\n *\n * The spot the lines are for, `options.config`, defaults to the one\n * `solution` solved. The ranking can come from a cheaper spot with the same first\n * round: the reach of a flop line is the flop play alone, so a solve with\n * the river checked down ranks the lines much as the real one does, in a\n * fraction of its memory (see `ShareHistories.keepLines`).\n */\nexport function linesWithin(solution: Solution, maxBytes: number, options: LinesWithinOptions = {}): string[] {\n\tconst config = options.config ?? solution.spot.source;\n\tconst precision = options.precision ?? 'f32';\n\tconst asked = config.shareHistories;\n\tif (!asked) throw new Error('linesWithin picks lines to keep out of shareHistories; this spot shares nothing');\n\tconst share = asked === true ? {} : asked;\n\tconst ranked = turnLineReach(solution).map((l) => l.line);\n\tconst lines = (count: number): string[] => [...new Set([...(share.keepLines ?? []), ...ranked.slice(0, count)])];\n\tconst bytes = (count: number): number =>\n\t\tstorageCost(defineSpot({ ...config, maxBytes: Number.MAX_SAFE_INTEGER, shareHistories: { ...share, keepLines: lines(count) } }), precision);\n\tconst least = bytes(0);\n\tif (least > maxBytes) {\n\t\tthrow new Error(`linesWithin: the spot needs ${least} bytes keeping no more lines, over the budget of ${maxBytes}`);\n\t}\n\t// bytes(low) fits; find the largest count that does.\n\tlet low = 0;\n\tlet high = ranked.length;\n\twhile (low < high) {\n\t\tconst mid = Math.ceil((low + high) / 2);\n\t\tif (bytes(mid) <= maxBytes) low = mid;\n\t\telse high = mid - 1;\n\t}\n\treturn lines(low);\n}\n\n/** Settings for {@link linesWithin}. */\nexport interface LinesWithinOptions {\n\t/** The spot the lines are kept in; unset, the one the ranking solution solved. */\n\treadonly config?: SpotConfig;\n\t/** The precision the spot will be solved at, which the budget is for; default 'f32'. */\n\treadonly precision?: Precision;\n}\n","/**\n * What a preset changed (issue #115).\n *\n * Purpose: `solveLite` and `largeTree` take any caller betting and turn it\n * into a cheaper game. Nothing they do may be silent, so each hands back a\n * `PresetChanges`: the bet, raise and shove sizes its tree no longer offers,\n * found by walking the caller's betting tree beside the preset's, the rounds\n * that lost any, and every other setting it set or dropped, each with a\n * sentence a page can show as it is.\n */\n\nimport { bettingTree } from './betting.ts';\nimport { parseCards } from './cards.ts';\nimport type { SamplingOptions } from './cfr.ts';\nimport type { SpotConfig } from './index.ts';\nimport { ActionKind, NodeKind } from './tree.ts';\nimport type { Tree } from './tree.ts';\n\n/** A betting round by name. */\nexport type Street = 'flop' | 'turn' | 'river';\n\n/** Sizes one player's decisions of one kind lost on one round. */\nexport interface SizesCut {\n\treadonly street: Street;\n\treadonly player: 'oop' | 'ip';\n\t/** 'bet' opens the round's betting; 'raise' answers a bet. */\n\treadonly facing: 'bet' | 'raise';\n\t/**\n\t * The sizes cut, ascending: each a fraction of the pot after a call, to\n\t * two places, as `betSizes` and `raiseSizes` give them, or 'allin'.\n\t * Where the caller's sizes resolve to different chips at different pots,\n\t * one caller size can show as neighbouring fractions.\n\t */\n\treadonly sizes: readonly (number | 'allin')[];\n\t/** The caller's decisions of this kind that lost at least one size. */\n\treadonly decisions: number;\n\t/**\n\t * The caller's decisions of this kind, offering any size, that the\n\t * preset's tree still reaches: those below a cut action are gone with\n\t * it and counted in neither number.\n\t */\n\treadonly of: number;\n}\n\n/** A setting a preset set, changed or dropped. */\nexport interface SettingChange {\n\t/** The setting's name: a `SpotConfig` field, or a `SolveOptions` one (`approximations.chanceSampling`, `precision`, ...). */\n\treadonly setting: string;\n\t/** The caller's value; undefined where it was unset. */\n\treadonly from: unknown;\n\t/** The preset's value; undefined where it dropped it. */\n\treadonly to: unknown;\n}\n\n/** Everything a preset changed against the caller's spot. */\nexport interface PresetChanges {\n\t/** Sizes the preset's tree no longer offers, by street, player and kind. */\n\treadonly sizesCut: readonly SizesCut[];\n\t/** Streets whose betting lost any size: the rounds simplified. */\n\treadonly roundsSimplified: readonly Street[];\n\t/** Every other setting set, changed or dropped, the approximations included. */\n\treadonly settings: readonly SettingChange[];\n\t/** One sentence per change, sizes first, in plain words. */\n\treadonly notes: readonly string[];\n}\n\n/**\n * Every bet, raise and shove the caller's tree offers and `preset`'s does\n * not. The trees are walked side by side, an action matched by its kind and\n * the chips it puts in; below a cut action nothing more is counted, and a\n * line `preset` adds (one the caller cut with `removeActions` below a deal,\n * say) is not walked.\n */\nexport function sizesCut(caller: SpotConfig, preset: SpotConfig): SizesCut[] {\n\tconst from = bettingTree(caller);\n\tconst to = bettingTree(preset);\n\tconst rounds = 6 - parseCards(caller.board).length;\n\tconst streets: readonly Street[] = (['flop', 'turn', 'river'] as const).slice(3 - rounds);\n\tconst groups = new Map<string, { cut: Map<string, number | 'allin'>; decisions: number; of: number }>();\n\n\tconst walk = (a: number, b: number, invested: readonly [number, number]): void => {\n\t\tconst kind = from.kind[a];\n\t\tif (kind === NodeKind.Chance) {\n\t\t\t// One edge each: the deal.\n\t\t\twalk(from.edgeChild[from.firstEdge[a]], to.edgeChild[to.firstEdge[b]], invested);\n\t\t\treturn;\n\t\t}\n\t\tif (kind !== NodeKind.Decision) return;\n\t\tconst me = from.player[a];\n\t\tconst owed = Math.max(0, invested[1 - me] - invested[me]);\n\t\tconst facing = owed > 0 ? 'raise' : 'bet';\n\t\tconst key = `${from.round[a]} ${me} ${facing}`;\n\t\tconst group = groups.get(key) ?? { cut: new Map(), decisions: 0, of: 0 };\n\t\tgroups.set(key, group);\n\t\tconst theirs = edgesOf(to, b);\n\t\tlet sized = false;\n\t\tlet lost = false;\n\t\tfor (let e = from.firstEdge[a]; e < from.firstEdge[a] + from.numEdges[a]; e++) {\n\t\t\tconst action = from.edgeAction[e];\n\t\t\tconst target = from.edgeTarget[e];\n\t\t\tconst aggressive = action === ActionKind.Bet || action === ActionKind.Raise || action === ActionKind.AllIn;\n\t\t\tif (aggressive) sized = true;\n\t\t\tconst match = theirs.get(`${action} ${target}`);\n\t\t\tif (match === undefined) {\n\t\t\t\tif (!aggressive) throw new Error(`sizesCut: the preset's tree lost a fold, check or call at node ${a}`);\n\t\t\t\tlost = true;\n\t\t\t\tconst size = action === ActionKind.AllIn ? 'allin' : fraction(from, a, target, invested, me, owed);\n\t\t\t\tgroup.cut.set(String(size), size);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst next: [number, number] = [invested[0], invested[1]];\n\t\t\tnext[me] = target;\n\t\t\twalk(from.edgeChild[e], to.edgeChild[match], next);\n\t\t}\n\t\tif (sized) group.of++;\n\t\tif (lost) group.decisions++;\n\t};\n\twalk(0, 0, [0, 0]);\n\n\tconst out: SizesCut[] = [];\n\tfor (const [key, group] of groups) {\n\t\tif (group.cut.size === 0) continue;\n\t\tconst [round, player, facing] = key.split(' ');\n\t\tconst sizes = [...group.cut.values()].sort((x, y) => (x === 'allin' ? 1 : y === 'allin' ? -1 : x - y));\n\t\tout.push({\n\t\t\tstreet: streets[Number(round)],\n\t\t\tplayer: player === '0' ? 'oop' : 'ip',\n\t\t\tfacing: facing as 'bet' | 'raise',\n\t\t\tsizes,\n\t\t\tdecisions: group.decisions,\n\t\t\tof: group.of,\n\t\t});\n\t}\n\tconst order = (c: SizesCut): number =>\n\t\tstreets.indexOf(c.street) * 4 + (c.player === 'oop' ? 0 : 2) + (c.facing === 'bet' ? 0 : 1);\n\treturn out.sort((x, y) => order(x) - order(y));\n}\n\n/** A node's edges by action and target. */\nfunction edgesOf(tree: Tree, node: number): Map<string, number> {\n\tconst out = new Map<string, number>();\n\tfor (let e = tree.firstEdge[node]; e < tree.firstEdge[node] + tree.numEdges[node]; e++) {\n\t\tout.set(`${tree.edgeAction[e]} ${tree.edgeTarget[e]}`, e);\n\t}\n\treturn out;\n}\n\n/** A sized action as a fraction of the pot after a call, to two places. */\nfunction fraction(tree: Tree, node: number, target: number, invested: readonly [number, number], me: number, owed: number): number {\n\tconst potAfterCall = tree.pot[node] + owed;\n\treturn Math.round(((target - invested[me] - owed) / potAfterCall) * 100) / 100;\n}\n\n/** Assemble a report: the sizes cut, the rounds they leave simplified, the other settings, and a sentence each. */\nexport function presetChanges(caller: SpotConfig, preset: SpotConfig, settings: readonly SettingChange[], notes: readonly string[]): PresetChanges {\n\tconst cuts = sizesCut(caller, preset);\n\tconst roundsSimplified = (['flop', 'turn', 'river'] as const).filter((s) => cuts.some((c) => c.street === s));\n\tconst sizeNotes = cuts.map((c) => {\n\t\tconst sizes = c.sizes.map((s) => (s === 'allin' ? 'all-in' : String(s))).join(', ');\n\t\tconst who = c.player === 'oop' ? 'OOP' : 'IP';\n\t\tconst what = c.facing === 'bet' ? 'bet' : 'raise';\n\t\treturn `${c.street}: ${who} loses the ${what} size${c.sizes.length > 1 ? 's' : ''} ${sizes} at ${c.decisions} of the ${c.of} such decisions the preset keeps`;\n\t});\n\treturn { sizesCut: cuts, roundsSimplified, settings, notes: [...sizeNotes, ...notes] };\n}\n\n/** What a `chanceSampling` setting does, in a sentence. */\nexport function samplingNote(sampling: SamplingOptions): string {\n\tconst which = sampling.rounds ? `the deals of rounds ${sampling.rounds.join(', ')}` : \"every later round's deals\";\n\treturn sampling.every\n\t\t? `${which} walked once every ${sampling.every} iterations, in rotation`\n\t\t: `${which} sampled at p ${sampling.p ?? 0.35}`;\n}\n","/**\n * Lite mode (issue #100): one opt-in that turns the caller's betting into the\n * phone/laptop blueprint issue #85 measured, solves it until its root play\n * settles, and re-solves later streets at the caller's full betting on demand.\n *\n * Purpose: the recipe needs a dozen settings — the flop betting kept, one\n * size on the turn and river, `shareHistories`, `runoutBuckets`,\n * `chanceSampling`, a stop on the root play rather than on exploitability —\n * and callers should not have to assemble it. Nothing else in the package\n * calls this; unused, it changes nothing.\n *\n * What is measured, and what each default costs, is in `solveLite`'s notes.\n */\n\nimport { parseCards } from './cards.ts';\nimport type { SamplingOptions } from './cfr.ts';\nimport { linesWithin } from './hybrid.ts';\nimport type { ShareHistories, Solution, SolveOptions, SpotConfig, SubgameBetting } from './index.ts';\nimport { defineSpot, solve } from './index.ts';\nimport type { PresetChanges, SettingChange } from './presets.ts';\nimport { presetChanges, samplingNote } from './presets.ts';\nimport type { ResolvedSubgame, ResolveOptions } from './resolve.ts';\nimport { resolveSubgame } from './resolve.ts';\nimport type { SettleOptions } from './settle.ts';\nimport type { BetSize, PerPlayer, RaiseSizes } from './tree.ts';\nimport { mapPlayers, perRound, raisesPerRound } from './tree.ts';\n\n/** How `liteConfig` simplifies the caller's betting. */\nexport interface LiteOptions {\n\t/**\n\t * The turn and river keep one bet size: the caller's pot-fraction size\n\t * nearest this. Default 0.75.\n\t */\n\treadonly laterSize?: number;\n\t/**\n\t * Keep one raise on the turn and river, of the caller's raise size\n\t * nearest `laterSize`. Default false: a bet and no raise, as issue #85\n\t * measured. A raise nearly doubles the tree: on issue #47's rainbow\n\t * betting 707 MiB unshared became 1375 (173 shared became 261), an\n\t * iteration cost 1.74 times as much and Node peaked at 546 MiB.\n\t */\n\treadonly laterRaise?: boolean;\n\t/**\n\t * Cap the flop's aggressions, the opening bet the first. Default: the\n\t * caller's. A speed trim, off by default: see `solveLite`'s notes for\n\t * what it saved and cost.\n\t */\n\treadonly flopMaxRaises?: number;\n\t/**\n\t * Forbid donk bets on the turn and river (`SpotConfig.noDonk`). Default:\n\t * the caller's setting. A speed trim, off by default: see `solveLite`'s\n\t * notes for what it saved and cost.\n\t */\n\treadonly noDonk?: boolean;\n\t/** `SpotConfig.runoutBuckets` for the blueprint. Default 3. */\n\treadonly runoutBuckets?: number;\n\t/**\n\t * `SpotConfig.shareHistories` for the blueprint. Default true, the river.\n\t *\n\t * For better turn re-solves, keep the most-reached flop lines unshared\n\t * within a memory budget: `SolveLiteOptions.keepBudget` (issue #113),\n\t * which picks them with `linesWithin` for you. Lines given here in\n\t * `keepLines` are kept besides.\n\t */\n\treadonly shareHistories?: boolean | ShareHistories;\n}\n\n/** Settings for {@link solveLite}. */\nexport interface SolveLiteOptions\n\textends LiteOptions,\n\t\tPick<SolveOptions, 'workers' | 'precision' | 'wasmStorage' | 'algorithm' | 'onProgress' | 'targetPercent'> {\n\t/** Iteration cap. Default 2000; the solve normally settles well before. */\n\treadonly iterations?: number;\n\t/** The stop on the root play (`SolveOptions.settle`); false to run to `iterations`. Default {}, its own defaults. */\n\treadonly settle?: SettleOptions | false;\n\t/**\n\t * `Approximations.chanceSampling` for the blueprint, or false for none.\n\t * Default {}: sampled at p 0.35, on `workers` threads.\n\t */\n\treadonly sampling?: SamplingOptions | false;\n\t/**\n\t * Keep the most-reached first-round lines' later streets unshared\n\t * (`ShareHistories.keepLines`, issue #101), as many as this many bytes\n\t * of storage at `precision` (default 'f32') allow; `keepWithin` picks\n\t * them, and the blueprint with them kept is solved from cold. It is for\n\t * turn re-solves: on issue #47's flops it cut their gain by a third to a\n\t * half at the settle point, more when run longer, root play unchanged.\n\t * 150 MiB with `precision: 'i16'` and `wasmStorage` kept 3–19 lines and\n\t * peaked at 317–534 MiB in Chromium, re-solve included. Throws if the\n\t * shared blueprint alone is over the budget, or if it shares nothing.\n\t * Unset, off. Measures are in `solveLite`'s notes.\n\t */\n\treadonly keepBudget?: number;\n\t/** Iterations of the picking solve under `keepBudget`. Default 80, as issue #101 measured. */\n\treadonly pickIterations?: number;\n}\n\n/** Settings for `LiteSolution.resolve`. */\nexport interface LiteResolveOptions extends Omit<ResolveOptions, 'betting'> {\n\t/** Overrides on the caller's own betting for the subgame. */\n\treadonly betting?: SubgameBetting;\n}\n\n/** What {@link litePreset} returns: the blueprint spot and the solve's settings, and what they changed. */\nexport interface LitePreset {\n\t/** The blueprint spot (`liteConfig`'s). */\n\treadonly config: SpotConfig;\n\t/** The blueprint solve's settings: `iterations`, `settle`, sampling and the solve options given. */\n\treadonly options: SolveOptions;\n\t/** Everything the preset changed against the caller's spot. */\n\treadonly changes: PresetChanges;\n}\n\n/** What {@link solveLite} returns. */\nexport interface LiteSolution {\n\t/** The blueprint's solution. */\n\treadonly solution: Solution;\n\t/** The blueprint spot that was solved (`liteConfig`'s, with `keepBudget` its kept lines). */\n\treadonly blueprint: SpotConfig;\n\t/** The lines kept unshared (`ShareHistories.keepLines`); empty without `keepBudget` or kept lines of the caller's. */\n\treadonly kept: readonly string[];\n\t/** The caller's spot, full betting. */\n\treadonly source: SpotConfig;\n\t/**\n\t * What the blueprint changed against `source`: the sizes cut on each\n\t * street (the flop's own only with `flopMaxRaises`), the streets\n\t * simplified, and the sharing, buckets, sampling and stop rule switched\n\t * on. `resolve` puts the cut sizes back below the node it re-solves.\n\t */\n\treadonly changes: PresetChanges;\n\t/**\n\t * Re-solve the subgame at a node opening the turn or river, at the\n\t * caller's full betting for the streets from there, the caller's cuts\n\t * below the node included: `resolveSubgame` with 200 iterations\n\t * unless `options` say otherwise, with the blueprint's `workers`,\n\t * `precision` and `wasmStorage`.\n\t */\n\tresolve(node: number, board: number, options: LiteResolveOptions): ResolvedSubgame;\n}\n\n/**\n * The blueprint of `config`: its first round's betting as given, every later\n * round one bet size (the given size nearest `laterSize`) and, with\n * `laterRaise`, one raise; no shove offered after the first round; and\n * `shareHistories` and `runoutBuckets: 3`. Ranges, pot, stacks and everything\n * else carry over. Per-player betting is simplified side by side.\n *\n * Bet and raise cuts (`removeActions`) on the first round carry over, but\n * for those past `flopMaxRaises`; those below a deal are dropped, as the\n * later rounds' sizes no longer exist (`LiteSolution.resolve` puts them\n * back). The caller's own `shareHistories` stands unless `options` give one.\n */\nexport function liteConfig(config: SpotConfig, options: LiteOptions = {}): SpotConfig {\n\tconst target = options.laterSize ?? 0.75;\n\tif (!(target > 0)) throw new Error(`laterSize must be above 0; got ${target}`);\n\tconst rounds = 6 - parseCards(config.board).length;\n\tif (!(rounds >= 1 && rounds <= 3)) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);\n\tconst flopCap = options.flopMaxRaises;\n\tif (flopCap !== undefined && !(Number.isInteger(flopCap) && flopCap >= 1)) {\n\t\tthrow new Error(`flopMaxRaises must be a whole number of at least 1; got ${flopCap}`);\n\t}\n\n\tconst betSizes = mapPlayers(config.betSizes, (rows) =>\n\t\tperRound(rows, true, rounds, 'betSizes').map((row, r) => (r === 0 ? row : nearest(row, target))),\n\t);\n\t// Unset raise sizes follow the bet sizes, which are already down to one.\n\tconst raiseSizes =\n\t\tconfig.raiseSizes === undefined\n\t\t\t? undefined\n\t\t\t: mapPlayers(config.raiseSizes, (side: RaiseSizes | undefined): RaiseSizes | undefined =>\n\t\t\t\t\tside === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: raiseRows(side, rounds).map((row, r) => (r === 0 ? row : nearest(row, target))),\n\t\t\t\t);\n\tconst maxRaises = mapPlayers(config.maxRaises ?? 1, (side) =>\n\t\tperRound(side, Array.isArray(side), rounds, 'maxRaises').map((n, r) =>\n\t\t\tr === 0 ? (flopCap === undefined ? n : Math.min(n, flopCap)) : Math.min(n, options.laterRaise ? 2 : 1),\n\t\t),\n\t);\n\tconst allowAllIn = mapPlayers(config.allowAllIn ?? false, (side) =>\n\t\tperRound(side, Array.isArray(side), rounds, 'allowAllIn').map((on, r) => (r === 0 ? on : false)),\n\t);\n\t// Cuts below a deal name sizes the blueprint no longer has, and cuts past\n\t// the flop cap name raises it no longer has.\n\tconst aggressions = (line: string): number => line.split(' ').filter((w) => w === 'bet' || w === 'raise' || w === 'allin').length;\n\tconst removeActions = config.removeActions?.filter(\n\t\t(line) => !line.includes('/') && (flopCap === undefined || aggressions(line) <= flopCap),\n\t);\n\tconst buckets = options.runoutBuckets ?? 3;\n\tconst given = typeof config.runoutBuckets === 'number' ? config.runoutBuckets : config.runoutBuckets ? 1 : 0;\n\treturn {\n\t\t...config,\n\t\tbetSizes: betSizes as SpotConfig['betSizes'],\n\t\t...(raiseSizes === undefined ? {} : { raiseSizes: raiseSizes as SpotConfig['raiseSizes'] }),\n\t\tmaxRaises: maxRaises as SpotConfig['maxRaises'],\n\t\tallowAllIn: allowAllIn as SpotConfig['allowAllIn'],\n\t\t...(options.noDonk === undefined ? {} : { noDonk: options.noDonk }),\n\t\t...(removeActions === undefined ? {} : { removeActions }),\n\t\trunoutBuckets: Math.max(buckets, given),\n\t\tshareHistories: options.shareHistories ?? config.shareHistories ?? true,\n\t};\n}\n\n/** Raise sizes as one row per round. */\nfunction raiseRows(side: RaiseSizes, rounds: number): (readonly BetSize[])[] {\n\treturn raisesPerRound(side)\n\t\t? perRound<readonly BetSize[]>(side, true, rounds, 'raiseSizes')\n\t\t: Array.from({ length: rounds }, () => side as readonly BetSize[]);\n}\n\n/** The one size of `row` nearest `target` pot: the nearest pot fraction, else the first size. */\nfunction nearest(row: readonly BetSize[], target: number): BetSize[] {\n\tlet best: BetSize | undefined;\n\tlet gap = Infinity;\n\tfor (const size of row) {\n\t\tif (typeof size !== 'number') continue;\n\t\tconst g = Math.abs(Math.log(size / target));\n\t\tif (g < gap) {\n\t\t\tgap = g;\n\t\t\tbest = size;\n\t\t}\n\t}\n\tif (best === undefined && row.length > 0) best = row[0];\n\treturn best === undefined ? [] : [best];\n}\n\n/**\n * Solve `config`'s lite blueprint (`liteConfig`) until its root play settles,\n * and hand back a re-solver for later streets at the full betting.\n *\n * Defaults: `shareHistories` on the river, `runoutBuckets: 3`,\n * `chanceSampling` at p 0.35, and `settle` with its defaults (every 20\n * iterations, under 1% of the range moved, twice running).\n *\n * Measured (issue #100) on issue #47's betting (0.33 / 0.75 / 1.5 pot, a\n * 0.75 raise, all-in, three aggressions; pot 55, stack 975, the bench\n * ranges), so the blueprint plays 0.75 and no raise on the turn and river.\n * Headless Chromium, `poker-flopsolve/threads`; the clock counts solving\n * and the settle checks. Root play loss is the EV OOP's root mix and IP's\n * mix after a check lose at the unshared blueprint's per-action values\n * (solved to 0.05% of pot), % of pot, with that blueprint's own loss as the\n * floor; it measures what sharing, sampling and stopping early cost, not\n * distance to the full game. Re-solve gain is the opponent's best response\n * against a turn re-solved at the full betting (300 iterations),\n * under the unshared blueprint's ranges, % of the subgame's pot, weighted\n * over 3 lines × 3 turns by how often each is reached:\n *\n * | flop | settled | Chromium, 1 / 2 / 4 threads | peak RSS | root play loss (floor) | per-hand EV error | re-solve gain (unshared) | re-solve, 1 / 2 / 4 threads |\n * |---|---|---|---|---|---|---|---|\n * | As Kh 7d | 400 it | 103 / 59 / 35 s | 511 MiB | 0.023 / 0.014 (0.009 / 0.008) | 0.75 / 0.85 | 3.1 / 2.7 (0.67 / 0.50) | 38 / 22 / 14 s |\n * | Ts 9s 4h | 320 it | 64 / 38 / 21 s | 426 MiB | 0.118 / 0.076 (0.116 / 0.052) | 0.54 / 0.60 | 4.0 / 3.3 (0.48 / 0.55) | 42 / 23 / 13 s |\n * | Ks 9s 4s | 360 it | 31 / 19 / 12 s | 253 MiB | 0.059 / 0.037 (0.047 / 0.025) | 1.5 / 1.9 | 3.6 / 3.6 (0.44 / 0.47) | 28 / 17 / 10 s |\n *\n * Sampling runs on the threads (issue #99): the same iterations settle the\n * root on every count, within 0.002% of pot. Unsampled, the rainbow\n * blueprint took 473 ms an iteration on 4 threads in Node against 251\n * sampled on one, and settled later. Peak memory counts the page, the\n * blueprint and a re-solve; it is the most a phone must give. The rainbow root play's loss is\n * 0.014% of pot over its floor for OOP; `settle: { every: 40, tolerance:\n * 0.02, patience: 3 }` brings it to 0.009 in 120 s instead of 104 (Node).\n *\n * Against exact solves of the full game, which separate what the turn and\n * river simplification costs:\n * - issue #51's T₀ on As Kh 7d (0.33 / 0.75 / 1.5 on every street, all-in\n * raises, two aggressions, solved to 0.22% of pot): OOP's root play lost\n * 0.072% of pot at T₀'s per-action values, the simplified blueprint\n * unshared and solved to 0.04% lost 0.057; per-hand root EVs were 3.9 /\n * 2.9% of pot off, unshared 4.1 / 3.1. Simplifying is the cost; sharing,\n * sampling and the stop add 0.015. T₀ stores no strategy, so there is no\n * floor from its own play.\n * - napkinpoker's postflop-solver solves (issue #87; two flop sizes, 75% on\n * the turn and river with 3× raises and all-in, weighted BU/CO/SB ranges,\n * SRP and 3-bet pots, 0.3% of pot), 8 spots across textures, one thread in\n * Node: root play lost 0.034 / 0.135% of pot on average at the stored\n * per-action values, where the stored solve's own play lost 0.027 /\n * 0.131; settled in 38-176 s. Wide single-raised ranges took up to\n * 452 MiB of storage, near a browser's default `maxBytes` of 512: give it\n * room, or `compactStorage` with `wasmStorage` (on rainbow, 300 MiB peak\n * in Node against 411, 27% slower). `minWeight: 0.05` there cut 2-5% of\n * storage and up to 15% of the time, root play unchanged; it edits the\n * ranges, so it is the caller's to set.\n *\n * `laterRaise`'s cost is on it; the trims `flopMaxRaises` and `noDonk`, and\n * what was rejected, are in docs/APPROXIMATIONS.md.\n *\n * `keepBudget` (issue #113) recovers part of the re-solve gain above. With\n * `keepBudget: 150 * 2 ** 20, precision: 'i16', wasmStorage` (the recipe\n * issue #101 measured), the same measures, the pick included in the time:\n *\n * | flop | kept, storage | settled | Chromium, 1 / 2 / 4 threads | peak RSS, 1 / 2 / 4 | root play loss | per-hand EV error | re-solve gain |\n * |---|---|---|---|---|---|---|---|\n * | As Kh 7d | 3 lines, 150 MiB | 440 it | 123 / 61 / 35 s | 489 / 509 / 534 MiB | 0.026 / 0.011 | 0.58 / 0.70 | 2.54 / 1.72 |\n * | Ts 9s 4h | 6 lines, 141 MiB | 320 it | 69 / 37 / 22 s | 437 / 463 / 469 MiB | 0.115 / 0.063 | 0.33 / 0.27 | 1.93 / 1.28 |\n * | Ks 9s 4s | all 19, 97 MiB | 360 it | 32 / 19 / 11 s | 290 / 301 / 317 MiB | 0.056 / 0.036 | 0.82 / 1.02 | 2.61 / 1.91 |\n *\n * Root play is as without it; the re-solve gain falls by a third to a half,\n * but stays well over the unshared blueprint's 0.4–0.7. What holds the rest\n * is the stop, not the sharing: monotone keeps every line, and at 16 bits\n * or 32 alike it re-solves at 2.6 / 1.9 when its root play settles, 1.25 /\n * 0.68 unsampled (220 iterations, 37 s on 4 threads in Node), and 0.99 /\n * 0.64 run sampled to 800 iterations (20 s). At 800 iterations (`settle:\n * false, iterations: 800`) As Kh 7d re-solves at 1.33 / 1.14 in 59 s on 4\n * threads in Chromium, peaking at 533 MiB, and Ts 9s 4h at 1.10 / 0.92 in\n * 47 s (Node); plain sharing run as long gives 2.23 / 2.41 on As Kh 7d. A\n * re-solve times as without it.\n *\n * Its memory: the picking solve's WebAssembly memory is freed only once the\n * caller yields to the event loop, so it stays resident beside the\n * blueprint's. The pick samples the turn but not the checked-down river,\n * whose baselines would be most of it (182 MiB resident on As Kh 7d sampled\n * on both, 56 on the turn alone, the same lines kept on all three flops);\n * sampling both, rainbow peaked at 661 MiB on 4 threads.\n */\nexport function solveLite(config: SpotConfig, options: SolveLiteOptions = {}): LiteSolution {\n\tconst preset = litePreset(config, options);\n\tconst blueprint = preset.config;\n\tconst share = blueprint.shareHistories;\n\tconst kept = typeof share === 'object' ? [...(share.keepLines ?? [])] : [];\n\tconst solution = solve(defineSpot(blueprint), preset.options);\n\tconst subgameSolve = pick(options, ['workers', 'precision', 'wasmStorage']);\n\tconst { tree } = solution.spot;\n\tconst scale = solution.spot.chipScale;\n\treturn {\n\t\tsolution,\n\t\tblueprint,\n\t\tkept,\n\t\tsource: config,\n\t\tchanges: preset.changes,\n\t\tresolve(node, board, resolveOptions) {\n\t\t\tconst round = tree.round[node];\n\t\t\t// The caller's cuts below the node, re-rooted there as `subgameAt`\n\t\t\t// does its own: chips count from what each player has put in.\n\t\t\tconst prefix = `${solution.path(node)} `;\n\t\t\tconst invested = (tree.pot[node] - solution.spot.potUnits) / 2;\n\t\t\tconst removeActions = (config.removeActions ?? [])\n\t\t\t\t.filter((line) => line.startsWith(prefix))\n\t\t\t\t.map((line) =>\n\t\t\t\t\tline\n\t\t\t\t\t\t.slice(prefix.length)\n\t\t\t\t\t\t.split(' ')\n\t\t\t\t\t\t.map((word) => (/^-?[\\d.]+$/.test(word) ? String((Math.round(Number(word) * scale) - invested) / scale) : word))\n\t\t\t\t\t\t.join(' '),\n\t\t\t\t);\n\t\t\treturn resolveSubgame(solution, node, board, {\n\t\t\t\t...resolveOptions,\n\t\t\t\tbetting: { ...bettingFrom(config, round), removeActions, ...resolveOptions.betting },\n\t\t\t\tsolve: { ...subgameSolve, ...resolveOptions.solve },\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * What {@link solveLite} solves, without solving it: `liteConfig`'s\n * blueprint, the solve's settings (`iterations` 2000, `settle` at its\n * defaults, `chanceSampling` at p 0.35, and the solve options given), and a\n * report of everything changed against `config`. With `keepBudget` it\n * does solve: the short picking solve `keepWithin` ranks lines on, whose\n * kept lines are in the blueprint and the report. For a page that steps its\n * own run: `createRun(defineSpot(preset.config), preset.options)`, with\n * `trackSettle` for the stop, and `resolveSubgame` with `bettingFrom(config,\n * round)` for the re-solves `LiteSolution.resolve` would make.\n */\nexport function litePreset(config: SpotConfig, options: SolveLiteOptions = {}): LitePreset {\n\tconst blueprint = keepWithin(liteConfig(config, options), options);\n\tconst sampling = options.sampling === undefined ? {} : options.sampling;\n\tconst settle = options.settle === undefined ? {} : options.settle;\n\tconst solveOptions: SolveOptions = {\n\t\titerations: options.iterations ?? 2000,\n\t\t...(settle ? { settle } : {}),\n\t\t...(sampling ? { approximations: { chanceSampling: sampling } } : {}),\n\t\t...pick(options, ['workers', 'precision', 'wasmStorage', 'algorithm', 'onProgress', 'targetPercent']),\n\t};\n\n\t// Each setting compared by what it does, so equivalent spellings\n\t// (unset and false, true and a gap of 1) are no change.\n\tconst settings: SettingChange[] = [];\n\tconst notes: string[] = [];\n\tconst change = (setting: string, from: unknown, to: unknown, note: string): void => {\n\t\tsettings.push({ setting, from, to });\n\t\tnotes.push(`${setting}: ${note}`);\n\t};\n\tconst rounds = 6 - parseCards(config.board).length;\n\tconst streets = ['flop', 'turn', 'river'].slice(3 - rounds);\n\tconst donks = (value: SpotConfig['noDonk']): boolean[] => perRound(value ?? false, Array.isArray(value), rounds, 'noDonk');\n\tconst [donkFrom, donkTo] = [donks(config.noDonk), donks(blueprint.noDonk)];\n\tif (donkFrom.join() !== donkTo.join()) {\n\t\tconst on = streets.filter((_, r) => donkTo[r]);\n\t\tchange('noDonk', config.noDonk, blueprint.noDonk, on.length\n\t\t\t? `donk bets forbidden on the ${on.join(' and ')}, a speed trim that changes the game`\n\t\t\t: 'donk bets allowed on every street');\n\t}\n\tconst gap = (value: SpotConfig['runoutBuckets']): number => (value === true ? 1 : typeof value === 'number' ? value : 0);\n\tif (gap(config.runoutBuckets) !== gap(blueprint.runoutBuckets)) {\n\t\tconst to = gap(blueprint.runoutBuckets);\n\t\tchange('runoutBuckets', config.runoutBuckets, blueprint.runoutBuckets, to > 0\n\t\t\t? `gap ${to}: turn and river cards that play alike are solved once (approximate; folds nothing on ranges with no rank symmetry)`\n\t\t\t: 'off: every turn and river card solved');\n\t}\n\tconst sharing = (value: SpotConfig['shareHistories']): string => JSON.stringify(value === true ? {} : value || null);\n\tif (sharing(config.shareHistories) !== sharing(blueprint.shareHistories)) {\n\t\tconst kept = typeof blueprint.shareHistories === 'object' ? (blueprint.shareHistories.keepLines?.length ?? 0) : 0;\n\t\tchange('shareHistories', config.shareHistories, blueprint.shareHistories, blueprint.shareHistories\n\t\t\t? `lines that meet share river storage${kept ? `, but for ${kept} line${kept > 1 ? 's' : ''} kept apart` : ''} (approximate: exploitability plateaus a few % of pot from equilibrium; read the root play)`\n\t\t\t: 'off: every line stores its own river');\n\t}\n\tconst dropped = (config.removeActions?.length ?? 0) - (blueprint.removeActions?.length ?? 0);\n\tif (dropped > 0) {\n\t\tchange('removeActions', config.removeActions, blueprint.removeActions, `${dropped} line${dropped > 1 ? 's' : ''} below a deal or past the flop cap left out of the blueprint; resolve puts those below a deal back`);\n\t}\n\tif (sampling) change('approximations.chanceSampling', undefined, sampling, samplingNote(sampling));\n\tif (settle) change('settle', undefined, settle, 'stops once the root play stops moving, not at an exploitability target');\n\treturn { config: blueprint, options: solveOptions, changes: presetChanges(config, blueprint, settings, notes) };\n}\n\n/**\n * `blueprint` keeping the lines `options.keepBudget` allows, picked with\n * `linesWithin` from `options.pickIterations` of `checkedDown(blueprint)`;\n * `blueprint` itself without a budget. What `solveLite` solves; exported so\n * a caller stepping its own run can do the same. The picking solve uses\n * `options`' `workers`, `precision`, `wasmStorage`, `algorithm` and\n * `sampling`, the last on every round but the checked-down one.\n */\nexport function keepWithin(blueprint: SpotConfig, options: SolveLiteOptions = {}): SpotConfig {\n\tconst budget = options.keepBudget;\n\tif (budget === undefined) return blueprint;\n\tif (!(budget > 0)) throw new Error(`keepBudget must be a number of bytes above 0; got ${budget}`);\n\tconst its = options.pickIterations ?? 80;\n\tif (!(Number.isInteger(its) && its >= 1)) throw new Error(`pickIterations must be a whole number of at least 1; got ${its}`);\n\tconst asked = blueprint.shareHistories;\n\tif (!asked) throw new Error('keepBudget keeps lines out of shareHistories; this blueprint shares nothing');\n\tconst cheap = defineSpot(checkedDown(blueprint));\n\tconst picked = solve(cheap, {\n\t\titerations: its,\n\t\t...pickSampling(options.sampling === undefined ? {} : options.sampling, cheap.runouts.rounds),\n\t\t...pick(options, ['workers', 'precision', 'wasmStorage', 'algorithm']),\n\t});\n\tconst keepLines = linesWithin(picked, budget, { config: blueprint, precision: options.precision ?? 'f32' });\n\treturn { ...blueprint, shareHistories: { ...(asked === true ? {} : asked), keepLines } };\n}\n\n/**\n * The picking solve's sampling: the blueprint's, but not on the last round,\n * which `checkedDown` leaves without bets. Its baselines are most of a\n * sampled solve's memory (on As Kh 7d, 126 of 182 MiB), and `solveLite`\n * cannot let the picking solve's memory go before the blueprint starts, as\n * WebAssembly memory is freed only once the caller yields. Sampling the\n * turn alone ranked the same lines on all three of issue #47's flops.\n */\nfunction pickSampling(sampling: SamplingOptions | false, rounds: number): { approximations?: { chanceSampling: SamplingOptions } } {\n\tif (!sampling) return {};\n\tconst asked = sampling.rounds ?? Array.from({ length: rounds - 1 }, (_, i) => i + 1);\n\tconst kept = asked.filter((r) => r < rounds - 1);\n\treturn kept.length > 0 ? { approximations: { chanceSampling: { ...sampling, rounds: kept } } } : {};\n}\n\n/**\n * `config` with its last round checked down: no bet or all-in there, and\n * cuts naming that round's actions dropped. Its first rounds are the same\n * game tree, so how often each line reaches the next round\n * (`turnLineReach`) comes out much as the real spot's, at a fraction of its\n * storage: what `solveLite`'s `keepBudget` ranks lines on (issue #101: on\n * As Kh 7d the lite blueprint so cut stores 57 MiB, against 173, and ranked\n * the same top 3). `shareHistories.keepLines` is dropped, as it may name\n * nodes the cut removes.\n */\nexport function checkedDown(config: SpotConfig): SpotConfig {\n\tconst rounds = 6 - parseCards(config.board).length;\n\tif (!(rounds >= 1 && rounds <= 3)) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);\n\tconst last = rounds - 1;\n\tconst betSizes = mapPlayers(config.betSizes, (rows) =>\n\t\tperRound(rows, true, rounds, 'betSizes').map((row, r) => (r === last ? [] : row)),\n\t);\n\tconst allowAllIn = mapPlayers(config.allowAllIn ?? false, (side) =>\n\t\tperRound(side, Array.isArray(side), rounds, 'allowAllIn').map((on, r) => (r === last ? false : on)),\n\t);\n\t// A cut's round is the number of deals ('/') before its last action.\n\tconst removeActions = config.removeActions?.filter((line) => line.split('/').length - 1 < last);\n\tconst asked = config.shareHistories;\n\tconst shareHistories = typeof asked === 'object' ? (({ keepLines: _kept, ...rest }) => rest)(asked) : asked;\n\treturn {\n\t\t...config,\n\t\tbetSizes: betSizes as SpotConfig['betSizes'],\n\t\tallowAllIn: allowAllIn as SpotConfig['allowAllIn'],\n\t\t...(removeActions === undefined ? {} : { removeActions }),\n\t\t...(shareHistories === undefined ? {} : { shareHistories }),\n\t};\n}\n\n/** Only the listed keys of `from` that are set. */\nfunction pick<T extends object, K extends keyof T>(from: T, keys: readonly K[]): Partial<Pick<T, K>> {\n\tconst out: Partial<Pick<T, K>> = {};\n\tfor (const key of keys) if (from[key] !== undefined) out[key] = from[key];\n\treturn out;\n}\n\n/**\n * `config`'s tree-shaping betting for a subgame opening round `round`: each\n * setting given per round loses the rounds before it, as\n * `Solution.subgameAt` does with the spot's own.\n */\nexport function bettingFrom(config: SpotConfig, round: number): SubgameBetting {\n\tconst rounds = 6 - parseCards(config.board).length;\n\tconst from = <T>(value: T | readonly T[], listed: boolean, name: string): T | readonly T[] =>\n\t\tlisted ? perRound(value as readonly T[], true, rounds, name).slice(round) : value;\n\tconst each = <T>(value: PerPlayer<T> | undefined, listed: (side: T) => boolean, name: string): PerPlayer<T> | undefined =>\n\t\tvalue === undefined ? undefined : (mapPlayers(value, (side) => from(side, listed(side), name) as T) as PerPlayer<T>);\n\tconst out: Record<string, unknown> = {\n\t\tbetSizes: each(config.betSizes, () => true, 'betSizes'),\n\t\traiseSizes: each(config.raiseSizes, (side) => side !== undefined && raisesPerRound(side), 'raiseSizes'),\n\t\tmaxRaises: each(config.maxRaises ?? 1, Array.isArray, 'maxRaises'),\n\t\tallowAllIn: each(config.allowAllIn ?? false, Array.isArray, 'allowAllIn'),\n\t\tallInThreshold: each(config.allInThreshold, Array.isArray, 'allInThreshold'),\n\t\t// The blueprint may forbid donk bets where the caller did not.\n\t\tnoDonk: from(config.noDonk ?? false, Array.isArray(config.noDonk), 'noDonk'),\n\t};\n\t// `subgameAt` reads these with `in`, so an unset one stays present and\n\t// says \"none\" rather than carrying the blueprint's over.\n\treturn out as SubgameBetting;\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 type { PerPlayer } from './tree.ts';\nimport { actionLabel, buildTree, forPlayer, mapPlayers, NodeKind, raisesPerRound } from './tree.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { ResolvedBoard } from './runouts.ts';\nexport { rankSwap } 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 } from './range.ts';\nimport { buildShowdownTable } from './showdown.ts';\nimport { buildHandSpace } from './hands.ts';\nimport { createEngine } from './engine.ts';\nimport type { WasmStorage } from './engine.ts';\nimport type { WarmStartReport } from './warm.ts';\nimport { warmStart } from './warm.ts';\nimport type { SettleOptions } from './settle.ts';\nimport { settlePlan, trackSettle } from './settle.ts';\nimport { aliasHistories } from './history-merge.ts';\nimport { betRows, DEFAULT_CHIP_SCALE, treeConfig } from './betting.ts';\nimport type { Pool } from './parallel.ts';\nimport { defaultWorkerCount, planShards, startPool } from './parallel.ts';\nimport { DEFAULT_MAX_BYTES, PLATFORM, spawnEngineWorker, threadAdvice, threadLimit } from './platform/node.ts';\nimport type { CompactPlan, Context, PlayerIndex, RegretStore, RootValues, SamplingOptions, Solver, SumStore } from './cfr.ts';\nimport {\n\tbuildActiveLists,\n\tbuildLayout,\n\tbuildPlayerIndex,\n\tmakeSampling,\n\tplanSampling,\n\tsampledRounds,\n\tsamplingBytes,\n\tmakeSolver,\n\tmakeTerminalScratch,\n\tmatchupMass,\n\tMode,\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 { resolveSubgame } from './resolve.ts';\nexport { rootPlay, rootPlayMovement, rootPlayNodes, trackSettle } from './settle.ts';\nexport type { RootPlay, SettleOptions, SettleTracker } from './settle.ts';\nexport { linesWithin, turnLineReach } from './hybrid.ts';\nexport type { LineReach, LinesWithinOptions } from './hybrid.ts';\nexport type { ResolvedSubgame, ResolveOptions } from './resolve.ts';\nexport { simdAvailable } from './kernels.ts';\nexport type { BetSize } from './tree.ts';\nexport type { SamplingOptions, Solver } from './cfr.ts';\nexport type { WasmStorage } from './engine.ts';\nexport { ACTION_LABELS, ActionKind, NodeKind } from './tree.ts';\nexport type { PerPlayer, RaiseSizes } from './tree.ts';\n/** 'node' or 'browser': which build is running. */\nexport { PLATFORM } from './platform/node.ts';\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/**\n\t * Bet sizes per betting round; a single row applies to every round.\n\t *\n\t * This and every other betting setting below (`raiseSizes`, `maxRaises`,\n\t * `allowAllIn`, `allInThreshold`) can be given apart for each player as\n\t * `{ oop: …, ip: … }`, each side in the setting's usual form:\n\t * `betSizes: { oop: [[0.33]], ip: [[0.5, 1]] }`. They only shape the\n\t * tree, so a solve costs the same either way.\n\t */\n\treadonly betSizes: PerPlayer<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?: PerPlayer<RaiseSizes | undefined>;\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. Given apart, a player may bet\n\t * or raise only while the round's aggressions are under their own limit.\n\t */\n\treadonly maxRaises?: PerPlayer<number | readonly number[]>;\n\t/** Offer a shove alongside the configured sizes; once, or per round. Default false. */\n\treadonly allowAllIn?: PerPlayer<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?: PerPlayer<number | readonly number[] | undefined>;\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/**\n\t * Bets, raises and shoves to cut from the tree, with everything below\n\t * them: each the readable path of the node the action leads to, exactly as\n\t * `Solution.path` writes it — `\"check bet 18.15\"`, `\"bet 41.25 raise\n\t * 133.31\"`, `\"check check / bet 18.15\"`, chips being the actor's total\n\t * investment after the action and `/` a deal. Only the line named goes; the\n\t * same size elsewhere stays. Checks, calls and folds cannot be cut, and a\n\t * path that names no such action in the tree is refused.\n\t *\n\t * For a budgeted tree: keep three sizes where they earn their memory, one\n\t * where they do not. A tree's memory is almost all on the river, and each\n\t * flop or turn action multiplies the river subtrees below it, so cutting a\n\t * line saves what its whole subtree stores. Default none; unset, the tree\n\t * is the one the other settings build, unchanged.\n\t */\n\treadonly removeActions?: readonly string[];\n\t/**\n\t * Thin the bet sizes to a shape that keeps most of what the full ones are\n\t * worth in a fraction of the memory. Every size stays at the root, where\n\t * out of position opens the first round. Everywhere else a decision keeps\n\t * one bet, raise or shove: the one nearest three quarters of the pot, a\n\t * shove where that would be one. Opening the last round after an earlier\n\t * round saw a bet, sizes above the pot and the shove stay as well.\n\t *\n\t * The shape is what growing sizes one at a time by their value per byte\n\t * picked on As Kh 7d and Ks 9s 4s (issue #51). Measured on As Kh 7d, pot\n\t * 55, stack 975, sizes 0.33 / 0.75 / 1.5 with shove-only raises and two\n\t * aggressions: see the #51 entry in docs/APPROXIMATIONS.md for its memory and error.\n\t * It is a fixed rule, so it costs nothing to apply. A subgame from\n\t * `Solution.subgameAt` gets the full sizes back unless its betting sets\n\t * this again, and then it is thinned as a tree of its own: bets on the\n\t * streets before it do not count, so a river after a bet on the flop\n\t * keeps only the 0.75 size, where the whole tree also kept its big sizes\n\t * and shove. Default false; unset, the tree is unchanged.\n\t */\n\treadonly thinSizes?: boolean;\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\t/**\n\t * Share river storage between betting histories that reach the same pot,\n\t * a lossy approximation for fitting a spot in memory (issue #49). Off by\n\t * default.\n\t *\n\t * Every earlier line gets its own copy of the streets below it, yet with\n\t * pot-fraction sizes many lines meet: check, bet, call and bet, call\n\t * reach the same pot, and so does every raise line taken in either order.\n\t * Their subtrees are identical, so their nodes keep one set of regrets and\n\t * strategy sums. Each history is still walked with its own reach, so an\n\t * iteration costs exactly what it did; only storage shrinks. On the\n\t * three-size target spot (AsKh7d, pot 55, stack 975, sizes 33/75/150%, a\n\t * 75% raise and all-in, three aggressions) 173 river starts collapse to 23\n\t * and storage falls 5.9 times: 17.2 GiB to 2.9 at 32 bits, 8.7 to 1.5 at 16.\n\t * There, at 16 bits, a Node solve peaked at 1.6 GiB on one thread and 2.0\n\t * on four (30 s an iteration), and was 12% of pot exploitable after 150\n\t * iterations.\n\t *\n\t * What is lost is recall: a player plays one strategy for every line that\n\t * met, though the ranges each line brings differ. Each history's regret is\n\t * weighted by how often the acting hand plays into it, which cut the cost\n\t * fourfold against plain CFR's sum. Measured on AsKh7d, pot 55, stack\n\t * 975, against the exact solve, 4 threads: with sizes 33/75/150%, an\n\t * all-in raise and two aggressions, 5.8 GiB became 1.22 GiB, and after\n\t * 400 iterations the strategy was 8.0% of pot exploitable, with\n\t * per-combination root EVs 0.72% of pot off on average and 2.5% at worst\n\t * (the exact solve: 0.28%). With one 50% size, 4.0% exploitable after\n\t * 300 iterations, EVs 0.67% off on average and 6.8% at worst.\n\t * Exploitability is measured in the full game, which the strategy covers\n\t * node by node, so it is exact. Do not expect it to approach\n\t * equilibrium: expect a strategy several percent of the pot from it, in\n\t * a spot that otherwise does not fit.\n\t *\n\t * Two consequences of one block serving several histories, both part of\n\t * the approximation: within an iteration, a history visited later plays\n\t * the regrets an earlier one has already updated, so the result depends a\n\t * little on the order of the tree; and under `algorithm: 'cfr+'` each\n\t * history's update is clamped at zero on its own, rather than their sum.\n\t * A spot with it can warm-start only from a solve that shares too.\n\t *\n\t * On issue #47's blueprint (issue #85; T's flop betting, one 0.75 bet on\n\t * the turn and river with no raise, `runoutBuckets: 3`) it saves 4.1 times\n\t * on rainbow, two-tone and monotone flops alike, because the flop's sizes\n\t * and raises still meet at a few turn pots: 196 river decisions keep 44\n\t * blocks. On AsKh7d 707 MiB becomes 173 at 32 bits, so the blueprint stays\n\t * on the WebAssembly engine; in Chromium on 4 threads the tab peaked at\n\t * 327 MiB, against 860 unshared. An iteration costs what an unshared one\n\t * does (458 ms there). Exploitability stops falling near 2.7% of pot by\n\t * 160 iterations and never reaches 0.3%; the root play goes on settling.\n\t * Judged at the unshared blueprint's own per-action values (solved to\n\t * 0.045%), after 300 iterations (138 s) its root play lost 0.011% of pot\n\t * where the unshared blueprint's lost 0.008%, but at 60 s it was 0.054%:\n\t * the unshared one needs 115 s to reach 0.3% itself. Per-hand root EVs\n\t * came out 0.4–0.6% of pot from the unshared ones (2–3% at worst), and\n\t * turns re-solved from it with T's betting gave the opponent 2.2–3.0% of\n\t * their pot under the unshared ranges, against 0.5–0.7% from the unshared\n\t * blueprint. `chanceSampling` composes: on one thread 238 ms an iteration,\n\t * the root settled in 109 s, 453 MiB; on 4 threads (issue #99) 70 ms, the\n\t * root settled in 33 s at the same iteration, 452 MiB. `coarseStart` composes\n\t * but finds no coarser copy at a gap of 3. `bench/blueprint-share/` has\n\t * the scripts and figures.\n\t *\n\t * Where a shared solve stops depends on its first few iterations (issue\n\t * #105). A shared block plays one strategy for every history meeting in\n\t * it, so the game has many stable points, and which one the solve settles\n\t * on is decided early, when regret matching plays nearly pure. Any\n\t * randomness then picks another: chance sampling, 8-bit stochastic\n\t * rounding, even float rounding under CFR+. On #103's turn spot\n\t * (exploitability 5.8% of pot), sampling at p 0.9 ended at 0.3–1.6%\n\t * over six different sets of draws. On a second turn spot (0.7%) it\n\t * changed nothing. On the blueprint above, neither sampling at p 0.9\n\t * (2.9%) nor 8-bit stochastic storage (2.5%) moved the plateau beyond\n\t * that spread, against 2.6% shared alone. Do not count on noise to\n\t * lower it. Of the deterministic changes tried (other regret\n\t * weighting, discount start, uniform play mixed into the first\n\t * iterations), none was a reliable gain. `bench/share-noise/` has the\n\t * measurements.\n\t *\n\t * `true` shares the river. See `ShareHistories` for the turn and for\n\t * lossier buckets.\n\t */\n\treadonly shareHistories?: boolean | ShareHistories;\n\t/**\n\t * Store regrets and strategy sums at 8 bits — an approximation, off by\n\t * default. See `CompactStorage`. Set here rather than on the solve because it\n\t * decides how much memory the spot needs, which `maxBytes` is checked\n\t * against when the spot is defined.\n\t */\n\treadonly compactStorage?: CompactStorage;\n}\n\n/**\n * Compact storage (issue #50): accumulators as 8-bit integers, each hand on\n * each board scaled by its own power of two, instead of 32- or 16-bit\n * values. Regret matching and the average strategy both divide a hand's\n * values by their own total, so a per-hand scale cancels wherever a strategy\n * is read and costs only a byte per hand. Rounding is at random, with odds\n * set by the remainder, so every stored value is right on average; the\n * randomness is a hash of the slot and iteration, so a solve is deterministic\n * at any thread count.\n *\n * Two modes:\n *\n * - With strategy sums (the default): regrets and sums at 8 bits, about 2.75\n * bytes a slot against 16-bit storage's 4 and 32-bit's 8. Measured, it\n * converges like the full solve: on the bench flop (AsKh7d, one size) 0.18%\n * of pot at 80 iterations against 0.18%, 0.058% at 160 against 0.052%; on\n * the monotone flop with three sizes (Ks9s4s, issue #20's T₀) 1.87% at 160\n * against 1.85%. Rounding the sums leaves a floor, near 0.03% of pot on the\n * bench flop and 0.1% on a small, narrow-range spot. On issue #20's T₀\n * (AsKh7d, three sizes, all-in raise, SPR 18), at 320 iterations it was\n * 0.81% of pot exploitable where 32-bit storage was 0.69%, per-hand root\n * EVs 0.23% of pot off a 0.17% reference, every hand's preferred bet size\n * kept, in 1.75 GiB where 32-bit storage took 5.1 and 16-bit 2.6. T itself\n * takes 5.9 GiB, 16-bit storage 8.7.\n * - `sums: false`: no strategy sums, so each node's strategy, wherever one is\n * read (`strategyAt`, `reachAt`, EVs, exploitability), is the current\n * profile, the regret-matched strategy the next iteration plays. About 1.4\n * bytes a slot, 1.03 with `blockScale`: T in 2.2 GiB. Per-hand root EVs stay as close as\n * the average's, as `currentProfileEv` found, but the strategy is far more\n * exploitable: 2 times at equal iterations on the bench flop, 5 to 8 times\n * on deeper or narrower spots (T₀ monotone: 4.0% of pot at 320 iterations\n * against 0.71%), and the bet size each hand prefers at the root agreed with\n * the reference for 62-82% of the hands where it was clear, against all of\n * them for the average. `algorithm: 'cfr+'`, whose current profile swings\n * less, is the better rule for the strategy; DCFR's current profile gives\n * the closer EVs (on T₀ monotone 0.55% of pot against the average's 1.19%,\n * but 4.9% exploitable).\n *\n * Rounding regrets to 8 bits costs training almost nothing: with 32-bit\n * regrets and no sums (`float`) the same runs were no better.\n *\n * Training is otherwise the exact solve's; exploitability is measured\n * exactly, in the full tree. Storage is split in chunks under `chunkBytes`,\n * because browsers refuse a buffer of 2 GiB. Runs on the JavaScript engine\n * and its Node worker threads, where an iteration costs about 1.5 times a\n * 32-bit one, or on the WebAssembly engine, threads included, with\n * `SolveOptions.wasmStorage` (issue #84). Not with `analysisOnly`, which\n * loads float32 sums. `precision` sets the rounds before `from`; a warm\n * start, a coarse start or `runoutBuckets`' measure of the real game reads\n * and writes compact storage, rounded to nearest; `chanceSampling` applies\n * its DCFR catch-up to compact nodes too.\n *\n * With `shareHistories`, a node sharing another's storage shares its compact\n * storage too; together they fit issue #20's target T in 0.99 GiB (0.37\n * without sums). Measured on T₀ at 160 iterations, compact storage did not\n * add to sharing's own loss: 9.0% of pot exploitable against 9.5%, root EVs\n * 0.63% of pot off against 0.66%, and all clear bet-size choices kept\n * against 97%, in a third of the memory.\n *\n * What was measured and left out is with the other approximations, in the\n * comment inside `Approximations`.\n */\nexport interface CompactStorage {\n\t/**\n\t * Keep 8-bit strategy sums, and with them the average strategy. Default\n\t * true; false stores only regrets and plays the current profile.\n\t */\n\treadonly sums?: boolean;\n\t/**\n\t * With `sums: false`, one scale per node and board instead of one per\n\t * hand: about 1.03 bytes a slot instead of 1.4. Under CFR+ it measured\n\t * nearly as accurate (0.077% of pot against 0.064% on the bench flop at\n\t * 320 iterations); under DCFR, whose large negative regrets then crowd\n\t * the scale, clearly less (0.16% against 0.08%).\n\t */\n\treadonly blockScale?: boolean;\n\t/**\n\t * First round stored compactly, from the spot's first (0); earlier rounds\n\t * keep 32-bit regrets and sums. Default 0. With `sums: false`, an earlier\n\t * round's average above the current profile measured worse than the\n\t * current profile throughout (0.053% of pot against 0.035% on the bench\n\t * flop): the two come from different iterations.\n\t */\n\treadonly from?: number;\n\t/**\n\t * Largest single buffer to allocate, in bytes; storage is split in chunks\n\t * no bigger, a node never split. Default 1 GiB: Chromium refuses an\n\t * ArrayBuffer of 2 GiB, but gives several smaller ones.\n\t */\n\treadonly chunkBytes?: number;\n\t/** For measurement: the largest regret magnitude stored, at most 127. */\n\treadonly steps?: number;\n\t/** For measurement: round regrets to nearest instead of at random. */\n\treadonly nearest?: boolean;\n\t/** For measurement, with `sums: false`: keep 32-bit regrets, dropping only the sums. */\n\treadonly float?: boolean;\n}\n\n/** See `SpotConfig.shareHistories`. */\nexport interface ShareHistories {\n\t/**\n\t * Lines whose later streets keep storage of their own, each named as\n\t * `Solution.path` names a node (a flop line opening the turn reads like\n\t * `\"check check /\"`). Every node at or below a listed one is left out of\n\t * sharing, and so is any round root above one. The rest share as\n\t * before. Unset or empty, nothing is kept. A warm start into a spot that\n\t * differs only here, keeping at least the lines its source keeps,\n\t * carries the average strategy too, as for the same spot.\n\t *\n\t * What it is for (issue #101): a turn re-solved from a shared blueprint\n\t * (`resolveSubgame`) inherits only the ranges the blueprint brings to\n\t * it, and sharing distorts those. Its flop play is stored unshared, but\n\t * it learns from river values that several histories share. Keeping the\n\t * few most-reached flop lines unshared gives the flop exact values\n\t * where most of the play is, and that straightens the ranges on the\n\t * lines left shared too. Pick them with `linesWithin` (the most-reached\n\t * lines, `turnLineReach`, that a storage budget allows) from a short\n\t * solve, 80 iterations, of a cheap copy of the spot (below); close that\n\t * and solve the hybrid spot from cold. Continuing from the picking solve\n\t * instead is worse: its average lingers.\n\t *\n\t * Measured on issue #47's blueprint (`1size-b3`), 400 iterations, against\n\t * the unshared blueprint solved to 0.045% of pot. \"Re-solve gain\" is the\n\t * opponent's best response to an unsafe turn re-solve at the full\n\t * three-size betting, under the unshared blueprint's ranges, in % of the\n\t * subgame pot, weighted by line reach, refining OOP / IP; the unshared\n\t * blueprint's own re-solves give 0.67 / 0.50. On AsKh7d:\n\t *\n\t * | kept | storage, f32 | re-solve gain | root EV error, mean |\n\t * |---|---|---|---|\n\t * | none (plain sharing) | 173 MiB | 3.05 / 2.15 | 0.57 / 0.46 |\n\t * | top 1 | 201 MiB | 2.48 / 1.58 | 0.46 / 0.53 |\n\t * | top 3 | 285 MiB | 1.10 / 0.83 | 0.24 / 0.21 |\n\t * | top 6 | 383 MiB | 1.16 / 0.65 | 0.23 / 0.27 |\n\t * | all (unshared) | 707 MiB | 0.67 / 0.50 | 0 |\n\t *\n\t * On Ts9s4h and Ks9s4s plain sharing gives 4.10 / 3.69 and 4.23 /\n\t * 2.72 against 0.48 / 0.55 and 0.44 / 0.47 unshared. Kept by a 300 MiB\n\t * budget (`linesWithin`), two-tone keeps 6 lines in 282 MiB for 0.61 /\n\t * 0.72, and monotone all 19 in 187 MiB. The top 3 alone are not enough\n\t * on two-tone (1.82 / 1.96), so budget the storage, not the count.\n\t *\n\t * In Chromium the picking solve's WebAssembly memory stays resident\n\t * until it is collected, so it adds to the peak. Rank on a cheap copy\n\t * instead: the blueprint with its river checked down (57 MiB on AsKh7d)\n\t * ranked the same top 3 there. Within 512 MiB on AsKh7d, store the\n\t * hybrid at 16 bits (`precision: 'i16'` with `wasmStorage`) with a 150\n\t * MiB budget at that precision. It keeps the same 3 lines, re-solves at\n\t * 1.47 / 0.92, and peaked at 392 MiB on 4 threads, 592 ms an iteration\n\t * against 495 shared, its root play settled in 127 s. Two-tone the same\n\t * way: 0.88 / 0.85. `bench/blueprint-share/` has the scripts and figures.\n\t */\n\treadonly keepLines?: readonly string[];\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\t/** Storage with `compactStorage`, which `maxBytes` is then checked against; else null. */\n\treadonly compactBytes: number | null;\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(estimate.compactBytes !== null\n\t\t\t\t? `This spot needs ~${formatBytes(estimate.compactBytes)} even with compact storage, `\n\t\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/** Each node's storage owner under `shareHistories`; unset without it. */\n\treadonly historyAlias?: Int32Array;\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 = betRows(config, rounds);\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 merge =\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\tconst runouts = enumerateRunouts(board, symmetries, merge);\n\tconst tree = buildTree(treeConfig(config, rows), runouts);\n\n\tconst historyAlias = config.shareHistories ? shareHistories(tree, runouts, config, chipScale) : undefined;\n\tconst layout = buildLayout(tree, runouts, players, 4, historyAlias);\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, historyAlias).bytes + showdownBytes;\n\t// Shared storage is walked once per history all the same.\n\tconst walkedSlots = layout.walkedSlots;\n\tconst compact = config.compactStorage ? compactPlan(config.compactStorage, runouts.rounds) : null;\n\tconst compactBytes = compact\n\t\t? buildLayout(tree, runouts, players, 4, historyAlias, compact).bytes + showdownBytes\n\t\t: null;\n\tconst needed = compactBytes ?? compressedBytes;\n\n\tconst suggestions: string[] = [];\n\tif (needed > maxBytes) {\n\t\tconst widest = Math.max(...[0, 1].flatMap((p) => forPlayer(rows, p).map((r) => r.length)));\n\t\tif (widest > 1) suggestions.push(`use fewer bet sizes (currently up to ${widest} per round)`);\n\t\tconst raises = [0, 1].flatMap((p) => [forPlayer(config.maxRaises ?? 1, p)].flat());\n\t\tif (Math.max(...raises) > 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\tcompactBytes,\n\t\tsecondsPerThousandIterations: (walkedSlots * 4 * 1000) / OPS_PER_SECOND,\n\t\tfits: needed <= 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\t...(historyAlias ? { historyAlias } : {}),\n\t\tresolveBoard(cards) {\n\t\t\treturn resolveBoard(runouts, typeof cards === 'string' ? parseCards(cards) : cards);\n\t\t},\n\t};\n}\n\n/** `SpotConfig.shareHistories` resolved into each node's storage owner. */\nfunction shareHistories(tree: Tree, runouts: Runouts, config: SpotConfig, chipScale: number): Int32Array {\n\tconst asked: ShareHistories = config.shareHistories === true ? {} : config.shareHistories || {};\n\tconst keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : undefined;\n\treturn aliasHistories(tree, runouts, { keep }).alias;\n}\n\n/**\n * `ShareHistories.keepLines` as node marks: each listed node, everything\n * below it, and everything above it, so that no round root containing it\n * is shared either.\n */\nfunction keptNodes(tree: Tree, chipScale: number, lines: readonly string[]): Uint8Array {\n\tconst parent = new Int32Array(tree.nodeCount).fill(-1);\n\tconst paths: string[] = new Array(tree.nodeCount);\n\tpaths[0] = '(root)';\n\t// Children come after their parents, so a parent's path is always ready.\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\tconst child = tree.edgeChild[edge];\n\t\t\tparent[child] = node;\n\t\t\tconst step = tree.kind[node] === NodeKind.Decision ? actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], chipScale) : '/';\n\t\t\tpaths[child] = node === 0 ? step : `${paths[node]} ${step}`;\n\t\t}\n\t}\n\tconst listed = new Set(lines);\n\tconst missing = new Set(lines);\n\tconst marks = new Uint8Array(tree.nodeCount);\n\t// At or below a listed node: parents come first, so one sweep does.\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (listed.has(paths[node])) {\n\t\t\tmissing.delete(paths[node]);\n\t\t\tmarks[node] = 1;\n\t\t} else if (parent[node] >= 0 && marks[parent[node]]) {\n\t\t\tmarks[node] = 1;\n\t\t}\n\t}\n\tif (missing.size > 0) {\n\t\tthrow new Error(`shareHistories.keepLines: no node of this tree has the path ${[...missing].map((l) => `\"${l}\"`).join(', ')}`);\n\t}\n\t// Above one: every ancestor of a marked node.\n\tfor (let node = tree.nodeCount - 1; node > 0; node--) if (marks[node]) marks[parent[node]] = 1;\n\treturn marks;\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\t/**\n\t * Stop once the root play stops moving (issue #100): every `every`\n\t * iterations (default 20) read the average strategy at the root and at in\n\t * position's decision after a check, and stop once it has moved less than\n\t * `tolerance` (default 0.01: 1% of the range's mass, total variation\n\t * weighted by range) at `patience` checks in a row (default 2).\n\t * `stoppedAt` is then 'settled'. `rootPlayMovement` defines the measure.\n\t *\n\t * For solves that never reach an exploitability target, such as a\n\t * blueprint with `shareHistories`, which plateaus several percent of the\n\t * pot out while its first decisions go on settling (issue #85). A check\n\t * reads two nodes' strategies and no best-response pass, so it costs\n\t * almost nothing; with it, `Progress.exploitability` is NaN unless\n\t * `targetPercent` is set too, which then measures at every check and\n\t * stops on whichever comes first. `exploitEvery` is ignored. Measured\n\t * costs are in `solveLite`'s notes. Unset, off.\n\t */\n\treadonly settle?: SettleOptions;\n\treadonly onProgress?: (info: Progress) => void;\n\t/**\n\t * Accumulator storage. Unset, 'f32' — what the WebAssembly engine runs —\n\t * or 'i16' for a spot too big for it under `maxBytes`. 'f64' is there on\n\t * request and runs the JavaScript engine; measured, it buys no accuracy\n\t * an exploitability target can see.\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 unless `enableThreads` from\n\t * `poker-flopsolve/threads` has started its workers; any count above what\n\t * is available resolves to what is, with one warning.\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 * For a `warmStart` from a solve of a different board: each card of this\n\t * spot's deck to the card of the old spot's it plays as, a permutation of\n\t * the 52 cards taking this board onto the old one. A rank swap (`6` and\n\t * `7` in every suit, say) carries a solve of AsKh6d onto AsKh7d with every\n\t * hand keeping its role: 66 there is 77 here (`rankSwap` builds that map).\n\t * Hands and runouts relabel through it; whatever the old ranges lacked\n\t * starts cold. Unset, a warm start must come from the same board. The\n\t * average strategy never carries over through it, even for a relabelling\n\t * that leaves the game unchanged: only regrets do.\n\t *\n\t * Measured on the bench flop (AsKh7d, single-threaded, to 0.5% of pot):\n\t * 52 iterations cold, 8 warm from a 0.1% solve of AsKh6d, 20 from AsQh7d.\n\t * It pays only when the whole old solve is at hand: seeding the flop's\n\t * decisions alone, as a downloadable library could, saved at most 15%\n\t * (see `Approximations`).\n\t */\n\treadonly warmCards?: Uint8Array;\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\t/**\n\t * Which traversal runs. Unset, the WebAssembly engine wherever it applies\n\t * — 32-bit storage (or 16-bit and compact with `wasmStorage`), WebAssembly\n\t * SIMD available — and the JavaScript one otherwise. 'js' forces\n\t * JavaScript, to compare the two.\n\t */\n\treadonly engine?: 'js';\n\t/**\n\t * 16-bit and compact storage on the WebAssembly engine (issue #84): pass\n\t * `wasmStorage` from `poker-flopsolve/wasm-storage`. With it, a solve at\n\t * `precision: 'i16'` or of a `compactStorage` spot runs on the engine,\n\t * threads included, rather than on JavaScript. Its updates are the\n\t * JavaScript ones, step for step, worked in 32-bit floats rather than\n\t * 64-bit ones, so a stored value differs only where it lies within float32\n\t * precision of a rounding boundary; the random rounding hashes the same\n\t * slot and iteration, read to 24 bits rather than 32. Compact scales\n\t * below 2^-126 (regrets under 10^-35) are taken as 0. Unset, those solves run on\n\t * JavaScript as before; 32-bit solves run on the default engine either\n\t * way, and `precision: 'f64'` on JavaScript.\n\t */\n\treadonly wasmStorage?: WasmStorage;\n}\n\n/** See `SolveOptions.approximations`. */\nexport interface Approximations {\n\t/**\n\t * Solve a coarser copy of the spot first and start the real one from its\n\t * regrets — coarse to fine, as multigrid methods do. The copy buckets\n\t * turn and river cards like `runoutBuckets`, so each of its iterations\n\t * is cheaper (a flop stores ~40% fewer runouts at a gap of 3), and its\n\t * equilibrium is close enough to the real one's that the real solve picks\n\t * up roughly where it left off. The answer is still the real spot's: the\n\t * coarse game only chooses where it starts, and exploitability and\n\t * `targetPercent` measure the real game. Unset, off.\n\t *\n\t * Measured on three flop spots in Chromium, one thread, stopped at 15 s,\n\t * with 40 coarse iterations (issue #24): root-EV error per combination\n\t * against a 0.1%-of-pot reference fell from 1.51% to 0.19% of pot on\n\t * AsKh7d (exploitability 0.94% to 0.40%), and 0.26% to 0.06% on the\n\t * wider bench flop. A monotone flop, which a cold solve already settles\n\t * within 15 s, reached 0.5% error in half the time but ended a little\n\t * looser, 0.11% against 0.04%. To an exploitability target in Node it\n\t * was faster on all three: 0.1% on the monotone flop in 14.5 s instead of\n\t * 15.3, 0.2% on the wide one in 15.5 instead of 19.3, 0.3% on AsKh7d in\n\t * 23.8 instead of 31.5. Around 40 iterations suits a flop; far fewer\n\t * leave the coarse solve too rough to help, far more spend the time\n\t * where the real solve would have spent it better.\n\t *\n\t * Carrying the coarse average strategy, restarting DCFR's count (a\n\t * `warmIteration` of 0 or 10), a bucket gap of 1, or forbidding donk bets\n\t * in the coarse spot were measured too, and were all worse.\n\t *\n\t * The coarse iterations count toward `totalIterations`, not `completed`\n\t * or `Solution.iterations`; DCFR carries on counting from them unless\n\t * `warmIteration` says otherwise. Both solves are in memory at the\n\t * switch, the coarse one about 60% the size of the real one on a flop.\n\t * Where bucketing folds no runouts together — a river spot, ranges with no rank symmetry — it does\n\t * nothing. Not with `warmStart`, which it already is. The coarse solve\n\t * runs inside `createRun`, all at once and without progress reports, so\n\t * a caller stepping a run to stay responsive should keep it short; it\n\t * must fit in what `maxBytes` leaves beside the real spot, at 16 bits if\n\t * not 32, or `createRun` refuses.\n\t */\n\treadonly coarseStart?: CoarseStart;\n\t/**\n\t * Report `Solution.ev` and `Solution.handEvs` under the current profile —\n\t * the regret-matched strategy the next iteration would play — instead of\n\t * the average strategy. Default off. Measured under DCFR, the default\n\t * update rule; it applies to CFR+ alike.\n\t *\n\t * Measured against a solve to 0.045% of pot, after a 15 s single-threaded\n\t * browser budget, the current profile's per-hand root EVs had a mean error\n\t * of 1.23% of pot where the average's had 2.18% (flop As Kh 7d), 0.11%\n\t * against 0.37% (monotone Ks 9s 4s) and 1.40% against 2.02% (wide Qs Jh\n\t * 2c). Across those three spots it was the closer one at 62 of 65\n\t * checkpoints from 15 s down to 0.1% exploitability, often by 2–4 times.\n\t * It costs the same one pass per player as reading the average's EVs.\n\t *\n\t * Those EVs then belong to a different profile from the strategy\n\t * `strategyAt` and `reachAt` show, which stays the average: the average is\n\t * what converges to equilibrium and what exploitability measures, while\n\t * the current profile's values happen to settle sooner. Read them as the\n\t * better estimate of the equilibrium's EVs, not as the EVs of the strategy\n\t * on screen. A run with `analysisOnly` has no regrets and cannot use this.\n\t */\n\treadonly currentProfileEv?: boolean;\n\t/*\n\t * Every other approximation measured and left out, or measured as a\n\t * combination and offered only as a preset, is recorded with its numbers\n\t * and issue in docs/APPROXIMATIONS.md.\n\t */\n\t/**\n\t * Chance sampling with baselines (VR-MCCFR; Schmid et al., 2019). Each\n\t * training iteration walks each turn and river deal with probability `p`\n\t * (default 0.35, both rounds). A deal left out adds the per-hand values it\n\t * returned when last walked, its baseline; a walked deal adds\n\t * `b + (v - b) / p` and its values become the new baseline. DCFR discounts\n\t * a skipped subtree missed are applied when it is next walked. This is\n\t * what made sampling pay where the plain 1/p weighting (docs/APPROXIMATIONS.md) did not:\n\t * the correction only carries how much a deal's values moved since its\n\t * last walk, which is small.\n\t *\n\t * Iterations get several times cheaper and take 2–5 times as many to a\n\t * target, so the net is about 1.2–1.5 times faster to 0.3% of pot, and\n\t * per-hand root EVs come out closer to the true ones at the same\n\t * exploitability. Measured single-threaded in Node against the exact\n\t * solve, time to 0.3% of pot (to 1%): AsKh7d 23.7 s → 15.9 s (13.3 → 9.0),\n\t * Ks9s4s 6.0 → 4.3 (3.4 → 2.3), the README's wide flop 13.4 → 9.3\n\t * (7.5 → 5.3), and pairs-and-broadway ranges on AsKh7d 16.7 → 12.9 and on\n\t * Ks9s4s 5.5 → 4.5. Exploitability is measured exactly, in the full game.\n\t *\n\t * Costs: one float per hand per stored deal per chance node, 6–31 MB on\n\t * those flops (about 12–20% beside their storage), counted against\n\t * `maxBytes`. Any storage: 32-, 64- or 16-bit, or `compactStorage`\n\t * over 32 or 16 bits (16-bit since issue #102, with the same DCFR\n\t * catch-up, in both engines).\n\t *\n\t * Threads (issue #99): it runs on `workers` threads, in the JavaScript\n\t * pool and on the WebAssembly engine's threads alike. Threads split the\n\t * runouts as for an exact solve, and the state sampling keeps (baselines,\n\t * when each deal was last walked, when each block was last updated for\n\t * the catch-up) lives in shared memory, each thread's runouts' entries\n\t * its own. There is no per-thread random stream: whether a deal is walked\n\t * on an iteration is a hash of its chance node, the deal and the\n\t * iteration, in both engines, so every thread count walks the same deals\n\t * on the same iterations. A fixed count is then bitwise repeatable, and\n\t * different counts differ only as unsampled ones do (see `workers`). A\n\t * spot sampling a round above the threads' split, which no flop or turn\n\t * spot has, runs on one thread. Measured in Chromium on issue #47's\n\t * blueprint, 4 threads ran 3.1–3.2 times faster than 1 on three flops,\n\t * and the shared AsKh7d blueprint's root play settled in 33 s against\n\t * 105 s (`bench/blueprint-share/README.md`). With `targetPercent`, a sampled solve runs more\n\t * iterations, so it makes a few more exploitability checks.\n\t * Off, nothing changes; at `p: 1` it is the exact solve, bit for bit.\n\t */\n\treadonly chanceSampling?: SamplingOptions;\n}\n\n/** See `Approximations.coarseStart`. */\nexport interface CoarseStart {\n\t/** Iterations of the coarse spot to run before the real one. */\n\treadonly iterations: number;\n\t/**\n\t * The coarse spot's `runoutBuckets`, at least the spot's own. Default 3;\n\t * a wider gap folds more runouts only where the ranges allow it.\n\t */\n\treadonly runoutBuckets?: number;\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\t/** In chips; NaN at a `settle` check made without `targetPercent`. */\n\treadonly exploitability: number;\n\treadonly elapsedMs: number;\n\t/** With `settle`: how far the root play moved since the last check (`rootPlayMovement`), NaN at the first. */\n\treadonly movement?: number;\n}\n\n/** Which stopping rule ended a solve: see `Solution.stoppedAt`. */\nexport type StopReason = 'target' | 'iterations' | 'settled';\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. 'settled' is\n\t * `SolveOptions.settle`'s: the root play stopped moving.\n\t */\n\treadonly stoppedAt: StopReason;\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/**\n\t * Chips per hand for a player, under the average strategy — or under the\n\t * current profile with `approximations.currentProfileEv`.\n\t */\n\tev(player: 0 | 1): number;\n\t/**\n\t * Root EV in chips for each combination a player can hold, indexed like\n\t * `COMBO_CARDS` (as `reachAt` is): what that hand wins on average, over\n\t * the opponent hands it can be dealt against. Zero for combinations outside\n\t * the range or blocked by the board, and for a hand no opponent hand can be\n\t * dealt against, which has no EV to give. Weighted by range weight times\n\t * compatible opponent mass, the mean is `ev(player)`, and the same pass\n\t * serves both. Under the average strategy, or the current profile with\n\t * `approximations.currentProfileEv`. Returns a fresh copy.\n\t */\n\thandEvs(player: 0 | 1): Float64Array;\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'\n\t\t| 'raiseSizes'\n\t\t| 'maxRaises'\n\t\t| 'allowAllIn'\n\t\t| 'allInThreshold'\n\t\t| 'noDonk'\n\t\t| 'mergeSizes'\n\t\t| 'removeActions'\n\t\t| 'thinSizes'\n\t\t| 'maxCombos'\n\t\t| 'maxBytes'\n\t>\n>;\n\n/** Subgame settings that shape the tree, which a carried-over cut would not fit. */\nconst TREE_SETTINGS = [\n\t'betSizes', 'raiseSizes', 'maxRaises', 'allowAllIn', 'allInThreshold', 'noDonk', 'mergeSizes', 'thinSizes',\n] as const satisfies readonly (keyof SubgameBetting)[];\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/** Which traversal runs: the WebAssembly engine or the JavaScript one. */\n\treadonly engine: 'wasm' | 'js';\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?: StopReason): 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\tif (options.analysisOnly && options.approximations?.currentProfileEv) {\n\t\tthrow new Error('approximations.currentProfileEv needs regrets, and an analysisOnly run has none');\n\t}\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 { bytes } = spot.estimate;\n\tconst compact = spot.source.compactStorage ? compactPlan(spot.source.compactStorage, spot.runouts.rounds) : null;\n\tif (compact) {\n\t\tconst clashes: [unknown, string][] = [\n\t\t\t// An analysis-only run loads float32 sums, which compact nodes do not have.\n\t\t\t[options.analysisOnly, 'analysisOnly'],\n\t\t];\n\t\tconst clash = clashes.find(([set]) => set)?.[1];\n\t\tif (clash) throw new Error(`compactStorage does not combine with ${clash}`);\n\t}\n\t// With compact storage, `precision` is that of the rounds before `compactStorage.from`.\n\tconst precision: Precision = compact\n\t\t? options.precision ?? 'f32'\n\t\t: options.analysisOnly\n\t\t? 'f32'\n\t\t: options.precision ??\n\t\t\t(bytes <= maxBytes ? 'f32' : 'i16');\n\n\t// Planned before anything is allocated, so a bad option or a coarse spot\n\t// that does not fit fails here; solved only once the real run exists.\n\tconst coarsePlan = planCoarseStart(spot, options, precision, maxBytes);\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(\n\t\tspot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision], spot.historyAlias, compact ?? undefined,\n\t);\n\tconst weights = runoutWeights(spot.runouts);\n\n\t// The WebAssembly engine, where it applies: 32-bit storage, or 16-bit and\n\t// compact storage with `wasmStorage`, and a platform with WebAssembly\n\t// SIMD. Decided before the thread count, because the browser build can\n\t// only thread the engine.\n\tconst storageEngine = options.wasmStorage !== undefined && precision !== 'f64' && (precision === 'i16' || compact !== null);\n\tconst wantsEngine =\n\t\toptions.engine !== 'js' && !options.analysisOnly && options.simd !== false &&\n\t\t((precision === 'f32' && !compact) || storageEngine);\n\tconst samplingOptions = options.approximations?.chanceSampling;\n\tconst requested = resolveWorkers(options, wantsEngine);\n\tconst shards = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;\n\t// Threads sample the deals of their own runouts, below the split. A\n\t// sampled round above it would be sampled by the main thread after the\n\t// threads had walked it, so such a spot stays on one thread; the split\n\t// sits at the first round with more than one board, so no flop or turn\n\t// spot has one: this is a guard, not a case a real spot reaches.\n\tconst plan = shards && samplingOptions && sampledRounds(samplingOptions, spot.runouts.rounds).some((r) => r < shards.round)\n\t\t? null\n\t\t: shards;\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 active = buildActiveLists(spot.runouts, spot.players, showdown);\n\tconst hands = buildHandSpace(spot.runouts, spot.players, active);\n\tconst samplingPlan = samplingOptions ? planSampling(spot.tree, spot.runouts, active, layout, samplingOptions) : undefined;\n\t// Measured as the precision choice above measures storage: by the estimate\n\t// at the precision chosen (16-bit storage by its own); with compact\n\t// storage, which that estimate does not know, by the layout.\n\tconst storageBytes = compact\n\t\t? layout.bytes\n\t\t: Math.max(quantised ? spot.estimate.compressedBytes : bytes, layout.bytes);\n\tif (samplingPlan && storageBytes + samplingBytes(samplingPlan) > maxBytes) {\n\t\tthrow new Error(\n\t\t\t`chanceSampling needs ${Math.ceil(samplingBytes(samplingPlan) / 2 ** 20)} MiB of baselines beside ` +\n\t\t\t\t`${Math.ceil(storageBytes / 2 ** 20)} MiB of storage, over maxBytes; sample fewer rounds or raise maxBytes`,\n\t\t);\n\t}\n\t// The engine owns the storage; the context sees it through views.\n\tconst engine = wantsEngine\n\t\t? createEngine(\n\t\t\t\t{\n\t\t\t\t\ttree: spot.tree, runouts: spot.runouts, players: spot.players, layout, active, hands,\n\t\t\t\t\trunoutWeight: weights, chipScale: spot.chipScale, sampling: samplingPlan,\n\t\t\t\t\t...(storageEngine ? { storage: { source: options.wasmStorage!, quantised, compact } } : {}),\n\t\t\t\t},\n\t\t\t\tplan ? { plan, threads: requested, spawn: spawnEngineWorker } : undefined,\n\t\t\t)\n\t\t: null;\n\tconst engineCompact = engine?.compact ?? null;\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: engine\n\t\t\t? engine.regret\n\t\t\t: options.analysisOnly\n\t\t\t\t? new Float32Array(0)\n\t\t\t\t: makeRegretStore(precision, allocate(layout.totalSlots * width)),\n\t\tstrategySum: engine ? engine.strategySum : makeSumStore(precision, allocate(layout.totalSlots * width)),\n\t\tregretScale: !quantised ? null : engine ? engine.regretScale : new Float64Array(allocate(layout.blocks * 8)),\n\t\tsumScale: !quantised ? null : engine ? engine.sumScale : new Float64Array(allocate(layout.blocks * 8)),\n\t\tcompact,\n\t\tcompactRegret: !compact\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.regret\n\t\t\t\t: layout.chunkSlots.map((slots) =>\n\t\t\t\t\t\tcompact.float ? new Float32Array(allocate(slots * 4)) : new Int8Array(allocate(slots)),\n\t\t\t\t\t),\n\t\thandShift: !compact?.perHand\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.handShift\n\t\t\t\t: layout.chunkHands.map((hands) => new Uint8Array(allocate(hands))),\n\t\tcompactSum: !compact?.sums\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.sum\n\t\t\t\t: layout.chunkSlots.map((slots) => new Uint8Array(allocate(slots))),\n\t\tsumShift: !compact?.sums\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.sumShift\n\t\t\t\t: layout.chunkHands.map((hands) => new Uint8Array(allocate(hands))),\n\t\tcompactScale:\n\t\t\t!compact || compact.perHand || compact.float\n\t\t\t\t? null\n\t\t\t\t: engineCompact\n\t\t\t\t\t? engineCompact.scale\n\t\t\t\t\t: new Float64Array(allocate(layout.blocks * 8)),\n\t\tscratch: makeTerminalScratch(),\n\t\tchipScale: spot.chipScale,\n\t\tactive,\n\t\thands,\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\tif (samplingPlan) ctx.sampling = makeSampling(samplingPlan, engine?.sampling ?? undefined, allocate);\n\tif (layout.shared) ctx.discounted = engine?.discounted ?? new Int32Array(layout.blocks);\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\tlet solver: Solver;\n\tlet pool: Pool | null;\n\ttry {\n\t\tif (options.warmCards && !options.warmStart) {\n\t\t\tthrow new Error('`warmCards` relabels a warm start, so it needs `warmStart` too');\n\t\t}\n\t\tif (options.warmStart) {\n\t\t\tconst source = options.warmStart;\n\t\t\twarm = options.warmCards\n\t\t\t\t? warmStart(ctx, source.solver.ctx, false, options.warmCards)\n\t\t\t\t: warmStart(ctx, source.solver.ctx, sameSpot(spot.source, source.spot.source));\n\t\t\toffset = options.warmIteration ?? source.totalIterations;\n\t\t} else if (coarsePlan && coarsePlan.iterations > 0) {\n\t\t\t// Regrets only: the bucketed game's average would have to be outweighed.\n\t\t\tconst coarse = solveCoarse(coarsePlan, options);\n\t\t\ttry {\n\t\t\t\twarm = warmStart(ctx, coarse.solver.ctx, false);\n\t\t\t} finally {\n\t\t\t\tcoarse.close();\n\t\t\t}\n\t\t\toffset = options.warmIteration ?? coarse.totalIterations;\n\t\t}\n\t\t// Inherited accumulators are discounted up to where the count resumes.\n\t\tif (warm) ctx.sampling?.lastUpdate.fill(offset);\n\n\t\tsolver = makeSolver(ctx);\n\t\tif (warm && coarsePlan) coarseMs.set(solver, coarsePlan.elapsed);\n\t\t// The engine runs its own threads; the JavaScript pool is for the rest.\n\t\tpool = plan && !engine\n\t\t\t? startPool(ctx, solver, plan, { config: spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd, compact }, requested)\n\t\t\t: null;\n\t} catch (error) {\n\t\t// The engine's threads would otherwise stay parked on this run for good.\n\t\tengine?.close();\n\t\tthrow error;\n\t}\n\tif (pool) solver.useRoot(pool.traverse);\n\tif (engine) solver.useRoot(engine.root(ctx.dcfr));\n\tconst threadCount = pool ? pool.workers : engine ? engine.threads : 1;\n\tlet completed = 0;\n\n\treturn {\n\t\tspot,\n\t\tsolver,\n\t\tworkers: threadCount,\n\t\tget completed() {\n\t\t\treturn completed;\n\t\t},\n\t\twarmStart: warm,\n\t\tengine: engine ? 'wasm' : 'js',\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\tengine?.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: threadCount,\n\t\t\t\tprecision,\n\t\t\t\twasmStorage: options.wasmStorage,\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(\n\t\t\t\tspot, solver, completed, offset + completed, [...history], stoppedAt, threadCount,\n\t\t\t\toptions.approximations?.currentProfileEv === true,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/** Validate `SpotConfig.compactStorage` into the solver's plan. */\nfunction compactPlan(settings: CompactStorage, rounds: number): CompactPlan {\n\tconst from = settings.from ?? 0;\n\tif (!Number.isInteger(from) || from < 0 || from >= rounds) {\n\t\tthrow new Error(`compactStorage.from must be a round of this spot, 0 to ${rounds - 1}; got ${from}`);\n\t}\n\tconst chunkBytes = settings.chunkBytes ?? 2 ** 30;\n\tif (!Number.isInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new Error(`compactStorage.chunkBytes must be a positive whole number of bytes; got ${chunkBytes}`);\n\t}\n\tconst steps = settings.steps ?? 127;\n\tif (!Number.isInteger(steps) || steps < 1 || steps > 127) {\n\t\tthrow new Error(`compactStorage.steps must be an integer from 1 to 127; got ${steps}`);\n\t}\n\tif (settings.sums !== false && (settings.blockScale || settings.float)) {\n\t\tthrow new Error('compactStorage.sums keeps a scale per hand, so blockScale and float need sums: false');\n\t}\n\treturn {\n\t\tfrom, steps, perHand: !settings.blockScale && !settings.float, stochastic: !settings.nearest,\n\t\tfloat: settings.float === true, chunkBytes, sums: settings.sums ?? true,\n\t};\n}\n\n/** Bucket gap of the coarse spot when `CoarseStart.runoutBuckets` is unset. */\nconst DEFAULT_COARSE_GAP = 3;\n\n/** A coarse start to run: its spot and settings, and once solved, how long it took. */\ninterface CoarsePlan {\n\treadonly spot: Spot;\n\treadonly iterations: number;\n\treadonly precision: Precision;\n\telapsed: number;\n}\n\n/** Milliseconds a run's coarse start took, by the real run's solver, for `solve()`'s clock. */\nconst coarseMs = new WeakMap<Solver, number>();\n\n/**\n * Validate `approximations.coarseStart` and define its spot, or null when\n * there is nothing to solve: the option unset, no iterations, or bucketing\n * folds no more runouts than the spot itself does.\n *\n * The coarse spot must fit in what `maxBytes` leaves beside the real one,\n * since both are in memory at the switch; at 32 bits if it can, else 16.\n */\nfunction planCoarseStart(spot: Spot, options: SolveOptions, precision: Precision, maxBytes: number): CoarsePlan | null {\n\tconst settings = options.approximations?.coarseStart;\n\tif (!settings) return null;\n\tconst { iterations, runoutBuckets = DEFAULT_COARSE_GAP } = settings;\n\tif (!(Number.isInteger(iterations) && iterations >= 0)) {\n\t\tthrow new Error(`coarseStart.iterations must be a whole number of iterations; got ${iterations}`);\n\t}\n\tif (!(Number.isInteger(runoutBuckets) && runoutBuckets >= 1)) {\n\t\tthrow new Error(`coarseStart.runoutBuckets must be a rank gap of 1 or more; got ${runoutBuckets}`);\n\t}\n\tif (options.warmStart) throw new Error('coarseStart is a warm start of its own; give one or the other, not both');\n\tif (options.analysisOnly) throw new Error('coarseStart solves; an analysis-only run must never be stepped');\n\n\t// Never a narrower gap than the spot already uses, and only a wider one helps.\n\tconst own = spot.source.runoutBuckets;\n\tconst ownGap = own === true ? DEFAULT_BUCKET_GAP : own || 0;\n\tif (iterations === 0 || spot.board.length === 5 || runoutBuckets <= ownGap) return null;\n\tconst coarseSpot = defineSpot({ ...spot.source, runoutBuckets });\n\tif (coarseSpot.runouts.counts.at(-1)! >= spot.runouts.counts.at(-1)!) return null;\n\n\t// A compact spot's coarse spot is compact too: its storage is its layout at\n\t// that precision, beside the rest `estimate.compactBytes` counts at 32 bits.\n\tconst used = storageCost(spot, precision);\n\tconst left = maxBytes - used;\n\tconst coarsePrecision: Precision = options.precision ?? (storageCost(coarseSpot, 'f32') <= left ? 'f32' : 'i16');\n\tconst needs = storageCost(coarseSpot, coarsePrecision);\n\tif (needs > left) {\n\t\tthrow new Error(\n\t\t\t`coarseStart needs ~${formatBytes(needs)} beside this spot's ~${formatBytes(used)}, ` +\n\t\t\t\t`over the ${formatBytes(maxBytes)} limit; raise maxBytes or leave coarseStart off`,\n\t\t);\n\t}\n\treturn { spot: coarseSpot, iterations, precision: coarsePrecision, elapsed: 0 };\n}\n\n/** Solve a planned coarse start, returning the run to warm-start from. */\nfunction solveCoarse(plan: CoarsePlan, options: SolveOptions): SolveRun {\n\tconst started = Date.now();\n\tconst { coarseStart: _, ...rest } = options.approximations!;\n\tconst run = createRun(plan.spot, {\n\t\tworkers: options.workers,\n\t\tprecision: plan.precision,\n\t\talgorithm: options.algorithm,\n\t\tsimd: options.simd,\n\t\tengine: options.engine,\n\t\twasmStorage: options.wasmStorage,\n\t\tapproximations: rest,\n\t});\n\ttry {\n\t\trun.step(plan.iterations);\n\t} catch (error) {\n\t\trun.close();\n\t\tthrow error;\n\t}\n\tplan.elapsed = Date.now() - started;\n\treturn run;\n}\n\n/** Bytes `of` takes stored at `at`, compact storage included. */\nexport function storageCost(of: Spot, at: Precision): number {\n\tif (of.estimate.compactBytes === null) {\n\t\treturn at === 'i16' ? of.estimate.compressedBytes : of.estimate.bytes * (at === 'f64' ? 2 : 1);\n\t}\n\tconst plan = compactPlan(of.source.compactStorage!, of.runouts.rounds);\n\tconst bytesAt = (width: number): number =>\n\t\tbuildLayout(of.tree, of.runouts, of.players, width, of.historyAlias, plan).bytes;\n\treturn of.estimate.compactBytes + bytesAt(PRECISION_BYTES[at]) - bytesAt(4);\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\tconst kept = (config: SpotConfig): readonly string[] | undefined =>\n\t\ttypeof config.shareHistories === 'object' ? config.shareHistories.keepLines : undefined;\n\tif (kept(a) === undefined && kept(b) === undefined) return plain(a) === plain(b);\n\t// `keepLines` only gives nodes their shared block's own copy, so a warm\n\t// start into a spot keeping every line its source keeps copies each node\n\t// exactly, average included; into one keeping fewer, several histories\n\t// would write one block.\n\tconst mine = new Set(kept(a) ?? []);\n\tif (!(kept(b) ?? []).every((line) => mine.has(line))) return false;\n\treturn plain(withoutKeptLines(a)) === plain(withoutKeptLines(b));\n}\n\n/** `config` with `keepLines` dropped and its sharing in one form: `true` and `{}` alike, unset keys gone. */\nfunction withoutKeptLines(config: SpotConfig): SpotConfig {\n\tconst asked = config.shareHistories;\n\tif (!asked) return config;\n\tconst { keepLines: _kept, ...rest } = asked === true ? {} : asked;\n\tconst set = Object.entries(rest).filter(([, value]) => value !== undefined);\n\treturn { ...config, shareHistories: set.length > 0 ? Object.fromEntries(set) : true };\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\nconst threadWarnings = new Set<string>();\n\n/**\n * Threads a run will use. Anything above what the platform can run now falls\n * back to what it can, with one warning per reason: the browser build threads\n * only the WebAssembly engine, and only after `enableThreads` from\n * `poker-flopsolve/threads` has started its workers.\n * @param options solver tuning\n * @param engine whether the WebAssembly engine is to run\n */\nfunction resolveWorkers(options: SolveOptions, engine: boolean): number {\n\tif (options.analysisOnly) return 1;\n\tconst asked = options.workers === 'auto' ? defaultWorkerCount() : (options.workers ?? 1);\n\tconst limit = threadLimit(engine);\n\tif (asked > limit) {\n\t\tconst advice = threadAdvice(engine);\n\t\tif (!threadWarnings.has(advice)) {\n\t\t\tthreadWarnings.add(advice);\n\t\t\tconsole.warn(`poker-flopsolve: ${asked} threads asked for, solving on ${limit} (${PLATFORM} build): ${advice}`);\n\t\t}\n\t\treturn limit;\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\t// Validated before any storage is taken.\n\tconst settle = options.settle ? settlePlan(options.settle) : null;\n\tconst run = createRun(spot, options);\n\tconst history: Progress[] = [];\n\t// A coarse start solves inside createRun, and that is solving time too.\n\tconst started = Date.now() - (coarseMs.get(run.solver) ?? 0);\n\t// Where DCFR's count stands before this run's first iteration, for\n\t// predicting the target; only a coarse start shifts it, as a warm start's\n\t// checks were always scheduled from zero.\n\tconst before = coarseMs.has(run.solver) ? run.totalIterations : 0;\n\n\ttry {\n\t\treturn runAll();\n\t} finally {\n\t\trun.close();\n\t}\n\n\tfunction runAll(): Solution {\n\t\tif (settle) return runSettled(settle);\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: StopReason = '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\tbefore + prevIteration,\n\t\t\t\t\tprevExploitability,\n\t\t\t\t\tbefore + done,\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 - before : 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\t/** `settle`'s loop: a cheap root-play check every `every` iterations. */\n\tfunction runSettled(plan: Required<SettleOptions>): Solution {\n\t\tconst tracker = trackSettle(plan);\n\t\tlet stoppedAt: StopReason = 'iterations';\n\t\tlet done = 0;\n\t\twhile (done < iterations) {\n\t\t\tconst until = Math.min(done + plan.every, iterations);\n\t\t\t// A short last step moves the play less; it is not a check.\n\t\t\tconst full = until - done === plan.every;\n\t\t\trun.step(until - done);\n\t\t\tdone = until;\n\t\t\tconst measured = run.snapshot();\n\t\t\tconst settled = full && tracker.check(measured, done);\n\t\t\tconst info: Progress = {\n\t\t\t\titeration: done,\n\t\t\t\texploitability: target > 0 ? measured.exploitability() : Number.NaN,\n\t\t\t\telapsedMs: Date.now() - started,\n\t\t\t\tmovement: full ? tracker.movement : Number.NaN,\n\t\t\t};\n\t\t\thistory.push(info);\n\t\t\toptions.onProgress?.(info);\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\t\t\tif (settled) {\n\t\t\t\tstoppedAt = 'settled';\n\t\t\t\tbreak;\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\tsolver: Solver,\n\titerations: number,\n\ttotalIterations: number,\n\thistory: Progress[],\n\tstoppedAt: StopReason,\n\tworkers: number,\n\tcurrentProfileEv: boolean,\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 => actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], spot.chipScale);\n\n\tconst path = (node: number): string => {\n\t\tconst steps: string[] = [];\n\t\tlet current = node;\n\t\twhile (parent[current] >= 0) {\n\t\t\tconst owner = parent[current];\n\t\t\tsteps.push(tree.kind[owner] === NodeKind.Decision ? label(viaEdge[current]) : '/');\n\t\t\tcurrent = owner;\n\t\t}\n\t\treturn steps.reverse().join(' ') || '(root)';\n\t};\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\t// One pass per player serves `ev` and `handEvs` alike.\n\tlet cachedEv: RootValues | null = null;\n\tconst rootValues = (): RootValues =>\n\t\t(cachedEv ??= solver.rootValues(currentProfileEv ? Mode.Current : Mode.Average));\n\tconst cachedHands: [Float64Array | null, Float64Array | null] = [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\treturn rootValues().totals[player];\n\t\t},\n\t\thandEvs(player) {\n\t\t\tcachedHands[player] ??= solver.handEvs(player, rootValues().values[player]);\n\t\t\treturn cachedHands[player].slice();\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,\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\t// Each player's side of a setting loses the played rounds alike.\n\t\t\tconst laterEach = <T>(value: PerPlayer<T> | undefined, listed: (side: T) => boolean): PerPlayer<T> | undefined =>\n\t\t\t\tvalue === undefined ? undefined : (mapPlayers(value, (side) => later(side, listed(side)) as T) as PerPlayer<T>);\n\t\t\tconst rows = laterEach(source.betSizes, () => true) as SpotConfig['betSizes'];\n\t\t\tconst raiseRows = laterEach(source.raiseSizes, (side) => side !== undefined && raisesPerRound(side));\n\t\t\t// Cuts below the node carry over, re-rooted at it, while the tree\n\t\t\t// keeps the old betting; new betting builds a tree they need not fit.\n\t\t\t// Settings read with `??` fall back when given as undefined, and an\n\t\t\t// unset thinSizes is the full tree the cuts were made on.\n\t\t\tconst keeps = (key: keyof SubgameBetting): boolean =>\n\t\t\t\tkey === 'thinSizes' ? !betting.thinSizes : betting[key] === undefined && ['betSizes', 'maxRaises', 'allowAllIn'].includes(key);\n\t\t\tconst reshaped = TREE_SETTINGS.some((key) => key in betting && !keeps(key));\n\t\t\tconst prefix = node === 0 ? '' : `${path(node)} `;\n\t\t\t// Chips in a path are the actor's total investment, which a subgame\n\t\t\t// counts from its own start: each amount drops by what is already in.\n\t\t\tconst rebase = (step: string): string => {\n\t\t\t\tconst [label, chips] = step.split(' ');\n\t\t\t\treturn chips === undefined ? step : `${label} ${(Math.round(Number(chips) * spot.chipScale) - invested) / spot.chipScale}`;\n\t\t\t};\n\t\t\tconst cuts = source.removeActions\n\t\t\t\t?.filter((line) => line.startsWith(prefix))\n\t\t\t\t.map((line) => line.slice(prefix.length).split(' ').reduce<string[]>((steps, word, i, words) => {\n\t\t\t\t\t// Words come as single actions (\"check\", \"/\") or a label and its chips.\n\t\t\t\t\tif (/^-?[\\d.]+$/.test(word)) steps[steps.length - 1] = rebase(`${words[i - 1]} ${word}`);\n\t\t\t\t\telse steps.push(word);\n\t\t\t\t\treturn steps;\n\t\t\t\t}, []).join(' '));\n\t\t\tconst removeActions =\n\t\t\t\t'removeActions' in betting ? betting.removeActions : reshaped || !cuts || cuts.length === 0 ? undefined : cuts;\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 ?? laterEach(source.maxRaises, Array.isArray),\n\t\t\t\tallowAllIn: betting.allowAllIn ?? laterEach(source.allowAllIn, Array.isArray),\n\t\t\t\tallInThreshold: 'allInThreshold' in betting ? betting.allInThreshold : laterEach(source.allInThreshold, Array.isArray),\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\t...(removeActions ? { removeActions } : {}),\n\t\t\t\t// The thinned shape is the whole tree's, so a subgame starts full.\n\t\t\t\t...(betting.thinSizes ? { thinSizes: true } : {}),\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\tcompactStorage: source.compactStorage,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport { formatCards, parseCards };\nexport { bettingFrom, checkedDown, keepWithin, liteConfig, litePreset, solveLite } from './lite.ts';\nexport type { LiteOptions, LitePreset, LiteResolveOptions, LiteSolution, SolveLiteOptions } from './lite.ts';\nexport type { PresetChanges, SettingChange, SizesCut, Street } from './presets.ts';\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,WAAW,EAAE;AAC1C,MAAI,QAAQ,SAAS,MAAM,EAAG,OAAM,IAAI,MAAM,IAAI,IAAI,kCAAkC;AAExF,QAAM,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,QAAQ,SAAS,OAAO,WAAW,SAAY,SAAY,MAAM,OAAO,QAAQ,MAAM,QAAQ,OAAO,MAAM,CAAC;AAAA,QAC1I,YAAY,gBAAgB,UAAU,QAAQ,aAAa,OAAO;AAAA,QAClE,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;AAAA;AAAA,QAEzC,GAAI,QAAQ,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;AAAA,QAC/C,WAAW,OAAO;AAAA,QAClB,aAAa,OAAO;AAAA,QACpB,WAAW,eAAe,UAAU,QAAQ,YAAY,OAAO;AAAA,QAC/D,UAAU,cAAc,UAAU,QAAQ,WAAW,OAAO;AAAA,QAC5D,WAAW,KAAK;AAAA,QAChB,gBAAgB,OAAO;AAAA,MACxB;AAAA,IACD;AAAA,EACD;AACD;","names":["fraction","nearest","walk","RANK_CHARS","high","span","i","childCols","regretMatch","width","p","makeBuffers","treeDepth","stochastic","high","wasm","wasm","treeDepth","bytes","plan","count","REGRET_STEPS","SUM_STEPS","walk","shifts","walk","makeBuffers","high","walk","shareHistories","bytes","hands","raiseRows","label"]}
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/hands.ts","../src/pairs.ts","../src/wasm/kernels.ts","../src/kernels.ts","../src/cfr.ts","../src/wasm/engine.ts","../src/wasm/engine-shared.ts","../src/platform/browser-threads.ts","../src/platform/browser.ts","../src/parallel.ts","../src/engine.ts","../src/warm.ts","../src/settle.ts","../src/history-merge.ts","../src/betting.ts","../src/resolve.ts","../src/hybrid.ts","../src/vendor/range-compress.js","../src/compress.ts","../src/presets.ts","../src/lite.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/**\n * A setting given once for both players, or apart: `{ oop: …, ip: … }`, each\n * side in the setting's own form.\n */\nexport type PerPlayer<T> = T | { readonly oop: T; readonly ip: T };\n\n/** Whether a setting is given apart for each player. */\nexport function isPerPlayer<T>(value: PerPlayer<T>): value is { readonly oop: T; readonly ip: T } {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value) && 'oop' in value && 'ip' in value;\n}\n\n/** One player's side of a setting: 0 out of position, 1 in position. */\nexport function forPlayer<T>(value: PerPlayer<T>, player: number): T {\n\treturn isPerPlayer(value) ? (player === 0 ? value.oop : value.ip) : value;\n}\n\n/** Apply `f` to each side of a setting, keeping its shape. */\nexport function mapPlayers<T, U>(value: PerPlayer<T>, f: (side: T) => U): PerPlayer<U> {\n\treturn isPerPlayer(value) ? { oop: f(value.oop), ip: f(value.ip) } : f(value);\n}\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; for both players, or apart. */\n\treadonly betSizes: PerPlayer<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?: PerPlayer<RaiseSizes | undefined>;\n\t/**\n\t * Maximum aggressive actions per round, the opening bet the first; once or\n\t * per round. Given apart, a player may bet or raise only while the round's\n\t * aggressions are under their own limit.\n\t */\n\treadonly maxRaises: PerPlayer<number | readonly number[]>;\n\t/** Offer a shove alongside the configured sizes; once or per round. */\n\treadonly allowAllIn: PerPlayer<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?: PerPlayer<number | readonly number[] | undefined>;\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\t/**\n\t * Bets, raises and shoves to leave out, each by the readable path of the\n\t * node it leads to — `Solution.path` — with the subtree below it. Unset,\n\t * none. See `SpotConfig.removeActions`.\n\t */\n\treadonly removeActions?: readonly string[];\n\t/**\n\t * Keep one size at most nodes: see `SpotConfig.thinSizes`. Unset or\n\t * false, every size the other settings give.\n\t */\n\treadonly thinSizes?: boolean;\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/**\n * How a path names an action: `check`, `call`, `fold`, or the kind and the\n * actor's total investment after it in chips — `bet 18.15`, `raise 60`,\n * `allin 975`. `Solution.path` joins these with spaces, and `/` for a deal.\n */\nexport function actionLabel(action: number, target: number, chipScale: number): string {\n\treturn action >= ActionKind.Bet ? `${ACTION_LABELS[action]} ${target / chipScale}` : ACTION_LABELS[action];\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 SizedAction {\n\treadonly action: number;\n\treadonly target: number;\n}\n\n/** The pot fraction `thinSizes` keeps at most decisions. */\nconst THIN_BASE = 0.75;\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\t/** Earlier rounds that saw a bet. */\n\treadonly streetsBet: 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: Pick<Runouts, 'rounds'>): 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\t// Every betting setting resolved per player, then per round.\n\tconst players = [0, 1] as const;\n\tconst maxRaises = players.map((p) => {\n\t\tconst value = forPlayer(config.maxRaises, p);\n\t\treturn perRound(value, Array.isArray(value), rounds, 'maxRaises');\n\t});\n\tconst allowAllIn = players.map((p) => {\n\t\tconst value = forPlayer(config.allowAllIn, p);\n\t\treturn perRound(value, Array.isArray(value), rounds, 'allowAllIn');\n\t});\n\tconst merge = config.mergeSizes ?? 0;\n\tconst raiseSizes = players.map((p) => {\n\t\tconst value = forPlayer(config.raiseSizes, p);\n\t\treturn value\n\t\t\t? perRound<readonly BetSize[]>(value, raisesPerRound(value), rounds, 'raiseSizes').map((row) => mergeBetSizes(row, merge))\n\t\t\t: null;\n\t});\n\tconst betSizes = players.map((p) => forPlayer(config.betSizes, p).map((row) => mergeBetSizes(row, merge)));\n\tconst threshold = players.map((p) => {\n\t\tconst value = forPlayer(config.allInThreshold, p) ?? 0;\n\t\treturn perRound(value, Array.isArray(value), rounds, 'allInThreshold');\n\t});\n\tconst noDonk = perRound(config.noDonk ?? false, Array.isArray(config.noDonk), rounds, 'noDonk');\n\tconst half = Math.round(potUnits / 2);\n\t// Lines to cut, and which of them were found. Paths are only built when\n\t// there is something to cut, so a tree without cuts is built as before.\n\tconst remove = config.removeActions && config.removeActions.length > 0 ? new Set(config.removeActions) : null;\n\tconst removed = new Set<string>();\n\tconst extend = (path: string, step: string): string => (remove ? (path ? `${path} ${step}` : step) : '');\n\n\t// The sizes `thinSizes` keeps at a decision, in the order they came.\n\tconst thin = config.thinSizes === true;\n\tconst thinned = (sized: readonly SizedAction[], state: BetState): readonly SizedAction[] => {\n\t\t// Every size where the first round opens.\n\t\tif (state.round === 0 && state.aggressions === 0 && state.acted === 0) return sized;\n\t\tconst me = state.toAct;\n\t\tconst mine = state.invested[me];\n\t\tconst owed = Math.max(0, state.invested[1 - me] - mine);\n\t\tconst potAfterCall = potUnits + state.invested[0] + state.invested[1] + owed;\n\t\tconst fraction = (target: number): number => (target - mine - owed) / potAfterCall;\n\t\t// The size nearest three quarters of the pot: a shove where that is one.\n\t\tlet nearest = -1;\n\t\tsized.forEach((entry, i) => {\n\t\t\tconst distance = Math.abs(fraction(entry.target) - THIN_BASE);\n\t\t\tif (nearest < 0 || distance < Math.abs(fraction(sized[nearest].target) - THIN_BASE)) nearest = i;\n\t\t});\n\t\t// Opening the last round after an earlier one saw a bet: the big sizes too.\n\t\tconst big = rounds > 1 && state.round === rounds - 1 && owed === 0 && state.streetsBet > 0;\n\t\treturn sized.filter(\n\t\t\t(entry, i) => i === nearest || (big && (entry.action === ActionKind.AllIn || fraction(entry.target) > 1)),\n\t\t);\n\t};\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, path: string): 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\tstreetsBet: state.streetsBet + (state.aggressions > 0 ? 1 : 0),\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, extend(path, '/')) : buildDecision(next, extend(path, '/'));\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\t// Short of a full raise: bumped up to one where the stack allows it,\n\t\t// and otherwise all-in for less. A player can always put in everything\n\t\t// they have, raise or not — dropping that shove left a short stack\n\t\t// facing a bet only call or fold.\n\t\tconst raiseSize = target - theirs;\n\t\tconst minimum = Math.max(state.lastRaise, minRaiseUnits);\n\t\tif (raiseSize < minimum) target = Math.min(theirs + minimum, cap);\n\t\treturn target;\n\t};\n\n\tconst buildDecision = (state: BetState, path: string): 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[me][state.round] && myRemaining > owed && !donk) {\n\t\t\tconst seen = new Set<number>();\n\t\t\tconst sized: { action: number; target: number }[] = [];\n\t\t\tconst myRaises = raiseSizes[me];\n\t\t\tconst sizes: BetSize[] =\n\t\t\t\towed > 0 && myRaises\n\t\t\t\t\t? [...myRaises[state.round]]\n\t\t\t\t\t: [...(betSizes[me][state.round] ?? [])].filter((size) => !(typeof size === 'object' && 'times' in size));\n\t\t\tif (allowAllIn[me][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[me][state.round] > 0 && target - mine >= threshold[me][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\tsized.push({ action: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet, target });\n\t\t\t}\n\t\t\tfor (const entry of thin ? thinned(sized, state) : sized) {\n\t\t\t\tif (remove) {\n\t\t\t\t\tconst line = extend(path, actionLabel(entry.action, entry.target, chipScale));\n\t\t\t\t\tif (remove.has(line)) {\n\t\t\t\t\t\tremoved.add(line);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tactions.push(entry);\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\t// Labels only matter to a cut, so a tree without one formats none.\n\t\t\tconst line = remove ? extend(path, actionLabel(entry.action, entry.target, chipScale)) : '';\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 }, line)\n\t\t\t\t\t: buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 }, line);\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\tstreetsBet: state.streetsBet,\n\t\t\t\t}, line);\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\tstreetsBet: 0,\n\t}, '');\n\n\tif (remove && removed.size < remove.size) {\n\t\t// A line below a cut one went with it, so the tree never reached it.\n\t\tconst under = (line: string): boolean => [...removed].some((cut) => line.startsWith(`${cut} `));\n\t\tconst missing = [...remove].filter((line) => !removed.has(line) && !under(line));\n\t\tif (missing.length > 0) throw new Error(\n\t\t\t`removeActions: no bet, raise or shove in this tree ends the line ${missing.map((m) => `\"${m}\"`).join(', ')}. ` +\n\t\t\t\t'Give each as Solution.path writes the node the action leads to, e.g. \"check bet 18.15\"; ' +\n\t\t\t\t'checks, calls and folds cannot be removed',\n\t\t);\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, which the solver\n\t * stores once per orbit.\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\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\tconst base = p * previousWidth;\n\t\t\tconst children = dealChildren(maps, previousCards, base, previousWidth, stabilisers[p], merge);\n\t\t\tfor (const child of children) if (child.merged) approximate = true;\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/** One stored child of a board, and the real deals it stands for. */\nexport interface DealtChild {\n\treadonly card: number;\n\t/** Each member deal's map onto this board, and its card; see `Runouts.orbitMap`. */\n\treadonly maps: number[];\n\treadonly cards: number[];\n\t/** The parent's symmetries that also fix this card: the child's own. */\n\treadonly fixing: number[];\n\t/** Folded into an earlier child, so not stored. */\n\tmerged: boolean;\n}\n\nconst usedScratch = new Uint8Array(DECK);\nconst seenScratch = new Uint8Array(DECK);\n\n/**\n * The children of one board: one per orbit of its symmetries, ascending by\n * card, with runout buckets folded into earlier children (`merged`).\n *\n * @param maps the relabellings in use, which merges add to\n * @param cards flat board cards, the parent at `base`, `width` of them\n * @param stabiliser the parent's symmetries, identity first\n */\nexport function dealChildren(\n\tmaps: CardMaps,\n\tcards: ArrayLike<number>,\n\tbase: number,\n\twidth: number,\n\tstabiliser: readonly number[],\n\tmerge?: RunoutMerge,\n): DealtChild[] {\n\tconst used = usedScratch;\n\tconst seen = seenScratch;\n\tused.fill(0);\n\tseen.fill(0);\n\tfor (let i = 0; i < width; i++) used[cards[base + i]] = 1;\n\n\t// One stored child per orbit of the board's symmetries.\n\tconst children: DealtChild[] = [];\n\tfor (let card = 0; card < DECK; card++) {\n\t\tif (used[card] || seen[card]) continue;\n\t\t// Ascending, so the first unseen card of an orbit is its lowest.\n\t\tconst child: DealtChild = { card, maps: [], cards: [], fixing: [], merged: false };\n\t\tfor (const sigma of stabiliser) {\n\t\t\tconst image = maps.card[sigma][card];\n\t\t\tif (image === card) child.fixing.push(sigma);\n\t\t\tif (seen[image]) continue;\n\t\t\tseen[image] = 1;\n\t\t\t// `sigma` sends `card` to `image`, so its inverse sends the\n\t\t\t// deal of `image` back onto this board.\n\t\t\tchild.maps.push(image === card ? 0 : maps.inverse(sigma));\n\t\t\tchild.cards.push(image);\n\t\t}\n\t\tchildren.push(child);\n\t}\n\n\t// Runout buckets: a child that plays like an earlier one is folded\n\t// into it, relabelled by swapping the two cards' ranks.\n\tif (merge) {\n\t\tconst boardRanks = new Set<number>();\n\t\tfor (let i = 0; i < width; i++) boardRanks.add(cards[base + i] >> 2);\n\t\tfor (let j = 0; j < children.length; j++) {\n\t\t\tconst later = children[j];\n\t\t\tconst rankJ = later.card >> 2;\n\t\t\tif (boardRanks.has(rankJ)) continue;\n\t\t\tfor (let i = 0; i < j; i++) {\n\t\t\t\tconst earlier = children[i];\n\t\t\t\tif (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;\n\t\t\t\tconst rankI = earlier.card >> 2;\n\t\t\t\tif (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;\n\t\t\t\tif (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;\n\t\t\t\tconst swap = maps.add(rankSwap(rankI, rankJ));\n\t\t\t\tfor (let m = 0; m < later.maps.length; m++) {\n\t\t\t\t\tearlier.maps.push(maps.then(later.maps[m], swap));\n\t\t\t\t\tearlier.cards.push(later.cards[m]);\n\t\t\t\t}\n\t\t\t\tlater.merged = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn children;\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\tconst children = runouts.childStart[round];\n\t\tconst relabel = runouts.orbitMap[round];\n\t\tfor (let child = children[index]; child < children[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, relabel[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\tconst keys = new Float64Array(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\t// By strength, ties in ascending order of combination. Sorted as plain\n\t\t// numbers, strength above the combination, since a typed array sorts\n\t\t// those natively and a comparator is called for every comparison.\n\t\tfor (let i = 0; i < count; i++) keys[i] = strength[live[i]] * 2048 + live[i];\n\t\tkeys.subarray(0, count).sort();\n\t\tconst slice = live.subarray(0, count);\n\t\tfor (let i = 0; i < count; i++) slice[i] = keys[i] % 2048;\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 * Hand-space index structures and terminal kernels.\n *\n * Purpose: let a traversal carry each player's reach and values as a dense\n * vector over the hands that player can hold on the current board — entry `i`\n * of their active list (`buildActiveLists` in cfr.ts) — instead of a sparse\n * 1326-wide array reached through a list of live combinations. Every loop\n * then runs `0..n` over contiguous memory.\n *\n * What a traversal needs to move between boards and to settle terminals:\n *\n * - At a deal, which parent hand each child hand is, for the stored board\n * and for every real deal it stands for (relabelled by the orbit's map).\n * Reach is gathered and values scatter-added through these.\n * - At a fold, which opposing hand is the very same combination as each of\n * mine, for the inclusion–exclusion that removes it.\n *\n * A showdown needs nothing here: on a final board the active lists are\n * already sorted by strength, with each entry's strength and cards beside it.\n */\n\nimport { COMBOS, DECK } from './cards.ts';\nimport type { PlayerIndex } from './cfr.ts';\nimport type { Runouts } from './runouts.ts';\n\n/** The active lists, as `buildActiveLists` lays them out. */\nexport interface HandLists {\n\treadonly start: Int32Array;\n\treadonly count: Uint16Array;\n\treadonly list: Uint16Array;\n\treadonly roundBase: Int32Array;\n\treadonly memberStart: Int32Array;\n\treadonly memberCombo: Uint16Array;\n}\n\n/** Everything a hand-space traversal looks up. */\nexport interface HandSpace {\n\t/**\n\t * Deals: for round `r`, orbit member `m` (an index into\n\t * `runouts.orbitMap[r]`) and player `p`, `up` from `upStart[r][m * 2 + p]`\n\t * holds, for each of the player's hands on the stored child board, the\n\t * index of the parent-board hand it is — through the member's relabelling.\n\t */\n\treadonly upStart: readonly Int32Array[];\n\treadonly up: Uint16Array;\n\t/**\n\t * Folds: for each list slot `(roundBase[r] + board) * 2 + p`, from\n\t * `sameStart[slot]`, the index in the other player's list of each of this\n\t * player's hands, or -1 where they cannot hold it.\n\t */\n\treadonly sameStart: Int32Array;\n\treadonly same: Int32Array;\n}\n\n/**\n * Point every hand the entries of one list stand for at its entry's position\n * in that list, or back at -1 with `clear`.\n */\nexport function markMembers(\n\tlists: Pick<HandLists, 'memberStart' | 'memberCombo'>,\n\tfrom: number,\n\tcount: number,\n\tindexOf: Int32Array,\n\tclear: boolean,\n): void {\n\tfor (let i = 0; i < count; i++) {\n\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\tindexOf[lists.memberCombo[m]] = clear ? -1 : i;\n\t\t}\n\t}\n}\n\n/** A list's offset and length for a round, board and player. */\nfunction span(lists: HandLists, round: number, board: number, player: number): [number, number] {\n\tconst slot = (lists.roundBase[round] + board) * 2 + player;\n\treturn [lists.start[slot], lists.count[slot]];\n}\n\n/** Build the hand-space structures for a prepared spot. */\nexport function buildHandSpace(\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tlists: HandLists,\n): HandSpace {\n\tvoid players;\n\tconst indexOf = new Int32Array(COMBOS).fill(-1);\n\n\t// Deals.\n\tconst upStart: Int32Array[] = [new Int32Array(0)];\n\t// Sized first: this is filled at the start of every solve, one entry per\n\t// hand per deal, and growing a plain array that far is most of its cost.\n\tlet upLength = 0;\n\tfor (let round = 1; round < runouts.rounds; round++) {\n\t\tconst orbitStart = runouts.orbitStart[round];\n\t\tfor (let child = 0; child < runouts.counts[round]; child++) {\n\t\t\tconst deals = orbitStart[child + 1] - orbitStart[child];\n\t\t\tupLength += deals * (span(lists, round, child, 0)[1] + span(lists, round, child, 1)[1]);\n\t\t}\n\t}\n\tconst up = new Uint16Array(upLength);\n\tlet upAt = 0;\n\tfor (let round = 1; round < runouts.rounds; round++) {\n\t\tconst orbitStart = runouts.orbitStart[round];\n\t\tconst starts = new Int32Array(runouts.orbitMap[round].length * 2);\n\t\tfor (let child = 0; child < runouts.counts[round]; child++) {\n\t\t\tconst parent = runouts.parent[round][child];\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst [parentFrom, parentCount] = span(lists, round - 1, parent, player);\n\t\t\t\tmarkMembers(lists, parentFrom, parentCount, indexOf, false);\n\t\t\t\tconst [childFrom, childCount] = span(lists, round, child, player);\n\t\t\t\tfor (let m = orbitStart[child]; m < orbitStart[child + 1]; m++) {\n\t\t\t\t\t// The member's map sends a real hand onto the stored board;\n\t\t\t\t\t// its inverse sends a stored hand back to the real one.\n\t\t\t\t\tconst back = runouts.maps.combo[runouts.maps.inverse(runouts.orbitMap[round][m])];\n\t\t\t\t\tstarts[m * 2 + player] = upAt;\n\t\t\t\t\tfor (let k = 0; k < childCount; k++) {\n\t\t\t\t\t\tconst real = back[lists.list[childFrom + k]];\n\t\t\t\t\t\tconst at = indexOf[real];\n\t\t\t\t\t\tif (at < 0) throw new Error('A relabelled hand is not in its range; the relabelling must preserve both ranges');\n\t\t\t\t\t\tup[upAt++] = at;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmarkMembers(lists, parentFrom, parentCount, indexOf, true);\n\t\t\t}\n\t\t}\n\t\tupStart.push(starts);\n\t}\n\n\t// Folds.\n\tconst slots = lists.roundBase[runouts.rounds] * 2;\n\tconst sameStart = new Int32Array(slots + 1);\n\tconst same = new Int32Array(lists.list.length);\n\tlet sameAt = 0;\n\tfor (let round = 0; round < runouts.rounds; 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 = (lists.roundBase[round] + board) * 2 + player;\n\t\t\t\tconst [otherFrom, otherCount] = span(lists, round, board, 1 - player);\n\t\t\t\tmarkMembers(lists, otherFrom, otherCount, indexOf, false);\n\t\t\t\tconst [from, count] = span(lists, round, board, player);\n\t\t\t\tsameStart[slot] = sameAt;\n\t\t\t\tfor (let i = 0; i < count; i++) same[sameAt++] = indexOf[lists.list[from + i]];\n\t\t\t\tmarkMembers(lists, otherFrom, otherCount, indexOf, true);\n\t\t\t}\n\t\t}\n\t}\n\tsameStart[slots] = sameAt;\n\n\treturn { upStart, up, sameStart, same };\n}\n\n/**\n * Values at a fold, in hand space, exact under card removal: each of my hands\n * wins or loses `payoff` against every opposing hand it does not collide with.\n *\n * @param oppReach the opponent's reach, over their list\n * @param oppCombos their list's combinations, from `oppFrom`\n * @param myCombos mine, from `myFrom`\n * @param same for each of my hands, its index in their list or -1\n * @param sums 52 doubles of scratch, all zero; left zero\n * @param out my values, `myCount` of them\n */\nexport function foldValuesHands(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tsame: Int32Array,\n\tsameFrom: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet total = 0;\n\tfor (let j = 0; j < oppCount; j++) {\n\t\tconst value = oppReach[j];\n\t\ttotal += value;\n\t\tsums[cardA[oppFrom + j]] += value;\n\t\tsums[cardB[oppFrom + j]] += value;\n\t}\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst twin = same[sameFrom + i];\n\t\t// The pair term: the one opposing hand holding both my cards.\n\t\tconst both = twin >= 0 ? oppReach[twin] : 0;\n\t\tout[i] = payoff * (total - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]] - both));\n\t}\n\tsums.fill(0, 0, DECK);\n}\n\n/**\n * Values at a showdown, in hand space, exact under card removal.\n *\n * On a final board both lists are sorted by strength, so this is two\n * contiguous sweeps. Ascending, the opponent's hands strictly weaker than\n * each of mine are added to running totals before mine is read, so its own\n * tie group and its own cards fall out; descending, the same for hands\n * strictly stronger. A hand's value is what it beats minus what beats it,\n * times `payoff`.\n *\n * @param sums 52 doubles of scratch, all zero; left zero\n */\nexport function showdownValuesHands(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\tstrength: Int32Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet running = 0;\n\tlet j = 0;\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j < oppCount && strength[oppFrom + j] < level) {\n\t\t\tconst value = oppReach[j];\n\t\t\trunning += value;\n\t\t\tsums[cardA[oppFrom + j]] += value;\n\t\t\tsums[cardB[oppFrom + j]] += value;\n\t\t\tj++;\n\t\t}\n\t\tout[i] = running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]]);\n\t}\n\tsums.fill(0, 0, DECK);\n\n\trunning = 0;\n\tj = oppCount - 1;\n\tfor (let i = myCount - 1; i >= 0; i--) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j >= 0 && strength[oppFrom + j] > level) {\n\t\t\tconst value = oppReach[j];\n\t\t\trunning += value;\n\t\t\tsums[cardA[oppFrom + j]] += value;\n\t\t\tsums[cardB[oppFrom + j]] += value;\n\t\t\tj--;\n\t\t}\n\t\tout[i] = payoff * (out[i] - (running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]])));\n\t}\n\tsums.fill(0, 0, DECK);\n}\n\n/**\n * Packed lists' card-removal sums: each entry's reach counted once per hand it\n * stands for, on that hand's own cards. Returns the reach-weighted total.\n */\nfunction addMembers(\n\treach: number,\n\tentry: number,\n\tmemberStart: Int32Array,\n\tmemberA: Uint8Array,\n\tmemberB: Uint8Array,\n\tsums: Float64Array,\n): number {\n\tconst to = memberStart[entry + 1];\n\tfor (let m = memberStart[entry]; m < to; m++) {\n\t\tsums[memberA[m]] += reach;\n\t\tsums[memberB[m]] += reach;\n\t}\n\treturn reach * (to - memberStart[entry]);\n}\n\n/** `foldValuesHands` over packed lists: every hand an opposing entry stands for counts. */\nexport function foldValuesPacked(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\tmemberStart: Int32Array,\n\tmemberA: Uint8Array,\n\tmemberB: Uint8Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tsame: Int32Array,\n\tsameFrom: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet total = 0;\n\tfor (let j = 0; j < oppCount; j++) total += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst twin = same[sameFrom + i];\n\t\tconst both = twin >= 0 ? oppReach[twin] : 0;\n\t\tout[i] = payoff * (total - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]] - both));\n\t}\n\tsums.fill(0, 0, DECK);\n}\n\n/** `showdownValuesHands` over packed lists: every hand an opposing entry stands for counts. */\nexport function showdownValuesPacked(\n\toppReach: Float64Array,\n\tcardA: Uint8Array,\n\tcardB: Uint8Array,\n\tmemberStart: Int32Array,\n\tmemberA: Uint8Array,\n\tmemberB: Uint8Array,\n\tstrength: Int32Array,\n\toppFrom: number,\n\toppCount: number,\n\tmyFrom: number,\n\tmyCount: number,\n\tpayoff: number,\n\tsums: Float64Array,\n\tout: Float64Array,\n): void {\n\tlet running = 0;\n\tlet j = 0;\n\tfor (let i = 0; i < myCount; i++) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j < oppCount && strength[oppFrom + j] < level) {\n\t\t\trunning += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);\n\t\t\tj++;\n\t\t}\n\t\tout[i] = running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]]);\n\t}\n\tsums.fill(0, 0, DECK);\n\n\trunning = 0;\n\tj = oppCount - 1;\n\tfor (let i = myCount - 1; i >= 0; i--) {\n\t\tconst level = strength[myFrom + i];\n\t\twhile (j >= 0 && strength[oppFrom + j] > level) {\n\t\t\trunning += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);\n\t\t\tj--;\n\t\t}\n\t\tout[i] = payoff * (out[i] - (running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]])));\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 { storedStrategy } from './cfr.ts';\nimport { markMembers } from './hands.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\t/** A combination's position in the current decision's hand list; -1 between uses. */\n\treadonly position: Int32Array;\n\t/** Each opposing hand's position in the acting list, or -1, per depth: deeper walks reuse `position`. */\n\treadonly at: 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\tposition: new Int32Array(COMBOS).fill(-1),\n\t\tat: make(() => new Int32Array(width)),\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\t\tconst starts = runouts.childStart[nextRound];\n\n\t\tfor (let childBoard = starts[board]; childBoard < starts[board + 1]; childBoard++) {\n\t\t\tconst stored = dealtCards[childBoard * width + width - 1];\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] ? stored : runouts.orbitCard[nextRound][m];\n\t\t\t\tconst map = runouts.maps.combo[runouts.orbitMap[nextRound][m]];\n\t\t\t\tconst blocked = (combo: number): boolean => cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt;\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 (blocked(combo)) 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 (!blocked(hands[k])) 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 (blocked(combo)) 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 lists = ctx.active;\n\tconst listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;\n\tconst activeFrom = lists.start[listSlot];\n\tconst activeCount = lists.count[listSlot];\n\t// Storage, and so the strategy, is laid out by position in this list.\n\tconst stride = activeCount;\n\tconst slotBase = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];\n\tconst strategy = buffers.strategy[depth];\n\tstoredStrategy(ctx, node, slotBase, actions, stride, strategy);\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 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\t// A packed entry's strategy is every hand's it stands for.\n\t\t\t\t\tconst share = strategy[a * stride + i];\n\t\t\t\t\tfor (let m = lists.memberStart[activeFrom + i]; m < lists.memberStart[activeFrom + i + 1]; m++) {\n\t\t\t\t\t\tconst combo = lists.memberCombo[m];\n\t\t\t\t\t\tout[row + combo] += share * value[row + 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// 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\t// Each opposing hand's position in the acting player's list here.\n\tconst position = buffers.position;\n\tmarkMembers(lists, activeFrom, activeCount, position, false);\n\tconst at = buffers.at[depth];\n\tfor (let c = 0; c < colCount; c++) at[cols[c]] = position[hands[cols[c]]];\n\tmarkMembers(lists, activeFrom, activeCount, position, true);\n\tfor (let a = 0; a < actions; a++) {\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// A hand not in the list here cannot be holding it.\n\t\t\tconst r = at[k] < 0 ? 0 : colReach[k] * strategy[a * stride + at[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/Ur9Uv0LBAAgAEECaiEADAELCwNAIAAgBEgEQCAAQQN0IgYgASAFamoiCSACIAZqKwMAIgxEAAAAAAAAAABkBHwgCSsDACAMowVEAAAAAAAA8D8gA7ejCzkDACAAQQFqIQAMAQsLIAdBAWohBwwBCwsL2wUDCH8BfAN7IAVBfnEhCyADIAVBA3RqIQkDQCAFIAdKBEAgB0EDdCIMIANqRAAAAAAAAAAAOQMAIAkgDGpEAAAAAAAAAAA5AwAgB0EBaiEHDAELCwNAIAQgCEoEQCAFIAhsQQN0IQxBACEHA0AgByALSARAIAdBA3QiDSADaiIOIA79AAQAIAAgDGogDWr9AAQA/fAB/QsEACAGBEAgCSANaiIOIA79AAQAIAEgDGogDWr9AAQA/QwAAAAAAAAAAAAAAAAAAAAA/fUB/fAB/QsEAAsgB0ECaiEHDAELCwNAIAUgB0oEQCAHQQN0Ig0gA2oiDiAOKwMAIAAgDGogDWorAwCgOQMAIAYEQCAJIA1qIg4gDisDACABIAxqIA1qKwMAIg9EAAAAAAAAAAAgD0QAAAAAAAAAAGQboDkDAAsgB0EBaiEHDAELCyAIQQFqIQgMAQsLRAAAAAAAAPA/IAS3o/0UIRADQCAEIApKBEAgBSAKbEEDdCEHQQAhCANAIAggC0gEQCAIQQN0IgwgA2r9AAQAIREgAiAHaiAMaiAAIAdqIAxq/QAEACAR/fMBIAYEeyABIAdqIAxq/QAEAP0MAAAAAAAAAAAAAAAAAAAAAP31ASAJIAxq/QAEACIS/fMBIBAgEv0MAAAAAAAAAAAAAAAAAAAAAP1K/VIFIBALIBH9DAAAAAAAAAAAAAAAAAAAAAD9Sv1S/QsEACAIQQJqIQgMAQsLA0AgBSAISgRAIAhBA3QiDCACIAdqaiADIAxqKwMAIg9EAAAAAAAAAABkBHwgACAHaiAMaisDACAPowUgBgR/IAkgCEEDdGorAwBEAAAAAAAAAABkBUEACwR8IAhBA3QiDCABIAdqaisDACIPRAAAAAAAAAAAIA9EAAAAAAAAAABkGyAJIAxqKwMAowVEAAAAAAAA8D8gBLejCws5AwAgCEEBaiEIDAELCyAKQQFqIQoMAQsLCw==';\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 { makeTerminalScratch } from './showdown.ts';\nimport type { HandSpace } from './hands.ts';\nimport { foldValuesHands, foldValuesPacked, showdownValuesHands, showdownValuesPacked } from './hands.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, and any held in reserve, 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/**\n * Build a player's index from their range weights.\n *\n * @param reserve combinations to index although they weigh nothing, so a\n * later change of range can give them weight without moving any storage\n */\nexport function buildPlayerIndex(weights: Float64Array, reserve?: 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 || (reserve !== undefined && reserve[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/**\n * Whether a combination is the one stored for its mirror orbit on a board:\n * the lowest combination the board's own symmetries send it to. A board\n * without symmetry stores every hand.\n */\nexport function orbitLeader(runouts: Runouts, round: number, board: number, combo: number): boolean {\n\tconst from = runouts.stabiliserStart[round][board];\n\tconst to = runouts.stabiliserStart[round][board + 1];\n\tfor (let k = from + 1; k < to; k++) {\n\t\tif (runouts.maps.combo[runouts.stabiliserMap[round][k]][combo] < combo) return false;\n\t}\n\treturn true;\n}\n\nconst INT32_MAX = 2 ** 31 - 1;\n\n/** Slot offsets for every decision node. */\nexport interface Layout {\n\t/**\n\t * Where each decision node's storage starts. Its block on a board is\n\t * `actions` rows of the owner's hands live there, in hand-list order —\n\t * entry `i` of their active list — so a row is as long as that list and\n\t * blocked hands take no room. See `blockBase`. Int32 while every slot\n\t * fits one, which keeps the traversal's indexing on integers; Float64,\n\t * exact to 2^53, for a tree past 2^31 slots, where Int32 would wrap.\n\t * With compact storage, a node of a compact round's offset is into its\n\t * chunk of the compact arrays instead.\n\t */\n\treadonly offset: Int32Array | Float64Array;\n\t/** For each list slot `(roundBase[r] + board) * 2 + p`: rows before this board's. */\n\treadonly rowStart: Int32Array;\n\t/** First list index of each round, as `ActiveLists.roundBase`. */\n\treadonly roundBase: 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\t/** Slots one iteration walks: `totalSlots`, and with shared storage what it would be unshared. */\n\treadonly walkedSlots: number;\n\treadonly maxActions: number;\n\treadonly bytes: number;\n\t/**\n\t * Whether some nodes share another's storage (`SpotConfig.shareHistories`):\n\t * a block may then be visited more than once an iteration.\n\t */\n\treadonly shared: boolean;\n\t/**\n\t * Per node, 1 where regret updates are weighted by the actor's own reach:\n\t * nodes whose storage more than one history shares, under\n\t * `shareHistories`. Null otherwise.\n\t */\n\treadonly reachWeighted: Uint8Array | null;\n\t/**\n\t * The first round stored compactly (see `CompactStorage`); the round\n\t * count when none is, so `round >= compactFrom` says whether a node is.\n\t */\n\treadonly compactFrom: number;\n\t/** Slots of compactly stored regrets; 0 without compact storage. */\n\treadonly compactSlots: number;\n\t/** Per node of a compact round: where its hands' scales start in its chunk, else -1. */\n\treadonly handOffset: Float64Array | null;\n\treadonly compactHands: number;\n\t/**\n\t * Compact storage comes in chunks, each its own buffer, because browsers\n\t * refuse an ArrayBuffer of 2 GiB or more. A node's storage is all in one\n\t * chunk: per node of a compact round, which (else -1); its `offset` and\n\t * `handOffset` count from that chunk's start.\n\t */\n\treadonly compactChunk: Int32Array | null;\n\t/** Per chunk: its slots, its hands, and the slots of every chunk before it. */\n\treadonly chunkSlots: readonly number[];\n\treadonly chunkHands: readonly number[];\n\treadonly chunkStart: readonly number[];\n}\n\n/**\n * Compact storage, for `SpotConfig.compactStorage`: from round `from` on,\n * regrets and (with `sums`) strategy sums as 8-bit integers; without sums,\n * each hand's strategy there is read as the current profile.\n */\nexport interface CompactPlan {\n\t/** First round stored compactly, counted from the spot's first. */\n\treadonly from: number;\n\t/** Largest magnitude stored: 127 for 8 bits. */\n\treadonly steps: number;\n\t/** One power-of-two scale per hand per block, else one float64 per block. */\n\treadonly perHand: boolean;\n\t/** Round at random, unbiased, rather than to nearest. */\n\treadonly stochastic: boolean;\n\t/** Keep the regrets as float32: only the sums are dropped. */\n\treadonly float: boolean;\n\t/** Largest buffer to allocate; compact storage is split in chunks no bigger. */\n\treadonly chunkBytes: number;\n\t/**\n\t * Keep 8-bit strategy sums too, with their own per-hand scale, so these\n\t * nodes keep the average strategy. Per-hand scale only.\n\t */\n\treadonly sums: boolean;\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 * @param alias each node's storage owner, from `aliasHistories`: a node\n * owned by another takes its owner's blocks and adds none. Unset, every\n * node owns its own.\n * @param compact compact storage's plan, for `SpotConfig.compactStorage`\n */\nexport function buildLayout(\n\ttree: Tree,\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tbytesPerElement: number,\n\talias?: Int32Array,\n\tcompact?: CompactPlan,\n): Layout {\n\tconst { roundBase, rowStart, totals } = liveRows(runouts, players);\n\n\tconst offset = new Float64Array(tree.nodeCount).fill(-1);\n\tconst blockOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tconst compactFrom = compact ? compact.from : runouts.rounds;\n\tconst handOffset = compact ? new Float64Array(tree.nodeCount).fill(-1) : null;\n\tconst compactChunk = compact ? new Int32Array(tree.nodeCount).fill(-1) : null;\n\tconst chunkSlots: number[] = [];\n\tconst chunkHands: number[] = [];\n\tconst chunkStart: number[] = [];\n\tconst width = compact?.float ? 4 : 1;\n\tlet total = 0;\n\tlet compactSlots = 0;\n\tlet compactHands = 0;\n\tlet blocks = 0;\n\tlet maxActions = 0;\n\tlet shared = false;\n\tlet walked = 0;\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\tconst hands = totals[tree.round[node] * 2 + tree.player[node]];\n\t\t// An owner always comes before the nodes it owns, so its blocks are placed.\n\t\twalked += actions * hands;\n\t\tif (alias !== undefined && alias[node] !== node) {\n\t\t\tconst owner = alias[node];\n\t\t\tif (owner > node) throw new Error('buildLayout: a storage owner must come before the nodes it owns');\n\t\t\toffset[node] = offset[owner];\n\t\t\tblockOffset[node] = blockOffset[owner];\n\t\t\tif (compact) {\n\t\t\t\thandOffset![node] = handOffset![owner];\n\t\t\t\tcompactChunk![node] = compactChunk![owner];\n\t\t\t}\n\t\t\tshared = true;\n\t\t\tcontinue;\n\t\t}\n\t\tblockOffset[node] = blocks;\n\t\tblocks += runouts.counts[tree.round[node]];\n\t\tif (tree.round[node] >= compactFrom) {\n\t\t\tconst slots = actions * hands;\n\t\t\tlet chunk = chunkSlots.length - 1;\n\t\t\tif (slots * width > compact!.chunkBytes) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`compactStorage.chunkBytes is ${compact!.chunkBytes}, but one decision needs ${slots * width} bytes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (chunk < 0 || (chunkSlots[chunk] + slots) * width > compact!.chunkBytes || chunkHands[chunk] + hands > compact!.chunkBytes) {\n\t\t\t\tchunk++;\n\t\t\t\tchunkSlots.push(0);\n\t\t\t\tchunkHands.push(0);\n\t\t\t\tchunkStart.push(compactSlots);\n\t\t\t}\n\t\t\tcompactChunk![node] = chunk;\n\t\t\toffset[node] = chunkSlots[chunk];\n\t\t\thandOffset![node] = chunkHands[chunk];\n\t\t\tchunkSlots[chunk] += slots;\n\t\t\tchunkHands[chunk] += hands;\n\t\t\tcompactSlots += slots;\n\t\t\tcompactHands += hands;\n\t\t} else {\n\t\t\toffset[node] = total;\n\t\t\ttotal += actions * hands;\n\t\t}\n\t}\n\tconst scales = bytesPerElement === 2 ? blocks * 8 * 2 : 0;\n\tconst compactBytes = !compact\n\t\t? 0\n\t\t: compact.float\n\t\t\t? compactSlots * 4\n\t\t\t: (compactSlots + (compact.perHand ? compactHands : blocks * 8)) * (compact.sums ? 2 : 1);\n\treturn {\n\t\toffset: Math.max(total, ...chunkSlots) <= INT32_MAX ? Int32Array.from(offset) : offset,\n\t\tblockOffset, blocks, totalSlots: total, walkedSlots: walked, maxActions, rowStart, roundBase,\n\t\tbytes: total * bytesPerElement * 2 + scales + compactBytes,\n\t\tshared,\n\t\treachWeighted: shared ? sharedNodes(tree, alias!) : null,\n\t\tcompactFrom, compactSlots, handOffset, compactHands, compactChunk, chunkSlots, chunkHands, chunkStart,\n\t};\n}\n\n/** `liveRows` of the players last asked about, per set of runouts. */\nconst liveRowsOf = new WeakMap<Runouts, { players: readonly [PlayerIndex, PlayerIndex]; rows: LiveRows }>();\n\ninterface LiveRows {\n\treadonly roundBase: Int32Array;\n\t/** Per list slot, how many of the player's hands earlier boards of the round hold. */\n\treadonly rowStart: Int32Array;\n\t/** Per round and player, the hands over all its boards. */\n\treadonly totals: Int32Array;\n}\n\n/**\n * How many of each player's hands each board leaves live: a block's rows.\n *\n * Every hand on every board, and the same for any tree and storage width, so\n * it is kept for the spot's runouts and players: defining a spot lays its\n * storage out up to three times, and each run once more.\n */\nfunction liveRows(runouts: Runouts, players: readonly [PlayerIndex, PlayerIndex]): LiveRows {\n\tconst kept = liveRowsOf.get(runouts);\n\tif (kept && kept.players[0] === players[0] && kept.players[1] === players[1]) return kept.rows;\n\tconst roundBase = new Int32Array(runouts.rounds + 1);\n\tfor (let round = 0; round < runouts.rounds; round++) roundBase[round + 1] = roundBase[round] + runouts.counts[round];\n\tconst rowStart = new Int32Array(roundBase[runouts.rounds] * 2);\n\tconst totals = new Int32Array(runouts.rounds * 2);\n\tconst onBoard = new Uint8Array(DECK);\n\tconst comboMaps = runouts.maps.combo;\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\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\tonBoard.fill(0);\n\t\t\tfor (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;\n\t\t\tconst stabFrom = stabStart[board] + 1;\n\t\t\tconst stabTo = stabStart[board + 1];\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst index = players[player];\n\t\t\t\tlet live = 0;\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\t// Only the lowest hand of a mirror orbit is stored; see `orbitLeader`.\n\t\t\t\t\tlet leader = 1;\n\t\t\t\t\tfor (let k = stabFrom; k < stabTo; k++) {\n\t\t\t\t\t\tif (comboMaps[stabMap[k]][combo] < combo) {\n\t\t\t\t\t\t\tleader = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlive += leader;\n\t\t\t\t}\n\t\t\t\trowStart[(roundBase[round] + board) * 2 + player] = totals[round * 2 + player];\n\t\t\t\ttotals[round * 2 + player] += live;\n\t\t\t}\n\t\t}\n\t}\n\tconst rows = { roundBase, rowStart, totals };\n\tliveRowsOf.set(runouts, { players, rows });\n\treturn rows;\n}\n\n/** 1 for every node whose storage more than one node uses, owner included. */\nfunction sharedNodes(tree: Tree, alias: Int32Array): Uint8Array {\n\tconst marks = new Uint8Array(tree.nodeCount);\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (alias[node] !== node) marks[node] = marks[alias[node]] = 1;\n\t}\n\treturn marks;\n}\n\n/**\n * Where a node's block on a board starts: `actions` rows of the owner's hands\n * live on that board, in their hand-list order.\n */\nexport function blockBase(layout: Layout, tree: Tree, node: number, board: number): number {\n\t// Into the compact regrets for a node of a compact round.\n\tconst slot = (layout.roundBase[tree.round[node]] + board) * 2 + tree.player[node];\n\treturn layout.offset[node] + tree.numEdges[node] * layout.rowStart[slot];\n}\n\n/** Accumulated regrets: float, or 16-bit integers scaled per block. */\nexport type RegretStore = Float64Array | Float32Array | Int16Array;\n/** Regrets as one of the stores, or compact storage's 8-bit ones. */\nexport type AnyRegrets = RegretStore | Int8Array;\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\t/**\n\t * Compact storage (`Approximations.compactStorage`), else unset: nodes of\n\t * rounds from `compact.from` on keep only `compactRegret`, one array per\n\t * chunk (`layout.compactChunk`) laid out by `layout.offset` as other\n\t * nodes' regrets are, and each hand's scale in\n\t * `handShift` — a stored integer `q` means `q * 2^(shift - SHIFT_BIAS)`,\n\t * and a shift of 0 means the hand's regrets are all zero. With a block\n\t * scale instead, `compactScale` holds it as `regretScale` does for 16-bit\n\t * storage.\n\t */\n\treadonly compact?: CompactPlan | null;\n\treadonly compactRegret?: readonly (Int8Array | Float32Array)[] | null;\n\treadonly handShift?: readonly Uint8Array[] | null;\n\t/**\n\t * With `compact.sums`: 8-bit strategy sums, laid out as `compactRegret`,\n\t * and their per-hand scales, as `handShift` is for regrets.\n\t */\n\treadonly compactSum?: readonly Uint8Array[] | null;\n\treadonly sumShift?: readonly Uint8Array[] | null;\n\t/** Compact storage's per-block scales, when it keeps one per block rather than per hand. */\n\treadonly compactScale?: 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/** How hand-space vectors move between boards and meet at terminals. */\n\treadonly hands: HandSpace;\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/**\n\t * Total weighted mass of legal matchups, as the ranges stood when the\n\t * run was made; the solver divides by the mass as they stand.\n\t */\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\t/**\n\t * Chance sampling with baselines, for `Approximations.chanceSampling`;\n\t * unset or null for the exact traversal.\n\t */\n\tsampling?: Sampling | null;\n\t/**\n\t * With shared storage (`Layout.shared`), per block the iteration DCFR\n\t * last discounted it in. A shared block is visited once per history that\n\t * reaches it, and only the first visit of an iteration discounts. Unset or\n\t * null for unshared storage, where every block is visited once.\n\t */\n\tdiscounted?: Int32Array | null;\n}\n\n/** How chance sampling picks deals; see `Approximations.chanceSampling`. */\nexport interface SamplingOptions {\n\t/**\n\t * Probability of walking each deal on a training iteration, chosen at\n\t * random per deal and iteration. Default 0.35. Ignored with `every`.\n\t */\n\treadonly p?: number;\n\t/**\n\t * Walk every deal exactly once every this many iterations, in rotation,\n\t * instead of at random. Measured, it converges worse than random at the\n\t * same rate; kept for comparison.\n\t */\n\treadonly every?: number;\n\t/**\n\t * Betting rounds whose deals are sampled, counted from the spot's first:\n\t * from a flop, 1 is the turn and 2 the river. Default every round after\n\t * the first.\n\t */\n\treadonly rounds?: readonly number[];\n\t/**\n\t * How a walked deal's fresh value meets its baseline: 'unbiased' adds\n\t * `(v - b) / p` to the baseline, the VR-MCCFR estimator; 'latest' uses\n\t * `v` itself, the freshest value without the correction.\n\t */\n\treadonly estimator?: 'unbiased' | 'latest';\n\t/** Apply the DCFR discounts a skipped subtree missed when it is next walked. Default true. */\n\treadonly catchUp?: boolean;\n}\n\n/** Where sampling keeps what, for a spot; see `makeSampling`. */\nexport interface SamplingPlan {\n\treadonly rounds: Uint8Array;\n\treadonly p: number;\n\treadonly every: number;\n\treadonly unbiased: boolean;\n\treadonly catchUp: boolean;\n\t/** Per chance node into a sampled round: where its baselines start, else -1. */\n\treadonly baseOffset: Int32Array;\n\t/** Per list slot of a sampled round: offset of that board and player's baseline within a node's. */\n\treadonly boardOffset: Int32Array;\n\t/** Per chance node: where its last-walk entries start, two per child board. */\n\treadonly walkOffset: Int32Array;\n\t/** Baseline values, last-walk entries and blocks the state holds. */\n\treadonly values: number;\n\treadonly walks: number;\n\treadonly blocks: number;\n}\n\n/** Sampling state: baselines, when each was last walked, when each block was last updated. */\nexport interface Sampling extends SamplingPlan {\n\treadonly baseline: Float32Array;\n\treadonly lastWalk: Int32Array;\n\t/** Per block: the iteration it was last updated in, for DCFR catch-up. */\n\treadonly lastUpdate: Int32Array;\n\t/** Memory the state takes. */\n\treadonly bytes: number;\n}\n\n/** The rounds chance sampling samples, of a spot with `rounds` betting rounds. */\nexport function sampledRounds(options: SamplingOptions, rounds: number): number[] {\n\tconst asked = options.rounds ?? Array.from({ length: rounds }, (_, r) => r);\n\treturn asked.filter((r) => r > 0 && r < rounds);\n}\n\n/** Lay out sampling state for a spot. */\nexport function planSampling(\n\ttree: Tree,\n\trunouts: Runouts,\n\tactive: ActiveLists,\n\tlayout: Layout,\n\toptions: SamplingOptions,\n): SamplingPlan {\n\tconst rounds = new Uint8Array(runouts.rounds);\n\tfor (const r of sampledRounds(options, runouts.rounds)) rounds[r] = 1;\n\tconst boardOffset = new Int32Array(active.roundBase[runouts.rounds] * 2);\n\tconst perNode = new Float64Array(runouts.rounds);\n\tfor (let r = 1; r < runouts.rounds; r++) {\n\t\tif (!rounds[r]) continue;\n\t\tlet total = 0;\n\t\tfor (let b = 0; b < runouts.counts[r]; b++) {\n\t\t\tfor (let p = 0; p < 2; p++) {\n\t\t\t\tconst slot = (active.roundBase[r] + b) * 2 + p;\n\t\t\t\tboardOffset[slot] = total;\n\t\t\t\ttotal += active.count[slot];\n\t\t\t}\n\t\t}\n\t\tperNode[r] = total;\n\t}\n\tconst baseOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tconst walkOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tlet values = 0;\n\tlet walks = 0;\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (tree.kind[node] !== NodeKind.Chance) continue;\n\t\tconst next = tree.round[node] + 1;\n\t\tif (next >= runouts.rounds || !rounds[next]) continue;\n\t\tbaseOffset[node] = values;\n\t\twalkOffset[node] = walks;\n\t\tvalues += perNode[next];\n\t\twalks += runouts.counts[next] * 2;\n\t}\n\tif (values > 0x3fffffff) throw new Error('chanceSampling: too many baseline values for this spot');\n\tconst every = options.every ?? 0;\n\tconst p = every > 0 ? 1 / every : (options.p ?? 0.35);\n\tif (!(p > 0 && p <= 1)) throw new Error(`chanceSampling: p must be in (0, 1], got ${p}`);\n\treturn {\n\t\trounds, p, every,\n\t\tunbiased: (options.estimator ?? 'unbiased') === 'unbiased',\n\t\tcatchUp: options.catchUp ?? true,\n\t\tbaseOffset, boardOffset, walkOffset,\n\t\tvalues, walks, blocks: layout.blocks,\n\t};\n}\n\n/** Bytes sampling state takes beyond its plan's small offset tables. */\nexport function samplingBytes(plan: SamplingPlan): number {\n\treturn (plan.values + plan.walks + plan.blocks) * 4;\n}\n\n/**\n * Sampling state over the given storage, or freshly allocated by `allocate`\n * (plain buffers by default; shared ones for a threaded solve, whose threads\n * each keep the state of their own runouts in it).\n */\nexport function makeSampling(\n\tplan: SamplingPlan,\n\tstorage?: { baseline: Float32Array; lastWalk: Int32Array; lastUpdate: Int32Array },\n\tallocate: (bytes: number) => ArrayBuffer | SharedArrayBuffer = (bytes) => new ArrayBuffer(bytes),\n): Sampling {\n\treturn {\n\t\t...plan,\n\t\tbaseline: storage?.baseline ?? new Float32Array(allocate(plan.values * 4)),\n\t\tlastWalk: storage?.lastWalk ?? new Int32Array(allocate(plan.walks * 4)),\n\t\tlastUpdate: storage?.lastUpdate ?? new Int32Array(allocate(plan.blocks * 4)),\n\t\tbytes: samplingBytes(plan),\n\t};\n}\n\n/** Whether a deal is walked on an iteration. */\nfunction sampled(s: Sampling, node: number, board: number, t: number): boolean {\n\tlet h = Math.imul(node ^ Math.imul(board, 0x9e3779b1), 0x85ebca6b);\n\tif (s.every > 0) {\n\t\th ^= h >>> 13;\n\t\th = Math.imul(h, 0xc2b2ae35);\n\t\th ^= h >>> 16;\n\t\treturn ((h >>> 0) + t) % s.every === 0;\n\t}\n\th ^= Math.imul(t, 0x27d4eb2f);\n\th ^= h >>> 15;\n\th = Math.imul(h, 0xc2b2ae35);\n\th ^= h >>> 13;\n\th = Math.imul(h, 0x165667b1);\n\th ^= h >>> 16;\n\treturn (h >>> 0) / 4294967296 < s.p;\n}\n\nconst factorCache: { keepPositive: number; keepNegative: number; keepSum: number }[] = [];\nfunction cachedFactors(t: number): { keepPositive: number; keepNegative: number; keepSum: number } {\n\tlet f = factorCache[t];\n\tif (f === undefined) factorCache[t] = f = dcfrFactors(t);\n\treturn f;\n}\n\n/**\n * What DCFR has a block keep as iteration `iterWeight` (counted from 1)\n * updates it, for every storage the update runs at. The order matters:\n * first, a shared block another history already discounted this iteration\n * keeps everything; then, with chance sampling, the discounts of the\n * iterations a skipped block missed are multiplied in. Marks the block\n * discounted and updated at `iterWeight`. DCFR only: callers check\n * `ctx.dcfr` first, where assembly/engine.ts's `blockFactors` checks it\n * itself and passes CFR+'s factors through.\n */\nfunction blockFactors(\n\tctx: Context,\n\tblock: number,\n\titerWeight: number,\n): { keepPositive: number; keepNegative: number; keepSum: number } {\n\tlet { keepPositive, keepNegative, keepSum } = cachedFactors(iterWeight);\n\tconst discounted = ctx.discounted;\n\tif (discounted !== undefined && discounted !== null) {\n\t\t// Another history already discounted this shared block this iteration.\n\t\tif (discounted[block] === iterWeight) keepPositive = keepNegative = keepSum = 1;\n\t\tdiscounted[block] = iterWeight;\n\t}\n\tconst sampling = ctx.sampling;\n\tif (sampling !== undefined && sampling !== null) {\n\t\t// A subtree chance sampling skipped missed those iterations'\n\t\t// discounts; nothing was added meanwhile, so each sign held.\n\t\tif (sampling.catchUp) {\n\t\t\tfor (let s = sampling.lastUpdate[block] + 1; s < iterWeight; s++) {\n\t\t\t\tconst f = cachedFactors(s);\n\t\t\t\tkeepPositive *= f.keepPositive;\n\t\t\t\tkeepNegative *= f.keepNegative;\n\t\t\t\tkeepSum *= f.keepSum;\n\t\t\t}\n\t\t}\n\t\tsampling.lastUpdate[block] = iterWeight;\n\t}\n\treturn { keepPositive, keepNegative, keepSum };\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 */\nexport interface 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/** Each entry's two cards, beside `list`. */\n\treadonly cardA: Uint8Array;\n\treadonly cardB: Uint8Array;\n\t/**\n\t * Each entry's strength on its final board, beside `list`; final-board\n\t * lists are sorted by it. Zero elsewhere.\n\t */\n\treadonly strength: Int32Array;\n\t/**\n\t * On a board with symmetry left, a list holds one hand per mirror orbit —\n\t * the lowest combination, see `orbitLeader` — standing for the whole\n\t * orbit. Mirrored hands play alike, since the board and both ranges look\n\t * the same after swapping suits, so one hand's strategy, reach and value\n\t * are all of theirs; storing them once is exact, and shortens every vector\n\t * there. Whether a list holds any orbit of more than one hand, beside\n\t * `start`: only those need the weighted deal and terminal kernels.\n\t */\n\treadonly packed: Uint8Array;\n\t/** How many hands each entry stands for, beside `list`: 1 unpacked. */\n\treadonly multiplicity: Float64Array;\n\t/**\n\t * The hands each entry stands for, itself first: `memberCombo` and their\n\t * cards from `memberStart[e]` to `memberStart[e + 1]`.\n\t */\n\treadonly memberStart: Int32Array;\n\treadonly memberCombo: Uint16Array;\n\treadonly memberA: Uint8Array;\n\treadonly memberB: Uint8Array;\n}\n\nfunction buildActiveLists(\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tshowdown: ShowdownTable | null = null,\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 packedSlot = new Uint8Array(slots);\n\t// This runs at the start of every solve, over every hand on every board,\n\t// so it writes typed arrays sized once: no list can hold more than its\n\t// player's whole range.\n\tconst capacity = roundBase[runouts.rounds] * (players[0].count + players[1].count);\n\tconst list = new Uint16Array(capacity);\n\tconst entrySlot = new Uint16Array(capacity);\n\tconst strength = new Int32Array(capacity);\n\tconst memberStart = new Int32Array(capacity + 1);\n\t// An entry stands for itself and at most one image per symmetry.\n\tlet members = new Uint16Array(capacity);\n\tconst onBoard = new Uint8Array(DECK);\n\tconst seen = new Uint8Array(COMBOS);\n\tconst comboMaps = runouts.maps.combo;\n\tconst last = runouts.rounds - 1;\n\tlet entries = 0;\n\tlet memberCount = 0;\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\tconst stabStart = runouts.stabiliserStart[round];\n\t\tconst stabMap = runouts.stabiliserMap[round];\n\t\t// On a final board, hands in order of strength: a showdown is then one\n\t\t// contiguous sweep. Order is free everywhere else.\n\t\tconst ranked = showdown !== null && round === last ? showdown : null;\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\tconst stabFrom = stabStart[board] + 1;\n\t\t\tconst stabTo = stabStart[board + 1];\n\t\t\tconst symmetric = stabTo > stabFrom;\n\t\t\tif (memberCount + (players[0].count + players[1].count) * (stabTo - stabFrom + 1) > members.length) {\n\t\t\t\tconst grown = new Uint16Array(Math.max(members.length * 2, memberCount + (players[0].count + players[1].count) * (stabTo - stabFrom + 1)));\n\t\t\t\tgrown.set(members.subarray(0, memberCount));\n\t\t\t\tmembers = grown;\n\t\t\t}\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;\n\t\t\t\t// The showdown table already holds this board's hands by\n\t\t\t\t// strength, ties in ascending order: the player's own, in that\n\t\t\t\t// order, are their list. Elsewhere, their range in its order.\n\t\t\t\tconst candidates = ranked ? ranked.liveCount[board] : index.count;\n\t\t\t\tconst orderBase = ranked ? board * ranked.stride : 0;\n\t\t\t\tconst groupBase = ranked ? board * (ranked.stride + 1) : 0;\n\t\t\t\tlet group = 0;\n\t\t\t\tfor (let c = 0; c < candidates; c++) {\n\t\t\t\t\tlet combo: number;\n\t\t\t\t\tlet at: number;\n\t\t\t\t\tif (ranked) {\n\t\t\t\t\t\twhile (c >= ranked.groupStart[groupBase + group + 1]) group++;\n\t\t\t\t\t\tcombo = ranked.order[orderBase + c];\n\t\t\t\t\t\tat = index.slot[combo];\n\t\t\t\t\t\tif (at < 0) continue;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tat = c;\n\t\t\t\t\t\tcombo = index.combos[c];\n\t\t\t\t\t\tif (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;\n\t\t\t\t\t}\n\t\t\t\t\t// Only the lowest hand of a mirror orbit is stored; see `orbitLeader`.\n\t\t\t\t\tlet leader = true;\n\t\t\t\t\tfor (let k = stabFrom; k < stabTo; k++) {\n\t\t\t\t\t\tif (comboMaps[stabMap[k]][combo] < combo) {\n\t\t\t\t\t\t\tleader = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!leader) continue;\n\t\t\t\t\tlist[entries] = combo;\n\t\t\t\t\tentrySlot[entries] = at;\n\t\t\t\t\tstrength[entries] = group;\n\t\t\t\t\tmemberStart[entries] = memberCount;\n\t\t\t\t\tmembers[memberCount++] = combo;\n\t\t\t\t\tif (symmetric) {\n\t\t\t\t\t\t// The rest of its orbit, which it stands for.\n\t\t\t\t\t\tconst first = memberCount - 1;\n\t\t\t\t\t\tseen[combo] = 1;\n\t\t\t\t\t\tfor (let k = stabFrom; k < stabTo; k++) {\n\t\t\t\t\t\t\tconst image = comboMaps[stabMap[k]][combo];\n\t\t\t\t\t\t\tif (seen[image]) continue;\n\t\t\t\t\t\t\tseen[image] = 1;\n\t\t\t\t\t\t\tmembers[memberCount++] = image;\n\t\t\t\t\t\t\tpackedSlot[slot] = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (let m = first; m < memberCount; m++) seen[members[m]] = 0;\n\t\t\t\t\t}\n\t\t\t\t\tentries++;\n\t\t\t\t}\n\t\t\t\tcount[slot] = entries - start[slot];\n\t\t\t}\n\t\t}\n\t}\n\tmemberStart[entries] = memberCount;\n\n\tconst cardA = new Uint8Array(entries);\n\tconst cardB = new Uint8Array(entries);\n\tconst multiplicity = new Float64Array(entries);\n\tfor (let e = 0; e < entries; e++) {\n\t\tcardA[e] = COMBO_CARDS[list[e] * 2];\n\t\tcardB[e] = COMBO_CARDS[list[e] * 2 + 1];\n\t\tmultiplicity[e] = memberStart[e + 1] - memberStart[e];\n\t}\n\tconst memberCombo = members.slice(0, memberCount);\n\tconst memberA = new Uint8Array(memberCount);\n\tconst memberB = new Uint8Array(memberCount);\n\tfor (let m = 0; m < memberCount; m++) {\n\t\tmemberA[m] = COMBO_CARDS[memberCombo[m] * 2];\n\t\tmemberB[m] = COMBO_CARDS[memberCombo[m] * 2 + 1];\n\t}\n\treturn {\n\t\tstart, count, list: list.slice(0, entries), slot: entrySlot.slice(0, entries), roundBase,\n\t\tcardA, cardB, strength: strength.slice(0, entries), packed: packedSlot, multiplicity,\n\t\tmemberStart: memberStart.slice(0, entries + 1), memberCombo, memberA, memberB,\n\t};\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\t/** 52 doubles for the terminal kernels' per-card sums, kept zero between uses. */\n\treadonly cardSums: Float64Array;\n}\n\nexport function 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\tcardSums: new Float64Array(DECK),\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\nexport function 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). Before iteration `t` adds its\n * regrets, accumulated positive regret is scaled by `s^α / (s^α + 1)` with\n * `s = t - 2` (see `dcfrFactors`) and negative regret by `s^β / (s^β + 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 *\n * Each iteration adds its strategy to the sum as it is, not weighted by the\n * hand's own reach (as postflop-solver does). A hand that equilibrium play\n * stops sending to a node then still averages to what its regrets settled on\n * there; with own-reach weighting the near-uniform early iterations swamped\n * it, so play continued off the path was close to random (issue #8). This\n * holds at every precision, here and in assembly/engine.ts. CFR+ keeps the\n * own-reach weighting: its iterates oscillate, and unweighted they averaged\n * to 2–3× the exploitability at the same iteration count.\n */\n// assembly/engine.ts repeats these in its sampling catch-up; keep in step.\nconst DCFR_ALPHA = 1.5;\nconst DCFR_BETA = 0;\nconst DCFR_GAMMA = 3;\n\n/**\n * DCFR's three factors before iteration `t` (counted from 1) adds its own\n * values: what positive regret, negative regret and the strategy sum keep.\n *\n * The positive factor counts iterations from the second, so iteration 2\n * keeps none of iteration 1's positive regret: that came from the uniform\n * starting strategy and says little. Measured against counting from the\n * first, it reaches 0.3% of pot in 10–15% fewer iterations on flop and turn\n * spots and is never worse; with γ 3 rather than 2, on top, it is better\n * still on most and never worse. A restart of the average at powers of 4 was\n * tried too and was worse on the turn.\n */\nexport function dcfrFactors(t: number): { keepPositive: number; keepNegative: number; keepSum: number } {\n\tconst age = t > 2 ? t - 2 : 0;\n\tconst grown = age ** DCFR_ALPHA;\n\tconst shrunk = age ** DCFR_BETA;\n\treturn {\n\t\tkeepPositive: grown / (grown + 1),\n\t\tkeepNegative: shrunk / (shrunk + 1),\n\t\tkeepSum: ((t - 1) / t) ** DCFR_GAMMA,\n\t};\n}\n\n/**\n * What a traversal plays and does. Train plays the current (regret-matched)\n * profile and updates the traverser's regrets and sums; Current plays that\n * same profile and updates nothing, for reading its values; Average plays the\n * average profile; BestResponse has the traverser best-respond to it.\n */\nexport const Mode = { Train: 0, BestResponse: 1, Average: 2, Current: 3 } 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 * Storage and strategy share a layout: `actions` rows of `count` hands.\n *\n * @param source regrets, for the current strategy\n */\nfunction normalise(\n\tsource: AnyRegrets | SumStore,\n\tbase: number,\n\tactions: 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 at = base + i;\n\t\tlet total = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst value = source[at + a * count];\n\t\t\tconst positive = value > 0 ? value : 0;\n\t\t\tstrategy[a * count + i] = 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 * count + i] /= total;\n\t\t} else {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * count + i] = uniform;\n\t\t}\n\t}\n}\n\n/**\n * How near, relative to the larger of the two, an action's value must be to\n * the hand's value at the node to count as tied with it: 2^-20, 8 to 16\n * float32 ulps of the larger. One tolerance for both engines, so they snap\n * alike; under `precision: 'f64'` it also drops real gaps that small, which\n * moves an answer by at most a millionth of the hand's value. Mirrored in\n * assembly/engine.ts. See `snapTies`.\n */\nexport const TIE_TOLERANCE = 2 ** -20;\n\n/**\n * Snap each action value that ties the hand's node value onto it, so the\n * regret it adds is exactly 0 (issue #117).\n *\n * Where a hand's actions are worth the same, its regrets are analytically\n * zero, but the node value is a strategy-weighted sum of the action values\n * and comes out an ulp or so off them, by a sign that depends on the order\n * of every sum beneath: thread count, engine, float width. Regret matching is\n * discontinuous at zero — one positive ulp plays that action purely, none\n * plays uniformly — so those ulps grew into percents of the strategy. A\n * difference within `TIE_TOLERANCE` of the values is rounding, not regret:\n * snapped, tied actions stay uniform whatever the summation order. Both\n * engines snap the same way, before any update reads the values.\n *\n * Laid out as `traverse` keeps them: `actionValues[a * count + i]`.\n */\nexport function snapTies(actionValues: Float64Array, out: Float64Array, actions: number, count: number): void {\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * count;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst v = actionValues[offset + i];\n\t\t\tconst value = out[i];\n\t\t\tconst gap = v < value ? value - v : v - value;\n\t\t\tconst size = v < 0 ? -v : v;\n\t\t\tconst valueSize = value < 0 ? -value : value;\n\t\t\tif (gap <= TIE_TOLERANCE * (size > valueSize ? size : valueSize)) actionValues[offset + i] = value;\n\t\t}\n\t}\n}\n\n/** Current strategy from positive regrets; uniform where there is none. */\nexport function regretMatch(regret: AnyRegrets, base: number, actions: number, count: number, strategy: Float64Array): void {\n\tnormalise(regret, base, actions, count, strategy);\n}\n\n/**\n * Average strategy from accumulated sums, which are never negative.\n *\n * A hand whose sum is zero here has no average to give: under CFR+, whose\n * sums follow the hand's own reach, it never reached this node on its own;\n * under DCFR, whose sums do not (issue #8), only a loaded strategy with gaps,\n * a warm start or 16-bit rounding leaves one. 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 | Uint8Array,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tstrategy: Float64Array,\n\tregret?: AnyRegrets,\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 at = base + i;\n\t\tlet total = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst value = strategySum[at + a * count];\n\t\t\tstrategy[a * count + i] = 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 * count + i] /= 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 * count];\n\t\t\t\tconst positive = value > 0 ? value : 0;\n\t\t\t\tstrategy[a * count + i] = 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 * count + i] /= total;\n\t\t} else {\n\t\t\tfor (let a = 0; a < actions; a++) strategy[a * count + i] = uniform;\n\t\t}\n\t}\n}\n\n/**\n * One walk of the subtree below `node`, for `traverser`, returning their\n * counterfactual values.\n *\n * Vectors are in hand space: `reachMe`, the result and every buffer for the\n * traverser hold one entry per hand of theirs live on `board` — entry `i` of\n * their active list there — and `reachOpp` likewise for the opponent. The\n * result is valid for the traverser's `count` hands on this board.\n */\nexport function 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\tdepth: number,\n): Float64Array {\n\tconst { tree, runouts } = ctx;\n\tconst out = buffers.value[depth];\n\tconst kind = tree.kind[node];\n\tconst round = tree.round[node];\n\tconst lists = ctx.active;\n\tconst opponent = (1 - traverser) as 0 | 1;\n\tconst mySlot = (lists.roundBase[round] + board) * 2 + traverser;\n\tconst oppSlot = (lists.roundBase[round] + board) * 2 + opponent;\n\tconst myFrom = lists.start[mySlot];\n\tconst myCount = lists.count[mySlot];\n\tconst oppFrom = lists.start[oppSlot];\n\tconst oppCount = lists.count[oppSlot];\n\n\tif (kind === NodeKind.TerminalFold) {\n\t\tconst signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];\n\t\tconst weight = ctx.runoutWeight[round] / ctx.chipScale;\n\t\tconst hands = ctx.hands;\n\t\tif (lists.packed[oppSlot]) {\n\t\t\tfoldValuesPacked(\n\t\t\t\treachOpp, lists.cardA, lists.cardB, lists.memberStart, lists.memberA, lists.memberB,\n\t\t\t\toppFrom, oppCount, myFrom, myCount, hands.same, hands.sameStart[mySlot], signed * weight, buffers.cardSums, out,\n\t\t\t);\n\t\t\treturn out;\n\t\t}\n\t\tfoldValuesHands(\n\t\t\treachOpp, lists.cardA, lists.cardB, oppFrom, oppCount, myFrom, myCount,\n\t\t\thands.same, hands.sameStart[mySlot], signed * weight, buffers.cardSums, out,\n\t\t);\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.TerminalShowdown) {\n\t\tconst weight = ctx.runoutWeight[round] / ctx.chipScale;\n\t\tif (lists.packed[oppSlot]) {\n\t\t\tshowdownValuesPacked(\n\t\t\t\treachOpp, lists.cardA, lists.cardB, lists.memberStart, lists.memberA, lists.memberB, lists.strength,\n\t\t\t\toppFrom, oppCount, myFrom, myCount, tree.payoff[node] * weight, buffers.cardSums, out,\n\t\t\t);\n\t\t\treturn out;\n\t\t}\n\t\tshowdownValuesHands(\n\t\t\treachOpp, lists.cardA, lists.cardB, lists.strength, oppFrom, oppCount, myFrom, myCount,\n\t\t\ttree.payoff[node] * weight, buffers.cardSums, out,\n\t\t);\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.Chance) {\n\t\tfor (let i = 0; i < myCount; i++) out[i] = 0;\n\t\tconst nextRound = round + 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 < myCount; i++) out[i] = ctx.chanceOverride[base + 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 orbitStart = runouts.orbitStart[nextRound];\n\t\tconst upStart = ctx.hands.upStart[nextRound];\n\t\tconst up = ctx.hands.up;\n\t\tconst childMe = buffers.reachFor[traverser][depth];\n\t\tconst childOpp = buffers.reachFor[opponent][depth];\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 starts = runouts.childStart[nextRound];\n\t\tconst first = starts[board];\n\t\tconst last = starts[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\t// Chance sampling decides how each deal's values are had; how they\n\t\t// spread over the deal's mirror images is the same either way.\n\t\tconst sampling = ctx.sampling ?? null;\n\t\tconst sampleHere =\n\t\t\tsampling !== null && mode === Mode.Train && ctx.applyUpdates && !ctx.expandOrbits && sampling.rounds[nextRound] === 1;\n\n\t\tfor (let childBoard = from; childBoard < to; childBoard++) {\n\t\t\tconst childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;\n\t\t\tconst childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;\n\t\t\tconst nMe = lists.count[childMySlot];\n\t\t\tconst nOpp = lists.count[childOppSlot];\n\t\t\tconst firstMember = orbitStart[childBoard];\n\t\t\tconst membersEnd = orbitStart[childBoard + 1];\n\n\t\t\t// Every real deal this board stands for, the stored one first. A\n\t\t\t// child hand's parent is `up`, through the deal's relabelling.\n\t\t\t// Without `expandOrbits`, reach is symmetric under the relabelling,\n\t\t\t// so one walk serves every member and only the values are spread.\n\t\t\tlet value: Float64Array | Float32Array | null = null;\n\t\t\tfor (let m = firstMember; m < membersEnd; m++) {\n\t\t\t\tconst upMe = upStart[m * 2 + traverser];\n\t\t\t\tif (sampleHere && value === null) {\n\t\t\t\t\tvalue = sampledValue(\n\t\t\t\t\t\tctx, sampling!, buffers, traverser, iterWeight, node, child, nextRound, childBoard,\n\t\t\t\t\t\treachMe, reachOpp, childMe, childOpp, depth,\n\t\t\t\t\t);\n\t\t\t\t} else if (value === null || ctx.expandOrbits) {\n\t\t\t\t\tconst upOpp = upStart[m * 2 + opponent];\n\t\t\t\t\tfor (let k = 0; k < nMe; k++) childMe[k] = reachMe[up[upMe + k]];\n\t\t\t\t\tfor (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp[up[upOpp + k]];\n\t\t\t\t\tvalue = traverse(ctx, buffers, mode, traverser, iterWeight, child, childBoard, childMe, childOpp, depth + 1);\n\t\t\t\t}\n\t\t\t\tif (lists.packed[childMySlot]) {\n\t\t\t\t\t// An entry stands for its whole orbit: weight it so, and\n\t\t\t\t\t// share the parent's total among its own orbit below.\n\t\t\t\t\tconst childFrom = lists.start[childMySlot];\n\t\t\t\t\tfor (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k] * lists.multiplicity[childFrom + k];\n\t\t\t\t} else {\n\t\t\t\t\tfor (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (lists.packed[mySlot]) {\n\t\t\tfor (let i = 0; i < myCount; i++) out[i] /= lists.multiplicity[myFrom + i];\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 isTraverser = owner === traverser;\n\n\t// The acting player's hands here: their active list on this board, which\n\t// is also how their storage block is laid out — `actions` rows of\n\t// `activeCount` hands from `slotBase`.\n\tconst listSlot = isTraverser ? mySlot : oppSlot;\n\tconst activeCount = lists.count[listSlot];\n\tconst stride = activeCount;\n\tconst slotBase = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];\n\n\t// Laid out as storage is: `strategy[a * stride + i]`.\n\tconst strategy = buffers.strategy[depth];\n\tconst length = actions * stride;\n\t// A compactly stored node without sums has no average: it plays the\n\t// current profile wherever a strategy is read.\n\tconst compactNode = round >= ctx.layout.compactFrom;\n\tconst chunk = compactNode ? ctx.layout.compactChunk![node] : 0;\n\tconst regrets: AnyRegrets = compactNode ? ctx.compactRegret![chunk] : ctx.regret;\n\tconst compactSums = compactNode && ctx.compact!.sums;\n\tconst current = mode === Mode.Train || mode === Mode.Current || (compactNode && !compactSums);\n\tif (current && buffers.kernels !== null) {\n\t\tconst kernels = buffers.kernels;\n\t\tkernels.input.set(regrets.subarray(slotBase, slotBase + length));\n\t\tkernels.regretMatch(strategy, actions, stride);\n\t} else if (current) {\n\t\tregretMatch(regrets, slotBase, actions, stride, strategy);\n\t} else if (compactSums) {\n\t\taverageStrategy(ctx.compactSum![chunk], slotBase, actions, stride, strategy, regrets);\n\t} else if (buffers.kernels !== null) {\n\t\tconst kernels = buffers.kernels;\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, strategy, ctx.regret);\n\t}\n\n\tif (isTraverser && mode === Mode.BestResponse) {\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, depth + 1,\n\t\t\t);\n\t\t\tif (a === 0) {\n\t\t\t\tfor (let i = 0; i < myCount; i++) out[i] = value[i];\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < myCount; i++) if (value[i] > out[i]) out[i] = value[i];\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tfor (let i = 0; i < myCount; i++) out[i] = 0;\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 row = a * stride;\n\t\tconst source = isTraverser ? reachMe : reachOpp;\n\t\tfor (let i = 0; i < activeCount; i++) childReach[i] = source[i] * strategy[row + i];\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\tdepth + 1,\n\t\t);\n\n\t\tif (isTraverser) {\n\t\t\tconst offset = a * myCount;\n\t\t\tfor (let i = 0; i < myCount; i++) {\n\t\t\t\tactionValues[offset + i] = value[i];\n\t\t\t\tout[i] += strategy[row + i] * value[i];\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 < myCount; i++) out[i] += value[i];\n\t\t}\n\t}\n\n\tif (isTraverser && mode === Mode.Train && ctx.applyUpdates) snapTies(actionValues, out, actions, myCount);\n\tconst weighted = ctx.layout.reachWeighted;\n\tif (weighted !== null && weighted[node] && isTraverser && mode === Mode.Train && ctx.applyUpdates) {\n\t\t// Each history's regret counts as often as this hand plays into it.\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst offset = a * myCount;\n\t\t\tfor (let i = 0; i < myCount; i++) {\n\t\t\t\tactionValues[offset + i] = out[i] + reachMe[i] * (actionValues[offset + i] - out[i]);\n\t\t\t}\n\t\t}\n\t}\n\tif (isTraverser && mode === Mode.Train && ctx.applyUpdates && compactNode) {\n\t\tupdateCompact(\n\t\t\tctx, node, chunk, ctx.layout.blockOffset[node] + board, slotBase,\n\t\t\tctx.layout.handOffset![node] + ctx.layout.rowStart[listSlot], actions, stride, iterWeight,\n\t\t\treachMe, strategy, actionValues, out,\n\t\t);\n\t} else if (isTraverser && mode === Mode.Train && ctx.applyUpdates && ctx.regretScale !== null) {\n\t\tupdateQuantised(\n\t\t\tctx, node, ctx.layout.blockOffset[node] + board, slotBase, actions, stride,\n\t\t\titerWeight, 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 { keepPositive, keepNegative, keepSum } = blockFactors(ctx, ctx.layout.blockOffset[node] + board, iterWeight);\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 * activeCount;\n\t\t\tconst slotRow = slotBase + a * stride;\n\t\t\tconst row = a * stride;\n\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\tconst at = slotRow + i;\n\t\t\t\tconst accumulated = regret[at];\n\t\t\t\tregret[at] = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[offset + i] - out[i];\n\t\t\t\tstrategySum[at] = strategySum[at] * keepSum + strategy[row + 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 * activeCount;\n\t\t\tconst slotRow = slotBase + a * stride;\n\t\t\tconst row = a * stride;\n\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\tconst at = slotRow + 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 + i] - out[i];\n\t\t\t\tregret[at] = updated > 0 ? updated : 0;\n\t\t\t\tstrategySum[at] += iterWeight * reachMe[i] * strategy[row + i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * One deal's values in a sampled chance node's training walk. A deal not\n * walked gives its baseline, the values it returned when last walked; a\n * walked deal gives `b + (v - b) / p` and its `v` becomes the new baseline\n * (with the 'latest' estimator, `v` itself). A deal never walked yet is\n * always walked. Returned in the child's hand space, as a walk's are.\n */\nfunction sampledValue(\n\tctx: Context,\n\ts: Sampling,\n\tbuffers: Buffers,\n\ttraverser: 0 | 1,\n\tt: number,\n\tnode: number,\n\tchild: number,\n\tnextRound: number,\n\tchildBoard: number,\n\treachMe: Float64Array,\n\treachOpp: Float64Array,\n\tchildMe: Float64Array,\n\tchildOpp: Float64Array,\n\tdepth: number,\n): Float64Array | Float32Array {\n\tconst lists = ctx.active;\n\tconst opponent = (1 - traverser) as 0 | 1;\n\tconst childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;\n\tconst nMe = lists.count[childMySlot];\n\tconst at = s.baseOffset[node] + s.boardOffset[childMySlot];\n\tconst walkAt = s.walkOffset[node] + childBoard * 2 + traverser;\n\tconst fresh = s.lastWalk[walkAt] === 0;\n\tif (!fresh && !sampled(s, node, childBoard, t)) return s.baseline.subarray(at, at + nMe);\n\n\tconst childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;\n\tconst nOpp = lists.count[childOppSlot];\n\tconst member = ctx.runouts.orbitStart[nextRound][childBoard];\n\tconst upStart = ctx.hands.upStart[nextRound];\n\tconst up = ctx.hands.up;\n\tconst upMe = upStart[member * 2 + traverser];\n\tconst upOpp = upStart[member * 2 + opponent];\n\tfor (let k = 0; k < nMe; k++) childMe[k] = reachMe[up[upMe + k]];\n\tfor (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp[up[upOpp + k]];\n\tconst value = traverse(ctx, buffers, Mode.Train, traverser, t, child, childBoard, childMe, childOpp, depth + 1);\n\t// The child's buffer is free again, so the estimate goes in place.\n\tconst weight = s.unbiased ? 1 / s.p : 1;\n\tconst baseline = s.baseline;\n\tfor (let k = 0; k < nMe; k++) {\n\t\tconst v = value[k];\n\t\tconst b = baseline[at + k];\n\t\tbaseline[at + k] = v;\n\t\t// `v + (w - 1)(v - b)` is `b + w(v - b)`, and exactly `v` at w = 1.\n\t\tif (!fresh) value[k] = v + (weight - 1) * (v - b);\n\t}\n\ts.lastWalk[walkAt] = t;\n\treturn value;\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. With\n * shared storage it is salted with the history's `node` (else 0): every\n * history that reaches a shared block re-encodes it in an iteration, and with\n * one stream for all of them their roundings would push the same way\n * (issue #94). The node is fixed by the tree, so the salt does not depend on\n * threads or on the order histories are visited in.\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\tnode: number,\n\tblock: number,\n\tslotBase: number,\n\tactions: number,\n\tcount: 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\t({ keepPositive, keepNegative, keepSum } = blockFactors(ctx, block, iterWeight));\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 * count;\n\t\tconst slotRow = slotBase + a * count;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst at = slotRow + 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 + i] - out[i];\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 + i] = updated;\n\n\t\t\t// DCFR adds the strategy unweighted by own reach (issue #8); CFR+ keeps the weight.\n\t\t\tconst added = clamp ? weight * reachMe[i] * strategy[a * count + i] : weight * strategy[a * count + i];\n\t\t\tconst sum = strategySum[at] * oldSum * keepSum + added;\n\t\t\tif (sum > largestSum) largestSum = sum;\n\t\t\tstrategy[a * count + 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\t// Which history is re-encoding a shared block; 0 keeps unshared streams as they were.\n\tconst salt = ctx.layout.shared ? node : 0;\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * count;\n\t\tconst slotRow = slotBase + a * count;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst at = slotRow + i;\n\t\t\tconst r = actionValues[offset + i] * regretStep;\n\t\t\tregret[at] = r < 0 ? r - 0.5 : r + 0.5;\n\t\t\tconst s = strategy[a * count + i] * sumStep + dither(at, iterWeight, salt);\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/** Bias of a compact hand's scale exponent; see `Context.handShift`. */\nconst SHIFT_BIAS = 160;\n/** `2^(shift - SHIFT_BIAS)` for every shift, 0 for a shift of 0. */\nexport const SHIFT_SCALE = Float64Array.from({ length: 256 }, (_, e) => (e === 0 ? 0 : 2 ** (e - SHIFT_BIAS)));\n\n/**\n * The update for a compactly stored node: decode, update in float as the rule\n * says, re-encode; with `sums`, the strategy sum too. Each hand is scaled by\n * its own power of two, chosen so its largest value uses the top of the\n * range; regret matching and the average only compare a hand's own values,\n * so a hand whose values are small beside the block's keeps all its\n * precision. Rounding is at random with odds set by the remainder (unless\n * `stochastic` is off), so each stored value is right on average; the\n * randomness is a hash of the slot's place in all of compact storage and the\n * iteration, so it does not depend on threads or chunks. With shared storage\n * the history's `node` goes into the hash too: every history reaching a\n * shared block re-encodes it, and the same random numbers each time would\n * push its rounding errors the same way instead of letting them cancel\n * (issue #88).\n */\nexport function updateCompact(\n\tctx: Context,\n\tnode: number,\n\tchunk: number,\n\tblock: number,\n\tslotBase: number,\n\thandBase: number,\n\tactions: number,\n\tcount: number,\n\titerWeight: number,\n\treachMe: Float64Array,\n\tstrategy: Float64Array,\n\tactionValues: Float64Array,\n\tout: Float64Array,\n): void {\n\tconst plan = ctx.compact!;\n\tconst q = ctx.compactRegret![chunk];\n\t// Rounding hashes the slot's place in all of compact storage, so how it\n\t// is chunked changes nothing.\n\tconst hashBase = ctx.layout.chunkStart[chunk] + slotBase;\n\t// Which history is re-encoding a shared block; 0 keeps unshared streams as they were.\n\tconst salt = ctx.layout.shared ? node : 0;\n\tconst steps = plan.steps;\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\t({ keepPositive, keepNegative, keepSum } = blockFactors(ctx, block, iterWeight));\n\t\tweight = 1;\n\t}\n\n\tif (plan.float) {\n\t\tfor (let k = 0; k < actions * count; k++) {\n\t\t\tconst accumulated = q[slotBase + k];\n\t\t\tconst updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[k % count];\n\t\t\tq[slotBase + k] = clamp && updated < 0 ? 0 : updated;\n\t\t}\n\t\treturn;\n\t}\n\n\tif (!plan.perHand) {\n\t\t// One scale for the block, as 16-bit storage keeps.\n\t\tconst scales = ctx.compactScale!;\n\t\tconst old = scales[block];\n\t\tlet largest = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst row = a * count;\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\tconst accumulated = q[slotBase + row + i] * old;\n\t\t\t\tlet updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[row + i] - out[i];\n\t\t\t\tif (clamp && updated < 0) updated = 0;\n\t\t\t\tactionValues[row + i] = updated;\n\t\t\t\tconst magnitude = updated < 0 ? -updated : updated;\n\t\t\t\tif (magnitude > largest) largest = magnitude;\n\t\t\t}\n\t\t}\n\t\tconst step = largest > 0 ? steps / largest : 0;\n\t\tconst stochastic = plan.stochastic;\n\t\t// One hash per row, stepped on for each hand.\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst row = a * count;\n\t\t\tlet h = stochastic ? streamSeed(hashBase + row, iterWeight, salt) : 0;\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\tconst value = actionValues[row + i] * step;\n\t\t\t\tlet rounded: number;\n\t\t\t\tif (stochastic) {\n\t\t\t\t\th = nextState(h);\n\t\t\t\t\trounded = Math.floor(value + (h >>> 0) / 4294967296);\n\t\t\t\t} else {\n\t\t\t\t\trounded = Math.round(value);\n\t\t\t\t}\n\t\t\t\tq[slotBase + row + i] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;\n\t\t\t}\n\t\t}\n\t\tscales[block] = largest / steps;\n\t\treturn;\n\t}\n\n\tconst shifts = ctx.handShift![chunk];\n\tconst stochastic = plan.stochastic;\n\tconst sums = plan.sums ? ctx.compactSum![chunk] : null;\n\tconst sumShifts = plan.sums ? ctx.sumShift![chunk] : null;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst scale = SHIFT_SCALE[shifts[handBase + i]];\n\t\tlet largest = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\tconst accumulated = q[slotBase + k] * scale;\n\t\t\tlet updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[i];\n\t\t\tif (clamp && updated < 0) updated = 0;\n\t\t\tactionValues[k] = updated;\n\t\t\tconst magnitude = updated < 0 ? -updated : updated;\n\t\t\tif (magnitude > largest) largest = magnitude;\n\t\t}\n\t\tconst exponent = scaleExponent(largest, steps);\n\t\tshifts[handBase + i] = exponent;\n\t\tconst inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];\n\t\t// One hash per hand, stepped on for each action.\n\t\tlet h = stochastic || sums !== null ? streamSeed(hashBase + i, iterWeight, salt) : 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\tconst value = actionValues[k] * inverse;\n\t\t\tlet rounded: number;\n\t\t\tif (stochastic) {\n\t\t\t\th = nextState(h);\n\t\t\t\trounded = Math.floor(value + (h >>> 0) / 4294967296);\n\t\t\t} else {\n\t\t\t\trounded = Math.round(value);\n\t\t\t}\n\t\t\tq[slotBase + k] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;\n\t\t}\n\n\t\tif (sums === null) continue;\n\t\t// The strategy sum, as 16-bit storage keeps it but scaled per hand:\n\t\t// the average divides each hand's sums by their own total, so the\n\t\t// scale cancels there just as it does for regret matching.\n\t\tconst sumScale = SHIFT_SCALE[sumShifts![handBase + i]];\n\t\tlet largestSum = 0;\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\t// DCFR adds the strategy unweighted by own reach (issue #8); CFR+ keeps the weight.\n\t\t\tconst added = clamp ? weight * reachMe[i] * strategy[k] : weight * strategy[k];\n\t\t\tconst sum = sums[slotBase + k] * sumScale * keepSum + added;\n\t\t\tstrategy[k] = sum;\n\t\t\tif (sum > largestSum) largestSum = sum;\n\t\t}\n\t\tconst sumExponent = scaleExponent(largestSum, COMPACT_SUM_STEPS);\n\t\tsumShifts![handBase + i] = sumExponent;\n\t\tconst sumInverse = sumExponent === 0 ? 0 : 1 / SHIFT_SCALE[sumExponent];\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst k = a * count + i;\n\t\t\th = nextState(h);\n\t\t\tconst rounded = Math.floor(strategy[k] * sumInverse + (h >>> 0) / 4294967296);\n\t\t\tsums[slotBase + k] = rounded < COMPACT_SUM_STEPS ? rounded : COMPACT_SUM_STEPS;\n\t\t}\n\t}\n}\n\n/** Largest strategy sum compact storage keeps per hand: the top of a byte. */\nexport const COMPACT_SUM_STEPS = 255;\n\n/**\n * A hand's scale exponent: the smallest power of two that brings `largest`\n * within `steps`, read off the float's exponent bits, biased by\n * `SHIFT_BIAS`; 0, for all zeros, below the smallest scale there is.\n */\nexport function scaleExponent(largest: number, steps: number): number {\n\tif (!(largest > 0)) return 0;\n\tEXPONENT_FLOAT[0] = largest / steps;\n\tconst high = EXPONENT_BITS[1];\n\tlet exponent = ((high >>> 20) & 0x7ff) - 1023 + SHIFT_BIAS;\n\tif ((high & 0xfffff) !== 0 || EXPONENT_BITS[0] !== 0) exponent++;\n\treturn exponent < 1 ? 0 : exponent > 255 ? 255 : exponent;\n}\n\n/**\n * Start of a slot's random stream on an iteration, for rounding a run of\n * values with `nextState`; `salt` tells apart histories sharing the slot\n * (0 when none do). Never zero, the stream's fixed point.\n */\nfunction streamSeed(slot: number, iteration: number, salt: number): number {\n\treturn Math.imul(slot ^ Math.imul(iteration, 0x9e3779b1) ^ Math.imul(salt, 0x7feb352d) ^ 0x5bd1e995, 0x85ebca6b) | 1;\n}\n\n/** One step of a random stream: the next state, whose `(h >>> 0) / 2^32` is uniform in [0, 1). */\nfunction nextState(h: number): number {\n\th ^= h >>> 15;\n\th = Math.imul(h, 0x2c1b3c6d);\n\treturn h ^ (h >>> 12);\n}\n\n/** Scratch for reading a float's exponent bits (little-endian: the high word second). */\nconst EXPONENT_FLOAT = new Float64Array(1);\nconst EXPONENT_BITS = new Uint32Array(EXPONENT_FLOAT.buffer);\n\n/**\n * The strategy a block's storage stands for, outside training: the average,\n * or the current profile where compact storage keeps no average.\n */\nexport function storedStrategy(\n\tctx: Context,\n\tnode: number,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tstrategy: Float64Array,\n): void {\n\tif (ctx.tree.round[node] >= ctx.layout.compactFrom && ctx.compact!.sums) {\n\t\tconst chunk = ctx.layout.compactChunk![node];\n\t\taverageStrategy(ctx.compactSum![chunk], base, actions, count, strategy, ctx.compactRegret![chunk]);\n\t} else if (ctx.tree.round[node] >= ctx.layout.compactFrom) {\n\t\tregretMatch(ctx.compactRegret![ctx.layout.compactChunk![node]], base, actions, count, strategy);\n\t} else {\n\t\taverageStrategy(ctx.strategySum, base, actions, count, strategy, ctx.regret);\n\t}\n}\n\n/**\n * A deterministic uniform value in [0, 1) for a slot on an iteration, from\n * the stream `salt` picks; salt 0 is the stream unshared storage has always\n * used. Distinct salts give a slot distinct hash inputs on every iteration.\n */\nexport function dither(slot: number, iteration: number, salt = 0): number {\n\tlet h = Math.imul(slot ^ Math.imul(iteration, 0x9e3779b1) ^ Math.imul(salt, 0x27d4eb2f), 0x85ebca6b);\n\th ^= h >>> 13;\n\th = Math.imul(h, 0xc2b2ae35);\n\th ^= h >>> 16;\n\treturn (h >>> 0) / 4294967296;\n}\n\n/** See `Solver.rootValues`. */\nexport interface RootValues {\n\treadonly totals: readonly [number, number];\n\treadonly values: readonly [Float64Array, Float64Array];\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\t/**\n\t * One root pass per player under the average profile (`Mode.Average`) or\n\t * the current one (`Mode.Current`): each player's chips per hand, as\n\t * `expectedValue` gives them for the average, and a copy of their root\n\t * counterfactual values, one per hand of their root active list. In chips\n\t * against a baseline where each player owns half the pot, unlike\n\t * `Solution.ev`'s share of the pot.\n\t */\n\trootValues(mode: typeof Mode.Average | typeof Mode.Current): RootValues;\n\t/**\n\t * Root EV in chips for each combination, indexed like `COMBO_CARDS`, from\n\t * root counterfactual values `rootValues` returned for `player`: each\n\t * hand's value over the opponent mass it can be dealt against. Zero for a\n\t * combination off the root list or with no opponent hand to face. Chips\n\t * are on the traversal's baseline, each player owning half the pot;\n\t * `unit` converts each hand that has an EV (as `Solution.handEvs` does to\n\t * a share of the pot), and the zeros stay zero.\n\t */\n\thandEvs(player: 0 | 1, values: Float64Array, unit?: (chips: number) => number): Float64Array;\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. In chips,\n\t * against a baseline where each player owns half the pot (folding is\n\t * −pot/2), as the traversal and its regrets are; not `Solution.ev`'s\n\t * share of the pot.\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 * The whole-tree traversal `iterate` and the other passes run now: this\n\t * thread's own, or what `useRoot` routed them to. For wrapping it.\n\t */\n\treadonly root: RootTraversal;\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. In\n\t * chips on `valuesAt`'s half-pot baseline.\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\t// Hand-space vectors for a round and board, from combination-indexed\n\t// arrays, and back.\n\tconst lists = ctx.active;\n\tconst listOf = (round: number, board: number, player: 0 | 1): [number, number] => {\n\t\tconst slot = (lists.roundBase[round] + board) * 2 + player;\n\t\treturn [lists.start[slot], lists.count[slot]];\n\t};\n\tconst gather = (source: Float64Array, round: number, board: number, player: 0 | 1, into: Float64Array): void => {\n\t\tconst [from, count] = listOf(round, board, player);\n\t\tfor (let i = 0; i < count; i++) into[i] = source[lists.list[from + i]];\n\t};\n\n\tconst run = (mode: Mode, traverser: 0 | 1, iterWeight: number): Float64Array => {\n\t\tgather(ctx.players[0].weights, 0, 0, 0, reach0);\n\t\tgather(ctx.players[1].weights, 0, 0, 1, reach1);\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, 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\tconst [from, count] = listOf(0, 0, traverser);\n\t\tlet sum = 0;\n\t\tfor (let i = 0; i < count; i++) sum += weights[lists.list[from + i]] * lists.multiplicity[from + i] * values[i];\n\t\t// The mass as the ranges stand, not as they stood when the run was\n\t\t// made: `SolveRun.setRange` reweights them, for every run on the spot.\n\t\treturn sum / (matchupMass(ctx.players[0].weights, ctx.players[1].weights) * ctx.runoutWeight[0]);\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\tget root() {\n\t\t\treturn root;\n\t\t},\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\t// Hand-space vectors for the chance node's own board, which at the\n\t\t\t// shard boundary is always board 0 of its round.\n\t\t\treturn traverse(ctx, buffers, mode, traverser, iterWeight, node, 0, me, opp, 0);\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\trootValues(mode) {\n\t\t\tif (mode === Mode.Current && ctx.regret.length === 0 && !ctx.compactRegret) {\n\t\t\t\tthrow new Error('The current profile needs regrets, and an analysis-only run has none');\n\t\t\t}\n\t\t\t// Each root vector is a buffer the next traversal reuses, so it is\n\t\t\t// read and copied before the other player's pass.\n\t\t\tconst one = (player: 0 | 1): [number, Float64Array] => {\n\t\t\t\tconst values = root(mode, player, 0);\n\t\t\t\treturn [total(values, player), values.slice(0, listOf(0, 0, player)[1])];\n\t\t\t};\n\t\t\tconst [total0, values0] = one(0);\n\t\t\tconst [total1, values1] = one(1);\n\t\t\treturn { totals: [total0, total1], values: [values0, values1] };\n\t\t},\n\t\thandEvs(player, values, unit = (chips) => chips) {\n\t\t\tconst opponent = ctx.players[1 - player];\n\t\t\tconst evs = new Float64Array(COMBOS);\n\t\t\tconst [from, count] = listOf(0, 0, player);\n\t\t\tif (values.length !== count) {\n\t\t\t\tthrow new Error(`Player ${player} has ${count} root hands, but ${values.length} values were given`);\n\t\t\t}\n\t\t\tconst scale = ctx.runoutWeight[0];\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t// A packed entry's value is each of its mirrored hands' own.\n\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\t\t\tconst combo = lists.memberCombo[m];\n\t\t\t\t\tconst a = COMBO_CARDS[combo * 2];\n\t\t\t\t\tconst b = COMBO_CARDS[combo * 2 + 1];\n\t\t\t\t\t// Summed directly rather than by inclusion-exclusion over\n\t\t\t\t\t// cards, so a hand with nothing to face gets exactly zero\n\t\t\t\t\t// mass, not a rounding residue to divide by. Board-blocked\n\t\t\t\t\t// opponent hands already weigh zero.\n\t\t\t\t\tlet mass = 0;\n\t\t\t\t\tfor (let j = 0; j < opponent.count; j++) {\n\t\t\t\t\t\tconst other = opponent.combos[j];\n\t\t\t\t\t\tconst c = COMBO_CARDS[other * 2];\n\t\t\t\t\t\tconst d = COMBO_CARDS[other * 2 + 1];\n\t\t\t\t\t\tif (c !== a && c !== b && d !== a && d !== b) mass += opponent.weights[other];\n\t\t\t\t\t}\n\t\t\t\t\tevs[combo] = mass > 0 ? unit(values[i] / (mass * scale)) : 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn evs;\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\tvoid live;\n\t\t\tvoid liveCount;\n\t\t\tconst round = ctx.tree.round[node];\n\t\t\tconst opponent = (1 - traverser) as 0 | 1;\n\t\t\t// Values depend on the opponent's reach alone. A packed list can\n\t\t\t// carry it only when mirrored hands hold equally much, as they do\n\t\t\t// for any reach the solve itself produces.\n\t\t\tconst [oppFrom, oppCount] = listOf(round, board, opponent);\n\t\t\tlet symmetric = true;\n\t\t\tfor (let j = 0; j < oppCount && symmetric; j++) {\n\t\t\t\tconst own = reachOpp[lists.list[oppFrom + j]];\n\t\t\t\tfor (let m = lists.memberStart[oppFrom + j] + 1; m < lists.memberStart[oppFrom + j + 1]; m++) {\n\t\t\t\t\tif (reachOpp[lists.memberCombo[m]] !== own) symmetric = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst members = (player: 0 | 1): Uint16Array => {\n\t\t\t\tconst [from, count] = listOf(round, board, player);\n\t\t\t\treturn lists.memberCombo.slice(lists.memberStart[from], lists.memberStart[from + count]);\n\t\t\t};\n\t\t\tif (!symmetric) {\n\t\t\t\t// Values are linear in the opponent's reach, so they are the\n\t\t\t\t// sum of the values against each opposing hand alone, which\n\t\t\t\t// are walked with every hand apart. Slower, by about the\n\t\t\t\t// number of opposing hands over 64.\n\t\t\t\tconst theirs = members(opponent).filter((combo) => reachOpp[combo] !== 0);\n\t\t\t\tconst mine = members(traverser);\n\t\t\t\tconst handReach = Float64Array.from(theirs, (combo) => reachOpp[combo]);\n\t\t\t\tconst rows = pairValues(ctx, node, board, traverser, theirs, handReach, mine, mine.length);\n\t\t\t\tconst result = new Float64Array(COMBOS);\n\t\t\t\tfor (let k = 0; k < theirs.length; k++) {\n\t\t\t\t\tfor (const combo of mine) result[combo] += rows[k * COMBOS + combo];\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\t// Mirrored deals below need not see symmetric reach, so they 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 me = new Float64Array(COMBOS);\n\t\t\t\tconst opp = new Float64Array(COMBOS);\n\t\t\t\tgather(reachMe, round, board, traverser, me);\n\t\t\t\tgather(reachOpp, round, board, opponent, opp);\n\t\t\t\tconst value = traverse(ctx, buffers, Mode.Average, traverser, 0, node, board, me, opp, 0);\n\t\t\t\tconst result = new Float64Array(COMBOS);\n\t\t\t\tconst [from, count] = listOf(round, board, traverser);\n\t\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\t\t\t\tresult[lists.memberCombo[m]] = value[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\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\t// In range order, as callers read it: hands the board blocks play\n\t\t\t// uniformly, as they always have.\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 slot = (lists.roundBase[ctx.tree.round[node]] + board) * 2 + owner;\n\t\t\tconst from = lists.start[slot];\n\t\t\tconst count = lists.count[slot];\n\t\t\tconst base = ctx.layout.offset[node] + actions * ctx.layout.rowStart[slot];\n\t\t\tconst strategy = new Float64Array(actions * count);\n\t\t\tstoredStrategy(ctx, node, base, actions, count, strategy);\n\t\t\tconst probs = new Float64Array(index.count * actions).fill(1 / actions);\n\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t// A packed entry's strategy is its whole orbit's.\n\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {\n\t\t\t\t\tconst at = index.slot[lists.memberCombo[m]];\n\t\t\t\t\tfor (let a = 0; a < actions; a++) probs[at * actions + a] = strategy[a * count + i];\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","// Generated by scripts/build-wasm.ts from assembly/engine.ts. Do not edit.\n/** The traversal engine, 7342 bytes of WebAssembly. */\nexport const ENGINE_WASM = 'AGFzbQEAAAABcAtgBH9/f38AYAd/f39/f3x/AGADf39/AGACf38AYAF/AGAGf39/f39/AX9gCH9/f39/f39/AGAMf3x/f39/f39/f39/AGAMf39/f39/f39/f39/AX9gCn9/f39/fX19fX8Bf2AJf39/f319fX1/AX8CDwEDZW52Bm1lbW9yeQIAAAMREAUGAAEBAgIHAwQDAAgJCgQGmwNIfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfAFEAAAAAAAA8D8LfwFBfwt/AUEAC38BQQALfwFBAAt/AUEBC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt8AUQAAAAAAADwPwt/AUEAC30BQwAAgD8LfwFBAQt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfAFEAAAAAAAA8D8LfAFEAAAAAAAAAAALfAFEAAAAAAAA8D8LfwFBAAt9AUMAAIA/C30BQwAAAAALfQFDAACAPwt9AUMAA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gCMCQMIAAoAjQkDSAAKAI4JA4gACgCPCQPIABBQGsoAgAkECAAKAJEJBEgACgCSCQSIAAoAkwkEyAAKAJQJBQgACgCVCQVIAAoAlgkFiAAKAJcJBcgACgCYCQYIAAoAmQkGSAAKAJoJBogACgCbCQbIAAoAnAkHCAAKAJ0JB0gACgCeCQeIAAoAnwkHyAAKAKAASQgIAAoAoQBJCEgACgCiAEkIiAAKAKMASQjIAAoApABuCQkCw==';\n","// Generated by scripts/build-wasm.ts from assembly/engine.ts. Do not edit.\n/** The traversal engine over shared memory, 7345 bytes of WebAssembly. */\nexport const ENGINE_SHARED_WASM = 'AGFzbQEAAAABcAtgBH9/f38AYAd/f39/f3x/AGADf39/AGACf38AYAF/AGAGf39/f39/AX9gCH9/f39/f39/AGAMf3x/f39/f39/f39/AGAMf39/f39/f39/f39/AX9gCn9/f39/fX19fX8Bf2AJf39/f319fX1/AX8CEgEDZW52Bm1lbW9yeQIDAICABAMREAUGAAEBAgIHAwQDAAgJCgQGmwNIfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfAFEAAAAAAAA8D8LfwFBfwt/AUEAC38BQQALfwFBAAt/AUEBC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt8AUQAAAAAAADwPwt/AUEAC30BQwAAgD8LfwFBAQt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfAFEAAAAAAAA8D8LfAFEAAAAAAAAAAALfAFEAAAAAAAA8D8LfwFBAAt9AUMAAIA/C30BQwAAAAALfQFDAACAPwt9AUMAAIA/C38BQQALfwFBAQsHgAEL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I4JA4gACgCPCQPIABBQGsoAgAkECAAKAJEJBEgACgCSCQSIAAoAkwkEyAAKAJQJBQgACgCVCQVIAAoAlgkFiAAKAJcJBcgACgCYCQYIAAoAmQkGSAAKAJoJBogACgCbCQbIAAoAnAkHCAAKAJ0JB0gACgCeCQeIAAoAnwkHyAAKAKAASQgIAAoAoQBJCEgACgCiAEkIiAAKAKMASQjIAAoApABuCQkCw==';\n","/**\n * The browser build's engine threads: started ahead of time, borrowed by solves.\n *\n * Purpose: everything behind `enableThreads` (`poker-flopsolve/threads`), kept\n * out of `platform/browser.ts` so the main browser build carries none of it.\n * See that file for why the threads must be started before a solve.\n */\n\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { ENGINE_CONTROL } from '../engine.ts';\nimport { serveEngine } from '../engine-thread.ts';\n\n/** A spawned solver thread. */\ninterface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The parts of the Web Worker API used here, typed locally: the project builds without DOM typings. */\ninterface WebWorker {\n\tpostMessage(message: unknown, transfer?: unknown[]): void;\n\tterminate(): void;\n\tonmessage: ((event: { data: unknown }) => void) | null;\n\tonerror: ((event: { message?: string; preventDefault?(): void }) => void) | null;\n}\n\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n}\n\ninterface BrowserGlobals {\n\tWorker?: new (url: string) => WebWorker;\n\tMessageChannel?: new () => { port1: MessagePortLike; port2: unknown };\n\tBlob?: new (parts: string[], options: { type: string }) => object;\n\tURL: { createObjectURL(blob: object): string; revokeObjectURL(url: string): void };\n\tcrossOriginIsolated?: boolean;\n\tnavigator?: { hardwareConcurrency?: number };\n\tWebAssembly?: { Memory: new (descriptor: { initial: number; maximum: number; shared: boolean }) => object };\n}\n\n/** One pre-started engine thread. */\ninterface Thread {\n\treadonly worker: WebWorker;\n\t/**\n\t * Where its solves are posted. A message posted on the Worker object\n\t * itself does not reach a running child while the parent is blocked in\n\t * `Atomics.wait` (Chromium), and a solve blocks right after posting; a\n\t * transferred MessagePort delivers regardless.\n\t */\n\treadonly port: MessagePortLike;\n\tbusy: boolean;\n}\n\n/** Where the pool is published on `globalThis`. */\nexport const THREADS_KEY = Symbol.for('poker-flopsolve.browser-threads');\n\n/** What the main build sees of the pool. */\nexport interface ThreadProvider {\n\tidle(): number;\n\ttotal(): number;\n\tspawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle;\n}\n\ntype Holder = Record<symbol, (ThreadProvider & { threads: Thread[] }) | undefined>;\n\n/** The engine threads started so far, shared by every copy of this module. */\nfunction pool(): Thread[] {\n\tconst holder = globalThis as unknown as Holder;\n\tholder[THREADS_KEY] ??= {\n\t\tthreads: [],\n\t\tidle: () => idleThreads(),\n\t\ttotal: () => pool().length,\n\t\tspawn: (setup, onError) => spawn(setup, onError),\n\t};\n\treturn holder[THREADS_KEY]!.threads;\n}\n\nfunction idleThreads(): number {\n\treturn pool().filter((thread) => !thread.busy).length;\n}\n\n/** Stop a thread for good and forget it. */\nfunction drop(thread: Thread): void {\n\tthread.worker.terminate();\n\tthread.busy = true;\n\tconst threads = pool();\n\tconst at = threads.indexOf(thread);\n\tif (at >= 0) threads.splice(at, 1);\n}\n\n/** `ENGINE_CONTROL.command`'s value that ends a thread's solve. */\nconst COMMAND_EXIT = 1;\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nfunction spawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst thread = pool().find((candidate) => !candidate.busy);\n\tif (!thread) throw new Error('No idle engine thread; call enableThreads() from poker-flopsolve/threads first');\n\tthread.busy = true;\n\tthread.worker.onerror = (event) => {\n\t\tevent.preventDefault?.();\n\t\tdrop(thread);\n\t\tonError(new Error(`Engine thread failed: ${event.message ?? 'unknown error'}`));\n\t};\n\tthread.port.postMessage(setup);\n\tconst control = new Int32Array(setup.control);\n\tlet released = false;\n\treturn {\n\t\tterminate() {\n\t\t\t// A run may be closed twice; by then the thread may serve another.\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tif (!pool().includes(thread)) return;\n\t\t\t// A solve a thread failed: its error event is still queued, and\n\t\t\t// would fail whichever solve borrowed the thread next. Which thread\n\t\t\t// failed is not recorded, so every one of that solve's goes;\n\t\t\t// `prepareThreads` starts replacements.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.failed) !== 0) {\n\t\t\t\tdrop(thread);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Whether this solve finished or gave up on starting, tell the\n\t\t\t// thread its solve is over: it returns to waiting for the next\n\t\t\t// setup, having started this one or not (serveEngine checks for\n\t\t\t// exit before it first waits). A thread that died is dropped by\n\t\t\t// its error handler instead.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.command) !== COMMAND_EXIT) {\n\t\t\t\tAtomics.store(control, ENGINE_CONTROL.command, COMMAND_EXIT);\n\t\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\t}\n\t\t\tthread.busy = false;\n\t\t\tthread.worker.onerror = () => drop(thread);\n\t\t},\n\t};\n}\n\n/** Why threads cannot run here, or null if they can. */\nexport function threadsUnavailableReason(): string | null {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tif (typeof g.Worker !== 'function' || typeof g.Blob !== 'function' || typeof g.MessageChannel !== 'function') {\n\t\treturn 'no Web Workers here';\n\t}\n\tif (g.crossOriginIsolated !== true) {\n\t\treturn 'the page is not cross-origin isolated (serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp)';\n\t}\n\tif (typeof SharedArrayBuffer !== 'function') return 'no SharedArrayBuffer here';\n\ttry {\n\t\t// Throws where blocking is not allowed: a page's main thread.\n\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);\n\t} catch {\n\t\treturn 'Atomics.wait is not allowed on this thread; solve inside a Web Worker';\n\t}\n\ttry {\n\t\tnew g.WebAssembly!.Memory({ initial: 1, maximum: 1, shared: true });\n\t} catch {\n\t\treturn 'no shared WebAssembly memory here';\n\t}\n\treturn null;\n}\n\n/** How long a thread may take to start before it is given up on. */\nconst START_MS = 30_000;\n\nfunction startThread(url: string): Promise<Thread | null> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\treturn new Promise((resolve) => {\n\t\tlet worker: WebWorker;\n\t\ttry {\n\t\t\tworker = new g.Worker!(url);\n\t\t} catch {\n\t\t\tresolve(null);\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t}, START_MS);\n\t\tconst channel = new g.MessageChannel!();\n\t\tworker.onmessage = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tworker.onmessage = null;\n\t\t\tworker.onerror = null;\n\t\t\tresolve({ worker, port: channel.port1, busy: false });\n\t\t};\n\t\tworker.postMessage(null, [channel.port2]);\n\t\tworker.onerror = (event) => {\n\t\t\tevent.preventDefault?.();\n\t\t\tclearTimeout(timer);\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t};\n\t});\n}\n\n/**\n * Start engine threads so that solves can use up to `count` threads, this one\n * included, and resolve to how many a solve can use now. Threads already\n * started are kept; idle ones beyond `count` are stopped, so `prepareThreads(1)`\n * stops every thread no open run is holding. Resolves to 1 where threads cannot run; see\n * {@link threadsUnavailableReason}.\n * @param count threads wanted, this one included; defaults to `navigator.hardwareConcurrency`\n */\nexport function prepareThreads(count?: number): Promise<number> {\n\t// One call at a time, so two calls in a row cannot both start the missing threads.\n\tconst next = pending.then(() => resize(count));\n\tpending = next.catch(() => undefined);\n\treturn next;\n}\n\nlet pending: Promise<unknown> = Promise.resolve();\n\nasync function resize(count?: number): Promise<number> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tconst wanted = Math.max(1, Math.floor(count ?? g.navigator?.hardwareConcurrency ?? 1));\n\tconst threads = pool();\n\tfor (let i = threads.length - 1; i >= 0 && threads.length > wanted - 1; i--) {\n\t\tif (!threads[i].busy) drop(threads[i]);\n\t}\n\tconst missing = wanted - 1 - threads.length;\n\tif (missing > 0 && threadsUnavailableReason() === null) {\n\t\t// The worker is this module's own loop, as source: there is no file\n\t\t// to point a worker at that every bundler would ship.\n\t\tconst source =\n\t\t\t`const serveEngine = ${serveEngine.toString()};\\n` +\n\t\t\t'onmessage = (event) => {\\n' +\n\t\t\t'\\tevent.ports[0].onmessage = (solve) => serveEngine(solve.data);\\n' +\n\t\t\t\"\\tpostMessage('ready');\\n\" +\n\t\t\t'};\\n';\n\t\tconst url = g.URL.createObjectURL(new g.Blob!([source], { type: 'text/javascript' }));\n\t\ttry {\n\t\t\tconst started = await Promise.all(Array.from({ length: missing }, () => startThread(url)));\n\t\t\tfor (const thread of started) if (thread) threads.push(thread);\n\t\t} finally {\n\t\t\tg.URL.revokeObjectURL(url);\n\t\t}\n\t}\n\treturn threadsUnavailableReason() === null ? Math.min(wanted, 1 + idleThreads()) : 1;\n}\n","/**\n * Browser platform.\n *\n * Purpose: stand in for `node.ts` in a browser build, with the same exports.\n *\n * Out of the box the browser build is single-threaded: no worker threads, no\n * SharedArrayBuffer, and so no cross-origin isolation headers needed on the\n * page. Run the solve inside a Web Worker to keep the page responsive; see\n * `examples/browser-worker.ts`.\n *\n * Threads are opt-in, through `enableThreads` in `poker-flopsolve/threads`\n * (`prepareThreads` here). A browser starts a Web Worker only asynchronously —\n * a worker spawned and then waited on with `Atomics.wait` never starts, as\n * the thread that would start it is the one blocked — while a solve is\n * synchronous. So the workers are started ahead of time, once, and wait idle\n * between solves; a solve with `workers: n` hands n − 1 of them its setup and\n * takes them back on `close()`. Only the WebAssembly engine is threaded here:\n * its workers share the engine's memory exactly as Node's do and run the same\n * loop (`serveEngine`), so a fixed thread count gives the same answer as Node\n * at that count.\n *\n * The pool lives in `browser-threads.ts` and is found through `globalThis`\n * under a registered symbol, so the threads entry and the main build share\n * it even when bundled separately, and the main build carries none of it.\n */\n\nimport type { WorkerSetup } from '../parallel.ts';\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { compiledEngine } from '../engine.ts';\nimport type { ThreadProvider } from './browser-threads.ts';\nimport { THREADS_KEY } from './browser-threads.ts';\n\nexport { prepareThreads, threadsUnavailableReason } from './browser-threads.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'browser';\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/** The engine threads `prepareThreads` started, if any. */\nfunction provider(): ThreadProvider | undefined {\n\treturn (globalThis as unknown as Record<symbol, ThreadProvider | undefined>)[THREADS_KEY];\n}\n\n/**\n * The most threads a solve can use now: one, plus the idle engine threads\n * when the WebAssembly engine is to run and can run over shared memory here.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadLimit(engine: boolean): number {\n\tconst threads = provider();\n\tif (!engine || !threads || threads.idle() === 0) return 1;\n\treturn compiledEngine('shared') ? 1 + threads.idle() : 1;\n}\n\n/** One, plus every idle engine thread `prepareThreads` started. */\nexport function defaultWorkerCount(): number {\n\treturn 1 + (provider()?.idle() ?? 0);\n}\n\n/**\n * Why a solve gets fewer threads than it asked for, for the one warning.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadAdvice(engine: boolean): string {\n\tif (!provider()) return 'call enableThreads() from poker-flopsolve/threads first, in a cross-origin isolated Web Worker';\n\tif (!engine) return 'browser threads run only the WebAssembly engine (default engine, f32 precision)';\n\treturn 'the other threads are held by open runs; close() a run to free its threads';\n}\n\n/** Never called: the browser build threads only the WebAssembly engine; see `threadLimit`. */\nexport function spawnWorker(_setup: WorkerSetup, _onError: (error: Error) => void): WorkerHandle {\n\tthrow new Error('The browser build threads only the WebAssembly engine; use workers: 1 with this solve');\n}\n\n/**\n * Nothing to do in a browser, whose engine threads `prepareThreads` started\n * and keeps; Node starts a run's threads here, ahead of its need for them.\n * @param _count idle engine threads wanted\n */\nexport function warmEngineThreads(_count: number): void {}\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nexport function spawnEngineWorker(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst threads = provider();\n\tif (!threads) throw new Error('No engine threads; call enableThreads() from poker-flopsolve/threads first');\n\treturn threads.spawn(setup, onError);\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\n/** How a pool starts its workers; the platform's `spawnWorker` unless a test swaps it. */\nexport type SpawnWorker = (setup: WorkerSetup, onError: (error: Error) => void) => WorkerHandle;\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\t/** Set, never cleared, once any thread's part of a step threw; see src/worker.ts. */\n\tfailed: 7,\n\tsize: 8,\n} as const;\n\n/** What a threaded step throws once a thread has failed mid-iteration, here or in src/engine.ts. */\nexport const THREAD_FAILED_ERROR =\n\t'A solver thread failed mid-iteration; this run cannot continue. Close it and solve again, or use workers: 1.';\n\n/**\n * What a threaded step throws once another thread has gone silent past the\n * backstop, here or in src/engine.ts.\n */\nexport const THREAD_LOST_ERROR =\n\t'A solver thread stopped answering mid-iteration; it may have run out of memory or been killed. ' +\n\t'This run cannot continue. Close it and solve again, or use workers: 1.';\n\n/**\n * The backstop on how long the main thread waits for the others in one step.\n *\n * A thread that throws reports itself in shared memory, but one killed\n * without unwinding (a Node worker out of V8 heap, a worker the browser\n * kills) runs no `catch` or `finally`, and its error event cannot reach a\n * main thread waiting in `Atomics.wait`. Every thread's shard is the same\n * size as the main thread's own and runs under the same load, so the wait is\n * bounded at a multiple of the main thread's own shard time, and never under\n * the floor: it only fires with one thread both 20× slower than the main\n * thread and over a minute late.\n */\nexport const THREAD_BACKSTOP_FLOOR_MS = 60_000;\nexport const THREAD_BACKSTOP_FACTOR = 20;\n\n/**\n * How long, from the step's dispatch, the main thread waits for the others.\n * @param ownMs the main thread's own shard time this step\n * @param floorMs the shortest wait; tests shorten it\n */\nexport function backstopMs(ownMs: number, floorMs: number = THREAD_BACKSTOP_FLOOR_MS): number {\n\treturn Math.max(floorMs, THREAD_BACKSTOP_FACTOR * ownMs);\n}\n\n/** How long one `Atomics.wait` of {@link awaitThreads} sleeps before looking again. */\nconst WAIT_SLICE_MS = 50;\n/** A wait that overruns its slice by more than this was a stopped process, not a slow thread. */\nconst STOPPED_MS = 1_000;\n\n/**\n * Wait, after this thread's own shard, for the other threads to count\n * themselves done in `control[slot]`, or until the backstop passes.\n *\n * Time the whole process spends stopped mid-wait (a debugger, Ctrl-Z, a VM\n * pause, a sleep the clock counts) stops every thread alike, so it extends\n * the backstop rather than counting against the others.\n *\n * @param control the pool's control slots\n * @param slot the slot the other threads count themselves done in\n * @param target how many other threads there are\n * @param dispatched `performance.now()` when the step was dispatched\n * @param floorMs the backstop's floor; see {@link backstopMs}\n * @param stopped whether to stop waiting for some other reason\n * @returns {@link THREAD_LOST_ERROR} once the backstop passes, else null\n */\nexport function awaitThreads(\n\tcontrol: Int32Array,\n\tslot: number,\n\ttarget: number,\n\tdispatched: number,\n\tfloorMs: number | undefined,\n\tstopped: () => boolean,\n): Error | null {\n\t// Monotonic, so a change to the wall clock is not taken for a silent thread.\n\tlet giveUp = dispatched + backstopMs(performance.now() - dispatched, floorMs);\n\tfor (;;) {\n\t\tconst done = Atomics.load(control, slot);\n\t\tif (done >= target || stopped()) return null;\n\t\tconst before = performance.now();\n\t\tif (before > giveUp) return new Error(THREAD_LOST_ERROR);\n\t\tAtomics.wait(control, slot, done, WAIT_SLICE_MS);\n\t\tconst overrun = performance.now() - before - WAIT_SLICE_MS;\n\t\tif (overrun > STOPPED_MS) giveUp += overrun;\n\t}\n}\n\nexport const COMMAND = { work: 0, exit: 1 } as const;\n\n/** How long worker threads may take to start before a solve gives up on them. */\nexport const WORKER_START_MS = 30_000;\nexport const WORKER_START_ERROR =\n\t'Worker threads did not start within 30 s. Run with workers: 1, or check that worker threads can load this package.';\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\t/** Compact storage's regrets and hand scales, else null. */\n\treadonly compactRegret: SharedArrayBuffer[] | null;\n\treadonly handShift: SharedArrayBuffer[] | null;\n\treadonly compactSum: SharedArrayBuffer[] | null;\n\treadonly sumShift: SharedArrayBuffer[] | null;\n\treadonly compactScale: SharedArrayBuffer | null;\n\t/**\n\t * Chance sampling's baselines, last walks and last updates, else null.\n\t * Each thread reads and writes only its own runouts' entries.\n\t */\n\treadonly sampling: readonly [SharedArrayBuffer, SharedArrayBuffer, 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 * @param spawn how each worker is started\n * @param backstopFloorMs the shortest a step waits for the workers; see {@link backstopMs}\n */\nexport function startPool(\n\tctx: Context,\n\tsolver: Solver,\n\tplan: ShardPlan,\n\tpayload: unknown,\n\tworkers: number,\n\tspawn: SpawnWorker = spawnWorker,\n\tbackstopFloorMs: number = THREAD_BACKSTOP_FLOOR_MS,\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\t// Workers wrap each of sampling's buffers whole, so each must be its own shared buffer.\n\tconst samplingBuffers = ctx.sampling\n\t\t? ([ctx.sampling.baseline, ctx.sampling.lastWalk, ctx.sampling.lastUpdate] as const).map((view) => {\n\t\t\t\tif (!(view.buffer instanceof SharedArrayBuffer) || view.byteOffset !== 0 || view.byteLength !== view.buffer.byteLength) {\n\t\t\t\t\tthrow new Error('chanceSampling on worker threads needs its state in shared buffers of its own');\n\t\t\t\t}\n\t\t\t\treturn view.buffer;\n\t\t\t})\n\t\t: 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\tcompactRegret: ctx.compactRegret?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\thandShift: ctx.handShift?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\tcompactSum: ctx.compactSum?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\tsumShift: ctx.sumShift?.map((chunk) => chunk.buffer as SharedArrayBuffer) ?? null,\n\t\t\tcompactScale: (ctx.compactScale?.buffer as SharedArrayBuffer | undefined) ?? null,\n\t\t\tsampling: samplingBuffers ? [samplingBuffers[0], samplingBuffers[1], samplingBuffers[2]] : 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 = spawn(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\t// A worker that fails to start reports it by an event, which cannot be\n\t// delivered while this thread waits here, so the wait is bounded.\n\tconst deadline = Date.now() + WORKER_START_MS;\n\tfor (;;) {\n\t\tconst ready = Atomics.load(control, CONTROL.ready);\n\t\tif (ready >= spawned || failure) break;\n\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\telse Atomics.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 failed = (): Error | null =>\n\t\tfailure ?? (Atomics.load(control, CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);\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\t\tconst dispatched = performance.now();\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\t// A worker whose walk throws says so in `failed` and counts itself\n\t\t// done, as its error event cannot reach this thread while it waits.\n\t\t// One killed without unwinding does neither, hence the backstop.\n\t\tfailure ??= awaitThreads(control, CONTROL.done, spawned, dispatched, backstopFloorMs, () => failure !== null);\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t};\n\n\tconst traverseAll: RootTraversal = (mode, traverser, iterWeight) => {\n\t\t// Pass A: walk the round above the split to capture what each worker\n\t\t// needs, applying nothing.\n\t\tctx.applyUpdates = false;\n\t\tctx.chanceOverride = null;\n\t\tctx.chanceCollect = (node, reachMe, reachOpp) => {\n\t\t\tconst entry = plan.entryIndexOf[node];\n\t\t\texchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);\n\t\t\texchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);\n\t\t};\n\t\ttry {\n\t\t\tsolver.traverseRoot(mode, traverser, iterWeight);\n\t\t} finally {\n\t\t\tctx.chanceCollect = null;\n\t\t}\n\n\t\t// Leaves this thread's own partial in `chanceValues`.\n\t\tdispatch(mode, traverser, iterWeight);\n\n\t\tfor (let w = 0; w < spawned; w++) {\n\t\t\tconst base = reachFloats + w * entryCount * COMBOS;\n\t\t\tfor (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];\n\t\t}\n\n\t\t// Pass B: finish that round from the totals, now applying updates.\n\t\tctx.chanceOverride = chanceValues;\n\t\tctx.applyUpdates = true;\n\t\ttry {\n\t\t\tconst value = solver.traverseRoot(mode, traverser, iterWeight);\n\t\t\ttotal.set(value.subarray(0, COMBOS));\n\t\t} finally {\n\t\t\tctx.chanceOverride = null;\n\t\t}\n\t\treturn total;\n\t};\n\n\treturn {\n\t\tworkers,\n\t\ttraverse(mode, traverser, iterWeight) {\n\t\t\t// Once any thread has failed, so does every step after, before it\n\t\t\t// touches anything.\n\t\t\tconst dead = failed();\n\t\t\tif (dead) throw dead;\n\t\t\ttry {\n\t\t\t\treturn traverseAll(mode, traverser, iterWeight);\n\t\t\t} catch (error) {\n\t\t\t\t// This thread's own part may have thrown with the workers still\n\t\t\t\t// walking; no later step may run over them.\n\t\t\t\tAtomics.store(control, CONTROL.failed, 1);\n\t\t\t\tthrow error;\n\t\t\t}\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 * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs where WebAssembly SIMD is available,\n * on one thread or several; otherwise the JavaScript traversal in cfr.ts\n * runs. A second build, which only `poker-flopsolve/wasm-storage` carries,\n * keeps 16-bit and compact storage the same way (`EngineInput.storage`).\n *\n * WebAssembly memory is one buffer, but Chromium lets it reach wasm32's full\n * 4 GiB, plain or shared, made at that size or grown to it, where it refuses\n * any ArrayBuffer over 2 GiB less 2 MiB (measured in Chromium 153 by\n * bin/memory-ceiling.ts; issue #84). So compact storage needs no chunks of\n * its own in the engine: its chunks are regions of the one memory, laid out\n * as the JavaScript engine's buffers are.\n */\n\nimport { COMBOS } from './cards.ts';\nimport type { ActiveLists, CompactPlan, Layout, PlayerIndex, RegretStore, RootTraversal, SamplingPlan, SumStore } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\nimport { awaitThreads, THREAD_FAILED_ERROR, WORKER_START_ERROR, WORKER_START_MS } from './parallel.ts';\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; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\treturn compileInto(modules, kind, kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM);\n}\n\n/** Compile base64 WebAssembly into `cache[kind]` once; null there where unavailable. */\nfunction compileInto(cache: Record<'plain' | 'shared', object | null | undefined>, kind: 'plain' | 'shared', text: string): object | null {\n\tif (cache[kind] !== undefined) return cache[kind]!;\n\tcache[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tcache[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tcache[kind] = null;\n\t}\n\treturn cache[kind]!;\n}\n\n/**\n * The engine with 16-bit and compact storage (issue #84), as base64 for plain\n * and shared memory. Only `poker-flopsolve/wasm-storage` holds the bytes, so\n * a build that never imports it carries none of them; a solve opts in by\n * passing it as `SolveOptions.wasmStorage`.\n */\nexport interface WasmStorage {\n\treadonly plain: string;\n\treadonly shared: string;\n}\n\nconst storageModules = new WeakMap<WasmStorage, Record<'plain' | 'shared', object | null | undefined>>();\n\n/** The storage engine compiled, over plain or shared memory; null where unavailable. */\nfunction compiledStorage(source: WasmStorage, kind: 'plain' | 'shared'): object | null {\n\tlet cache = storageModules.get(source);\n\tif (!cache) storageModules.set(source, (cache = { plain: undefined, shared: undefined }));\n\treturn compileInto(cache, kind, source[kind]);\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n\t/** Chance sampling's layout, for `Approximations.chanceSampling`; unset for none. */\n\treadonly sampling?: SamplingPlan;\n\t/** Bytes left unused below the layout, rounded up to 16; tests set it to place every pointer past 2 GiB. */\n\treadonly lowBytes?: number;\n\t/**\n\t * 16-bit or compact storage, run by the storage engine `source` holds;\n\t * unset for 32-bit storage on the default engine. `quantised` keeps\n\t * the nodes before `compact.from` (all of them without `compact`) at 16\n\t * bits, as `precision: 'i16'` does.\n\t */\n\treadonly storage?: { readonly source: WasmStorage; readonly quantised: boolean; readonly compact: CompactPlan | null };\n}\n\n/** Compact storage's arrays, per chunk, as `Context` holds them; views onto the engine's memory. */\nexport interface EngineCompact {\n\treadonly regret: (Int8Array | Float32Array)[];\n\treadonly handShift: Uint8Array[] | null;\n\treadonly sum: Uint8Array[] | null;\n\treadonly sumShift: Uint8Array[] | null;\n\treadonly scale: Float64Array | null;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory: 32-bit, or 16-bit with `EngineInput.storage`. */\n\treadonly regret: RegretStore;\n\treadonly strategySum: SumStore;\n\t/** With 16-bit storage, the per-block scales `Context.regretScale` and `sumScale` hold; else null. */\n\treadonly regretScale: Float64Array | null;\n\treadonly sumScale: Float64Array | null;\n\t/** With compact storage, its arrays; else null. */\n\treadonly compact: EngineCompact | null;\n\t/** Chance sampling's state, as views onto the engine's memory; null without sampling. */\n\treadonly sampling: { baseline: Float32Array; lastWalk: Int32Array; lastUpdate: Int32Array } | null;\n\t/** With shared storage, `Context.discounted` as a view onto the engine's memory; else null. */\n\treadonly discounted: Int32Array | null;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n\t/** With threads, where each traversal's time went (see `PROFILE`); null on one thread. */\n\treadonly profile: Float64Array | null;\n}\n\n/**\n * Slots of `Engine.profile`, milliseconds summed over every threaded\n * traversal (issue #133): the main thread's walk above the split before\n * the threads start (`collect`) and after they finish (`override`), its\n * wait for the others, adding their partial values, and from `busy` on\n * the time each thread spent walking boards, the main thread's first;\n * `run` is the whole threaded traversal. A few clock reads a thread a\n * traversal, so it is always on.\n */\nexport const PROFILE = { traversals: 0, collect: 1, override: 2, wait: 3, reduce: 4, run: 5, busy: 6 } as const;\n\n/** Each threaded run's profile, by the solver it runs for: read by benches, not part of the API. */\nexport const threadProfiles = new WeakMap<object, Float64Array>();\n\n/** The split round's boards in the order threads take them, and each board's last walk time, per traverser. */\nexport interface ScheduleViews {\n\treadonly order: Int32Array;\n\treadonly cost: Float64Array;\n}\n\n/** Bytes of a schedule for `boards` boards. */\nexport function scheduleBytes(boards: number): number {\n\treturn Math.ceil(boards / 2) * 8 + 2 * boards * 8;\n}\n\n/** A schedule's views onto its buffer. */\nexport function scheduleViews(buffer: SharedArrayBuffer, boards: number): ScheduleViews {\n\treturn {\n\t\torder: new Int32Array(buffer, 0, boards),\n\t\tcost: new Float64Array(buffer, Math.ceil(boards / 2) * 8, 2 * boards),\n\t};\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\t/** The split round and its number of boards. */\n\treadonly shard: readonly [number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\t/** Where each board's values for each entry go: `boards × entries` rows, board-major. */\n\treadonly boardValues: number;\n\t/** The boards' walking order and their last costs; see `scheduleViews`. */\n\treadonly schedule: SharedArrayBuffer;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n\t/** With shared storage: where the discount marks, the block table and the weighted nodes (or 0) sit. */\n\treadonly shared?: readonly [number, number, number];\n\t/** Set for the storage engine, whose updates need the iteration on every walk. */\n\treadonly storage?: boolean;\n\t/**\n\t * With chance sampling, `setSampling`'s arguments as the main thread\n\t * passed them: its state is in the shared memory, and each thread walks\n\t * and marks only its own runouts' deals.\n\t */\n\treadonly sampling?: SamplingArgs;\n\t/** `Engine.profile`'s buffer and this thread's slot in it. */\n\treadonly profile: readonly [SharedArrayBuffer, number];\n\t/** This thread's share of the storage to touch before it reports ready: `from, to` byte pairs; see `touchShares`. */\n\treadonly touch: readonly number[];\n}\n\n/** Bytes between two touches: a page of memory, the smallest a platform here maps. */\nconst TOUCH_STEP = 4096;\n\n/**\n * Split empty storage into one share a thread, as `from, to` byte pairs.\n *\n * Fresh memory is mapped page by page as it is first written, and left to\n * the first iteration that happens with every thread writing at once, each\n * waiting on the others: measured on a flop on 4 threads, it took 380 ms\n * where later ones took 75, and 1.3 s against 70 ms under chance sampling,\n * whose first iteration walks every deal. Written once up front, a share a\n * thread and in order, the same pages took 50–250 ms.\n *\n * @param ranges the pieces, as `[from, to]` in bytes\n * @param shares how many threads share them\n */\nfunction touchShares(ranges: readonly (readonly [number, number])[], shares: number): number[][] {\n\tconst total = ranges.reduce((sum, [from, to]) => sum + (to - from), 0);\n\tconst each = Math.ceil(total / shares / TOUCH_STEP) * TOUCH_STEP;\n\tconst out: number[][] = Array.from({ length: shares }, () => []);\n\tlet share = 0;\n\tlet room = each;\n\tfor (const [start, to] of ranges) {\n\t\tlet from = start;\n\t\twhile (from < to) {\n\t\t\tconst take = Math.min(room, to - from);\n\t\t\tout[share].push(from, from + take);\n\t\t\tfrom += take;\n\t\t\troom -= take;\n\t\t\tif (room === 0 && share < shares - 1) {\n\t\t\t\tshare++;\n\t\t\t\troom = each;\n\t\t\t}\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Write a zero to each page of a share of empty storage, so the memory is\n * mapped before the solve needs it. Only over pieces still all zeros, which\n * `createEngine` marks: reading a byte to write it back would be safe on any\n * piece, but maps each page twice, once to read and once to write, and an\n * atomic write took several times as long. Nothing else writes to a share\n * between the engine's memory being filled and its threads being ready.\n */\nfunction touchStorage(bytes: Uint8Array, share: readonly number[]): void {\n\tfor (let r = 0; r < share.length; r += 2) {\n\t\tfor (let at = share[r]; at < share[r + 1]; at += TOUCH_STEP) bytes[at] = 0;\n\t}\n}\n\n/** `EngineExports.setSampling`'s arguments, in order. */\nexport type SamplingArgs = Parameters<EngineExports['setSampling']>;\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** The most memory the engine lays out: just under wasm32's 4 GB. */\nconst MAX_MEMORY = 0xffff0000;\n\n/**\n * Control slots shared with engine workers. `failed` is set, never cleared,\n * once any thread's part of a step threw: the main thread waits in\n * `Atomics.wait` and so never sees a worker's error event while a step runs.\n */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, next: 7, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the plan's round between them, each taking the next board\n * off a shared queue (`runThreaded`), where the JavaScript engine's pool in\n * src/parallel.ts gives each worker a fixed slice.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: {\n\t\tplan: ShardPlan;\n\t\tthreads: number;\n\t\tspawn: SpawnEngineWorker;\n\t\t/** The shortest a step waits for the other threads; see `awaitThreads` in src/parallel.ts. */\n\t\tbackstopFloorMs?: number;\n\t},\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst storage = input.storage ?? null;\n\tconst compiledModule = storage\n\t\t? compiledStorage(storage.source, shared ? 'shared' : 'plain')\n\t\t: compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst compact = storage?.compact ?? null;\n\tconst quantised = storage?.quantised ?? false;\n\t// Its accumulators alone would pass wasm32's 4 GB, so no engine; checked\n\t// before anything is built. Such a layout is also the only kind that\n\t// holds offsets as Float64, which the engine's 32-bit offset table could\n\t// not take.\n\tconst width = quantised ? 2 : 4;\n\tconst compactBytes = !compact\n\t\t? 0\n\t\t: compact.float\n\t\t\t? layout.compactSlots * 4\n\t\t\t: (layout.compactSlots + (compact.perHand ? layout.compactHands : 0)) * (compact.sums ? 2 : 1);\n\tif (layout.totalSlots * width * 2 + compactBytes > MAX_MEMORY || !(layout.offset instanceof Int32Array)) return null;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tlet maxCount = 4;\n\tfor (let i = 0; i < active.count.length; i++) if (active.count[i] > maxCount) maxCount = active.count[i];\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\t// `empty`: allocated as zeros and left so until the first iteration, which\n\t// is what `touchStorage` may write zeros over. A piece filled in below,\n\t// before the threads start, says false.\n\tconst pieces: { data: ArrayBufferView | null; bytes: number; empty: boolean }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0, empty = data === null): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16, empty });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(new Int32Array(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.packed), add(new Float32Array(active.multiplicity)), add(active.memberStart),\n\t\tadd(active.memberA), add(active.memberB), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * width), // regret\n\t\tadd(null, layout.totalSlots * width), // strategy sums\n\t];\n\tconst REGRET = common[common.length - 2];\n\tconst SUMS = common[common.length - 1];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4, false),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\t// Each board's values, apart, so their sum does not depend on which thread walked which.\n\tconst boardValues = pool ? add(null, pool.plan.boards * entries * rowBytes) : -1;\n\t// Chance sampling, only when asked for.\n\tconst plan = input.sampling;\n\tconst sample = plan\n\t\t? {\n\t\t\t\tbaseOffset: add(plan.baseOffset), boardOffset: add(plan.boardOffset), walkOffset: add(plan.walkOffset),\n\t\t\t\tblockOffset: add(layout.blockOffset), baseline: add(null, plan.values * 4), lastWalk: add(null, plan.walks * 4),\n\t\t\t\tlastUpdate: add(null, plan.blocks * 4),\n\t\t\t}\n\t\t: null;\n\t// History sharing's once-an-iteration discount marks, only when storage is shared.\n\tconst share = layout.shared\n\t\t? {\n\t\t\t\tmarks: add(null, layout.blocks * 4),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : add(layout.blockOffset),\n\t\t\t\tweighted: layout.reachWeighted ? add(layout.reachWeighted) : -1,\n\t\t\t}\n\t\t: null;\n\t// 16-bit and compact storage's settings, scales and chunks, only on the storage engine.\n\tconst chunks = compact ? layout.chunkSlots.length : 0;\n\tconst stored = storage\n\t\t? {\n\t\t\t\tblock: add(null, 128, false),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),\n\t\t\t\tregretScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tsumScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tcompactChunk: compact ? add(layout.compactChunk) : -1,\n\t\t\t\thandOffset: compact ? add(new Int32Array(layout.handOffset!)) : -1,\n\t\t\t\ttables: compact ? add(null, chunks * 4 * 5, false) : -1,\n\t\t\t\tregrets: layout.chunkSlots.map((slots) => add(null, slots * (compact!.float ? 4 : 1))),\n\t\t\t\tshifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tsums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],\n\t\t\t\tsumShifts: compact?.sums ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tcompactScale: compact && !compact.perHand && !compact.float ? add(null, layout.blocks * 8) : -1,\n\t\t\t}\n\t\t: null;\n\n\tconst offsets: number[] = [];\n\tlet total = 64 + Math.ceil(Math.max(input.lowBytes ?? 0, 0) / 16) * 16;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > MAX_MEMORY) return null;\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\t// The accumulators and whatever else is allocated empty and large: the\n\t// pages the first iteration would otherwise map as it met them.\n\tconst touch = touchShares(\n\t\tpieces.flatMap((piece, i) => (piece.empty && piece.bytes >= 16 * TOUCH_STEP ? [[offsets[i], offsets[i] + piece.bytes] as const] : [])),\n\t\tthreads,\n\t);\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[common.length] = offsets[mine.buffers];\n\t\thead[common.length + 1] = depthBytes;\n\t\thead[common.length + 2] = rowBytes;\n\t\thead[common.length + 3] = offsets[mine.cardSums];\n\t\thead[common.length + 4] = input.chipScale;\n\t\tif (stored) head[common.length + 5] = offsets[stored.block];\n\t}\n\tif (stored) {\n\t\tconst at = (slot: number): number => (slot >= 0 ? offsets[slot] : 0);\n\t\tconst block = new Uint32Array(memory.buffer, offsets[stored.block], 20);\n\t\tblock.set([\n\t\t\tquantised ? 1 : 0, compact ? compact.from : 255, !compact ? 0 : compact.float ? 3 : compact.perHand ? 1 : 2,\n\t\t\tcompact?.sums ? 1 : 0, compact?.stochastic ? 1 : 0, compact?.steps ?? 127,\n\t\t\tat(stored.regretScale), at(stored.sumScale), offsets[stored.blockOffset], at(stored.compactChunk),\n\t\t\tat(stored.handOffset),\n\t\t]);\n\t\tif (compact) {\n\t\t\t// Per chunk: where its regrets, hand scales, sums and sum scales sit, and its first slot.\n\t\t\tconst tables = offsets[stored.tables];\n\t\t\tconst table = new Uint32Array(memory.buffer, tables, chunks * 5);\n\t\t\tfor (let c = 0; c < chunks; c++) {\n\t\t\t\ttable[c] = offsets[stored.regrets[c]];\n\t\t\t\ttable[chunks + c] = stored.shifts.length ? offsets[stored.shifts[c]] : 0;\n\t\t\t\ttable[2 * chunks + c] = stored.sums.length ? offsets[stored.sums[c]] : 0;\n\t\t\t\ttable[3 * chunks + c] = stored.sumShifts.length ? offsets[stored.sumShifts[c]] : 0;\n\t\t\t\ttable[4 * chunks + c] = layout.chunkStart[c] >>> 0;\n\t\t\t}\n\t\t\tblock.set([tables, tables + chunks * 4, tables + chunks * 8, tables + chunks * 12, tables + chunks * 16, at(stored.compactScale)], 11);\n\t\t}\n\t}\n\t// The update rule's factors, as float64, which the storage engine reads before each walk.\n\tconst factors = stored ? new Float64Array(memory.buffer, offsets[stored.block] + 80, 4) : null;\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\tlet samplingViews: Engine['sampling'] = null;\n\tlet samplingArgs: SamplingArgs | null = null;\n\tif (plan && sample) {\n\t\tlet mask = 0;\n\t\tfor (let r = 0; r < plan.rounds.length; r++) if (plan.rounds[r]) mask |= 1 << r;\n\t\tsamplingArgs = [\n\t\t\tmask, plan.p, plan.every, plan.unbiased ? 1 : 0, plan.catchUp ? 1 : 0,\n\t\t\toffsets[sample.baseOffset], offsets[sample.boardOffset], offsets[sample.walkOffset],\n\t\t\toffsets[sample.baseline], offsets[sample.lastWalk], offsets[sample.lastUpdate], offsets[sample.blockOffset],\n\t\t];\n\t\tconst a = samplingArgs;\n\t\texports.setSampling(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]);\n\t\tsamplingViews = {\n\t\t\tbaseline: new Float32Array(memory.buffer, offsets[sample.baseline], plan.values),\n\t\t\tlastWalk: new Int32Array(memory.buffer, offsets[sample.lastWalk], plan.walks),\n\t\t\tlastUpdate: new Int32Array(memory.buffer, offsets[sample.lastUpdate], plan.blocks),\n\t\t};\n\t}\n\n\tconst weightedAt = share && share.weighted >= 0 ? offsets[share.weighted] : 0;\n\tif (share) exports.setShared(offsets[share.marks], offsets[share.blockOffset], weightedAt);\n\tconst discounted = share ? new Int32Array(memory.buffer, offsets[share.marks], layout.blocks) : null;\n\n\tconst regret: RegretStore = quantised\n\t\t? new Int16Array(memory.buffer, offsets[REGRET], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum: SumStore = quantised\n\t\t? new Uint16Array(memory.buffer, offsets[SUMS], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst scaleView = (slot: number): Float64Array | null =>\n\t\tslot >= 0 ? new Float64Array(memory.buffer, offsets[slot], layout.blocks) : null;\n\tconst compactViews: EngineCompact | null = stored && compact\n\t\t? {\n\t\t\t\tregret: stored.regrets.map((slot, c) =>\n\t\t\t\t\tcompact.float\n\t\t\t\t\t\t? new Float32Array(memory.buffer, offsets[slot], layout.chunkSlots[c])\n\t\t\t\t\t\t: new Int8Array(memory.buffer, offsets[slot], layout.chunkSlots[c]),\n\t\t\t\t),\n\t\t\t\thandShift: compact.perHand ? stored.shifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tsum: compact.sums ? stored.sums.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkSlots[c])) : null,\n\t\t\t\tsumShift: compact.sums ? stored.sumShifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tscale: scaleView(stored.compactScale),\n\t\t\t}\n\t\t: null;\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tlet profile: Float64Array | null = null;\n\tlet schedule: ScheduleViews | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (!pool) touchStorage(bytes, touch[0]);\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\tconst profileBuffer = new SharedArrayBuffer(8 * (PROFILE.busy + threads));\n\t\tprofile = new Float64Array(profileBuffer);\n\t\tconst scheduleBuffer = new SharedArrayBuffer(scheduleBytes(plan.boards));\n\t\tschedule = scheduleViews(scheduleBuffer, plan.boards);\n\t\tfor (let i = 0; i < plan.boards; i++) schedule.order[i] = i;\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.boards],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tboardValues: offsets[boardValues], schedule: scheduleBuffer,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t\t...(share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] as const } : {}),\n\t\t\t\t...(stored ? { storage: true } : {}),\n\t\t\t\t...(samplingArgs ? { sampling: samplingArgs } : {}),\n\t\t\t\tprofile: [profileBuffer, PROFILE.busy + w],\n\t\t\t\ttouch: touch[w],\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\t// This thread's share, while the others start and touch theirs.\n\t\ttouchStorage(bytes, touch[0]);\n\t\t// A worker that fails to start reports it by an event, which cannot\n\t\t// be delivered while this thread waits here, so the wait is bounded.\n\t\tconst deadline = Date.now() + WORKER_START_MS;\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\t\telse Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst failed = (): Error | null =>\n\t\tfailure ?? (control && Atomics.load(control, ENGINE_CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);\n\n\t// The iteration a step is for, and its rule, which shared storage's threads need.\n\tlet iteration = 0;\n\tlet dcfrRule = 0;\n\tconst run = (asked: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\t// Once any thread has failed, so does every step after, before it\n\t\t// touches anything.\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\t// The engine knows three modes; the current profile is its Train\n\t\t// with updates off.\n\t\tconst apply = asked === Mode.Current ? 0 : 1;\n\t\tconst mode = asked === Mode.Current ? Mode.Train : asked;\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\titeration = mode === Mode.Train ? iterWeight : 0;\n\t\tdcfrRule = dcfr ? 1 : 0;\n\t\tif (plan || share || stored) exports.setIteration(iteration, dcfrRule);\n\t\t// CFR+ at 16 bits or compact floors a negative regret, as `updateQuantised`\n\t\t// and `updateCompact` do (one only a warm start could bring); 32-bit storage keeps it.\n\t\tfactors?.set([positive, mode === Mode.Train && !dcfr ? 0 : negative, sum, weight]);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tif (apply === 0) exports.setPhase(0, 0);\n\t\t\ttry {\n\t\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\t\t} finally {\n\t\t\t\tif (apply === 0) exports.setPhase(0, 1);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tat = runThreaded(mode, traverser, apply, positive, negative, sum, weight, clamp);\n\t\t\t} catch (error) {\n\t\t\t\t// This thread's own part may have thrown with the workers still\n\t\t\t\t// walking; no later step may run over them.\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.failed, 1);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\t/** One threaded traversal, returning where the root values are. */\n\tconst runThreaded = (\n\t\tmode: number, traverser: 0 | 1, apply: number,\n\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t): number => {\n\t\tconst plan = pool!.plan;\n\t\tconst { order, cost } = schedule!;\n\t\tconst clock = performance.now();\n\t\t// Collect: walk above the split, recording what the workers need.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(1, 0);\n\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\tconst collected = performance.now();\n\t\t// Costliest boards first, by what they took on this traverser's last\n\t\t// training walk, so the last boards anyone takes are the cheap ones.\n\t\t// Only training walks record costs: a best-response or current-profile\n\t\t// pass, unsampled and without updates, costs a board differently.\n\t\tconst costs = cost.subarray(traverser * plan.boards, (traverser + 1) * plan.boards);\n\t\tconst timed = mode === Mode.Train && apply === 1;\n\t\torder.sort((a, b) => costs[b] - costs[a] || a - b);\n\t\t// Every thread takes boards off the order until none are left.\n\t\tsettings!.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);\n\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\tAtomics.store(control!, ENGINE_CONTROL.next, 0);\n\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\tconst dispatched = performance.now();\n\t\texports.setPhase(0, apply);\n\t\tconst heap = new Float32Array(memory.buffer);\n\t\tconst into = offsets[boardValues] >>> 2;\n\t\tfor (;;) {\n\t\t\tconst taken = Atomics.add(control!, ENGINE_CONTROL.next, 1);\n\t\t\tif (taken >= plan.boards) break;\n\t\t\tconst board = order[taken];\n\t\t\texports.setShard(plan.round, board, board + 1);\n\t\t\tconst started = performance.now();\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 2;\n\t\t\t\theap.copyWithin(into + (board * entries + entry) * stride, out, out + stride);\n\t\t\t}\n\t\t\tif (timed) costs[board] = performance.now() - started;\n\t\t}\n\t\tconst walked = performance.now();\n\t\t// A thread whose walk throws says so in `failed` and counts itself\n\t\t// done, as its error event cannot reach this thread while it waits.\n\t\t// One killed without unwinding does neither, hence the backstop.\n\t\tfailure ??= awaitThreads(\n\t\t\tcontrol!, ENGINE_CONTROL.done, threads - 1, dispatched, pool!.backstopFloorMs, () => failure !== null,\n\t\t);\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\tconst waited = performance.now();\n\t\t// The boards' values summed in board order, whoever walked them.\n\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\tvalueView.fill(0);\n\t\tfor (let board = 0; board < plan.boards; board++) {\n\t\t\tconst rows = into + board * entries * stride;\n\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += heap[rows + i];\n\t\t}\n\t\tconst reduced = performance.now();\n\t\t// Finish above the split from the totals, now applying updates\n\t\t// unless this is a current-profile read.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(2, apply);\n\t\tconst at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\texports.setPhase(0, 1);\n\t\texports.setShard(-1, 0, 0);\n\t\tconst p = profile!;\n\t\tconst finished = performance.now();\n\t\tp[PROFILE.traversals]++;\n\t\tp[PROFILE.collect] += collected - clock;\n\t\tp[PROFILE.busy] += walked - dispatched;\n\t\tp[PROFILE.wait] += waited - walked;\n\t\tp[PROFILE.reduce] += reduced - waited;\n\t\tp[PROFILE.override] += finished - reduced;\n\t\tp[PROFILE.run] += finished - clock;\n\t\treturn at;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tregretScale: stored ? scaleView(stored.regretScale) : null,\n\t\tsumScale: stored ? scaleView(stored.sumScale) : null,\n\t\tcompact: compactViews,\n\t\tsampling: samplingViews,\n\t\tdiscounted,\n\t\tthreads,\n\t\tprofile,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/**\n * The engine's exports. A pointer one returns is a wasm32 `usize`, which\n * JavaScript receives as a signed 32-bit integer: read it with `>>> 0`, or\n * any address past 2 GiB comes back negative (#62).\n */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\tsetSampling(\n\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t): void;\n\tsetIteration(t: number, dcfr: number): void;\n\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\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 * A solve of another board can seed this one through a card relabelling — a\n * permutation of the deck taking one board onto the other, a rank swap for a\n * nearby flop — through which its runouts and hands are read.\n */\n\nimport type { Context, RegretStore, SumStore } from './cfr.ts';\nimport { COMPACT_SUM_STEPS, regretMatch, scaleExponent, SHIFT_SCALE } from './cfr.ts';\nimport { COMBO_CARDS, COMBOS, DECK, comboIndex } from './cards.ts';\nimport { markMembers } from './hands.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. */\nexport const SIZE_TOLERANCE = 1.35;\n\nexport const REGRET_STEPS = 32767;\nexport const 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, tolerance = SIZE_TOLERANCE): 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, tolerance);\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, tolerance: 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(tolerance) ? best : -1;\n}\n\n/** Read one block — a node on a board — as plain numbers, `actions * count` of them. */\nexport function 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. */\nexport function 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/**\n * Read a compactly stored block as plain numbers: the regrets, unless\n * `regrets` is null, and the strategy sums. Where compact storage keeps no\n * sums its strategy is the current profile, so that is what comes back as\n * the sums: any positive multiple of a strategy averages to it.\n */\nexport function readCompactBlock(\n\tctx: Context,\n\tnode: number,\n\tlistSlot: number,\n\tblock: number,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tregrets: Float64Array | null,\n\tsums: Float64Array,\n): void {\n\tconst plan = ctx.compact!;\n\tconst chunk = ctx.layout.compactChunk![node];\n\tconst q = ctx.compactRegret![chunk];\n\tconst handBase = ctx.layout.handOffset![node] + ctx.layout.rowStart[listSlot];\n\tconst shifts = plan.perHand ? ctx.handShift![chunk] : null;\n\tconst blockScale = !plan.perHand && !plan.float ? ctx.compactScale![block] : 1;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst scale = shifts ? SHIFT_SCALE[shifts[handBase + i]] : blockScale;\n\t\tif (regrets) for (let a = 0; a < actions; a++) regrets[a * count + i] = q[base + a * count + i] * scale;\n\t\tif (!plan.sums) continue;\n\t\tconst sumScale = SHIFT_SCALE[ctx.sumShift![chunk][handBase + i]];\n\t\tconst stored = ctx.compactSum![chunk];\n\t\tfor (let a = 0; a < actions; a++) sums[a * count + i] = stored[base + a * count + i] * sumScale;\n\t}\n\tif (!plan.sums) regretMatch(q, base, actions, count, sums);\n}\n\n/**\n * Write a compactly stored block, encoding it as compact storage does but\n * rounded to nearest: the regrets unless `regrets` is null, the sums where it\n * keeps them unless `sums` is null.\n */\nexport function writeCompactBlock(\n\tctx: Context,\n\tnode: number,\n\tlistSlot: number,\n\tblock: number,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tregrets: Float64Array | null,\n\tsums: Float64Array | null,\n): void {\n\tconst plan = ctx.compact!;\n\tconst chunk = ctx.layout.compactChunk![node];\n\tconst q = ctx.compactRegret![chunk];\n\tconst handBase = ctx.layout.handOffset![node] + ctx.layout.rowStart[listSlot];\n\tconst steps = plan.steps;\n\tconst fit = (value: number, top: number, bottom: number): number => {\n\t\tconst rounded = Math.round(value);\n\t\treturn rounded > top ? top : rounded < bottom ? bottom : rounded;\n\t};\n\tif (regrets && plan.float) {\n\t\tfor (let k = 0; k < actions * count; k++) q[base + k] = regrets[k];\n\t} else if (regrets && !plan.perHand) {\n\t\tlet largest = 0;\n\t\tfor (let k = 0; k < actions * count; k++) largest = Math.max(largest, Math.abs(regrets[k]));\n\t\tconst step = largest > 0 ? steps / largest : 0;\n\t\tfor (let k = 0; k < actions * count; k++) q[base + k] = fit(regrets[k] * step, steps, -steps);\n\t\tctx.compactScale![block] = largest / steps;\n\t} else if (regrets) {\n\t\tconst shifts = ctx.handShift![chunk];\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tlet largest = 0;\n\t\t\tfor (let a = 0; a < actions; a++) largest = Math.max(largest, Math.abs(regrets[a * count + i]));\n\t\t\tconst exponent = scaleExponent(largest, steps);\n\t\t\tshifts[handBase + i] = exponent;\n\t\t\tconst inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];\n\t\t\tfor (let a = 0; a < actions; a++) q[base + a * count + i] = fit(regrets[a * count + i] * inverse, steps, -steps);\n\t\t}\n\t}\n\tif (!sums || !plan.sums) return;\n\tconst stored = ctx.compactSum![chunk];\n\tconst shifts = ctx.sumShift![chunk];\n\tfor (let i = 0; i < count; i++) {\n\t\tlet largest = 0;\n\t\tfor (let a = 0; a < actions; a++) largest = Math.max(largest, sums[a * count + i]);\n\t\tconst exponent = scaleExponent(largest, COMPACT_SUM_STEPS);\n\t\tshifts[handBase + i] = exponent;\n\t\tconst inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];\n\t\tfor (let a = 0; a < actions; a++) stored[base + a * count + i] = fit(sums[a * count + i] * inverse, COMPACT_SUM_STEPS, 0);\n\t}\n}\n\n/** The real cards of a stored board. */\nexport function 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, unless `cards`\n * relabels one onto the other.\n *\n * @param cards for a solve of a different board: each card of `to` to the card\n * of `from` it plays as, a permutation of the deck taking `to`'s board onto\n * `from`'s. Hands and dealt cards map through it too. Unset, the identity.\n * @param tolerance largest ratio between two bet sizes still matched; unset,\n * `SIZE_TOLERANCE`. `Infinity` maps every bet to the nearest one of its kind,\n * which seeds a size the old tree lacked from its neighbour.\n * @returns what matched\n * @throws if the boards differ, or `cards` does not take one onto the other\n */\nexport function warmStart(\n\tto: Context,\n\tfrom: Context,\n\taverages: boolean,\n\tcards?: Uint8Array,\n\ttolerance = SIZE_TOLERANCE,\n): WarmStartReport {\n\tif (!(tolerance >= 1)) throw new Error(`warmStart: the size tolerance is a ratio of at least 1, not ${tolerance}`);\n\t// Each node is copied on its own, so into shared storage every history of\n\t// a group would overwrite the same block and the last would win. From\n\t// shared storage the copy is exact: each node takes its owner's block.\n\tif (to.layout.shared && !from.layout.shared) {\n\t\tthrow new Error('A spot with shareHistories can only warm-start from a solve that shares histories too');\n\t}\n\tconst a = to.runouts.initial;\n\tconst b = from.runouts.initial;\n\tif (cards) checkRelabelling(cards, a, b);\n\telse if (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, unless `warmCards` relabels one onto the other');\n\t}\n\t// A real board of `to` as `from` sees it: its own given board first, in\n\t// its order, then the dealt cards relabelled.\n\tconst asSource = (real: number[]): number[] =>\n\t\tcards ? [...b, ...real.slice(a.length).map((card) => cards[card])] : real;\n\t// Each hand of `to` as the hand of `from` it plays as.\n\tconst comboOf = new Uint16Array(COMBOS);\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tcomboOf[combo] = cards ? comboIndex(cards[COMBO_CARDS[combo * 2]], cards[COMBO_CARDS[combo * 2 + 1]]) : combo;\n\t}\n\tconst match = matchNodes(to.tree, from.tree, tolerance);\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\t// An analysis-only run has none; compact storage may keep all of its regrets compactly.\n\tconst keepsRegrets = (ctx: Context): boolean => ctx.regret.length > 0 || (ctx.compactRegret ?? null) !== null;\n\tconst hasRegret = keepsRegrets(to) && keepsRegrets(from);\n\n\t// The matched nodes of each round and owner, and which old action each of\n\t// their actions continues. What follows is laid out board by board: a\n\t// board is resolved once, and each player's hands on it placed in the old\n\t// list once, for every node of the round, where doing both again for\n\t// each node was most of a warm start's time.\n\tconst rounds = to.runouts.rounds;\n\tconst nodesOf: number[][] = Array.from({ length: rounds * 2 }, () => []);\n\tconst actionsOf = new Map<number, Int32Array>();\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 actions = tree.numEdges[node];\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, tolerance);\n\t\t\tif (other >= 0) actionOf[e] = other - from.tree.firstEdge[old];\n\t\t}\n\t\tactionsOf.set(node, actionOf);\n\t\tnodesOf[tree.round[node] * 2 + tree.player[node]].push(node);\n\t}\n\n\t// A combination's position in the old board's hand list, or -1.\n\tconst position = new Int32Array(COMBOS).fill(-1);\n\t// For each hand a new entry stands for, in order, its position in the old list.\n\tconst sourceOf = new Int32Array(COMBOS);\n\tconst sourceEnd = new Int32Array(COMBOS);\n\tfor (let round = 0; round < rounds; round++) {\n\t\tif (nodesOf[round * 2].length + nodesOf[round * 2 + 1].length === 0) continue;\n\t\tfor (let board = 0; board < to.runouts.counts[round]; board++) {\n\t\t\tconst resolved = resolveBoard(from.runouts, asSource(realCards(to.runouts, round, board)));\n\t\t\tfor (let owner = 0; owner < 2; owner++) {\n\t\t\t\tconst nodes = nodesOf[round * 2 + owner];\n\t\t\t\tif (nodes.length === 0) continue;\n\t\t\t\t// Blocks are laid out by position in each board's hand list.\n\t\t\t\tconst oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;\n\t\t\t\tconst oldFrom = from.active.start[oldSlot];\n\t\t\t\tconst oldCount = from.active.count[oldSlot];\n\t\t\t\tconst newSlot = (to.active.roundBase[round] + board) * 2 + owner;\n\t\t\t\tconst newFrom = to.active.start[newSlot];\n\t\t\t\tconst count = to.active.count[newSlot];\n\t\t\t\t// Every hand an old entry stands for is at that entry.\n\t\t\t\tmarkMembers(from.active, oldFrom, oldCount, position, false);\n\t\t\t\tlet sources = 0;\n\t\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t\tfor (let m = to.active.memberStart[newFrom + i]; m < to.active.memberStart[newFrom + i + 1]; m++) {\n\t\t\t\t\t\tsourceOf[sources++] = position[resolved.combos[comboOf[to.active.memberCombo[m]]]];\n\t\t\t\t\t}\n\t\t\t\t\tsourceEnd[i] = sources;\n\t\t\t\t}\n\t\t\t\tmarkMembers(from.active, oldFrom, oldCount, position, true);\n\n\t\t\t\t// Plain storage on both sides and one old hand for each new one:\n\t\t\t\t// the usual case, copied store to store.\n\t\t\t\tconst direct =\n\t\t\t\t\tsources === count && round < from.layout.compactFrom && round < to.layout.compactFrom &&\n\t\t\t\t\tfrom.regretScale === null && to.regretScale === null;\n\n\t\t\t\tfor (const node of nodes) {\n\t\t\t\t\tconst old = match[node];\n\t\t\t\t\tconst actions = tree.numEdges[node];\n\t\t\t\t\tconst oldActions = from.tree.numEdges[old];\n\t\t\t\t\tconst actionOf = actionsOf.get(node)!;\n\t\t\t\t\tconst oldBlock = from.layout.blockOffset[old] + resolved.board;\n\t\t\t\t\tconst oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];\n\t\t\t\t\tconst oldLength = oldActions * oldCount;\n\t\t\t\t\tif (direct) {\n\t\t\t\t\t\tconst base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];\n\t\t\t\t\t\tif (hasRegret) copyRows(to.regret, base, from.regret, oldBase, actionOf, count, oldCount, sourceOf);\n\t\t\t\t\t\tif (averages) copyRows(to.strategySum, base, from.strategySum, oldBase, actionOf, count, oldCount, sourceOf);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (round >= from.layout.compactFrom) {\n\t\t\t\t\t\treadCompactBlock(from, old, oldSlot, oldBlock, oldBase, oldActions, oldCount, hasRegret ? oldRegret : null, oldSum);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);\n\t\t\t\t\t\tif (averages) readBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst length = actions * count;\n\t\t\t\t\tnewRegret.fill(0, 0, length);\n\t\t\t\t\tif (averages) newSum.fill(0, 0, length);\n\t\t\t\t\tfor (let e = 0; e < actions; e++) {\n\t\t\t\t\t\tconst action = actionOf[e];\n\t\t\t\t\t\tif (action < 0) continue;\n\t\t\t\t\t\tconst row = e * count;\n\t\t\t\t\t\tconst oldRow = action * oldCount;\n\t\t\t\t\t\tlet first = 0;\n\t\t\t\t\t\tfor (let i = 0; i < count; i++) {\n\t\t\t\t\t\t\t// An entry stands for its mirror orbit here, which the old solve\n\t\t\t\t\t\t\t// may have stored apart and not played alike: it takes their mean.\n\t\t\t\t\t\t\tconst end = sourceEnd[i];\n\t\t\t\t\t\t\tconst share = 1 / (end - first);\n\t\t\t\t\t\t\tfor (let k = first; k < end; k++) {\n\t\t\t\t\t\t\t\tconst j = sourceOf[k];\n\t\t\t\t\t\t\t\tif (j < 0) continue;\n\t\t\t\t\t\t\t\tif (hasRegret) newRegret[row + i] += share * oldRegret[oldRow + j];\n\t\t\t\t\t\t\t\tif (averages) newSum[row + i] += share * oldSum[oldRow + j];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfirst = end;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst block = to.layout.blockOffset[node] + board;\n\t\t\t\t\tconst base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];\n\t\t\t\t\tif (round >= to.layout.compactFrom) {\n\t\t\t\t\t\twriteCompactBlock(to, node, newSlot, block, base, actions, count, hasRegret ? newRegret : null, averages ? newSum : null);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS, block, base, length, newRegret);\n\t\t\t\t\t\tif (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS, block, base, length, newSum);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };\n}\n\n/**\n * Copy a block between plain stores: each new action's row from the old\n * action it continues, each hand from its place in the old list, and zero\n * where there is none.\n */\nfunction copyRows(\n\tto: RegretStore | SumStore,\n\tbase: number,\n\tfrom: RegretStore | SumStore,\n\toldBase: number,\n\tactionOf: Int32Array,\n\tcount: number,\n\toldCount: number,\n\tsourceOf: Int32Array,\n): void {\n\tfor (let e = 0; e < actionOf.length; e++) {\n\t\tconst action = actionOf[e];\n\t\tconst row = base + e * count;\n\t\tif (action < 0) {\n\t\t\tto.fill(0, row, row + count);\n\t\t\tcontinue;\n\t\t}\n\t\tconst oldRow = oldBase + action * oldCount;\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst j = sourceOf[i];\n\t\t\tto[row + i] = j < 0 ? 0 : from[oldRow + j];\n\t\t}\n\t}\n}\n\n/** Throw unless `cards` is a permutation of the deck taking board `a` onto board `b`. */\nfunction checkRelabelling(cards: Uint8Array, a: readonly number[], b: readonly number[]): void {\n\tconst seen = new Uint8Array(DECK);\n\tif (cards.length !== DECK) throw new Error(`A card relabelling maps all ${DECK} cards; got ${cards.length}`);\n\tfor (const card of cards) {\n\t\tif (card >= DECK || seen[card]) throw new Error('A card relabelling must be a permutation of the deck');\n\t\tseen[card] = 1;\n\t}\n\tconst target = new Set(b);\n\tif (a.length !== b.length || a.some((card) => !target.has(cards[card]))) {\n\t\tthrow new Error('The card relabelling must take the board onto the warm start\\'s board');\n\t}\n}\n","/**\n * A stopping rule for solves that never reach an exploitability target: stop\n * once the root play stops moving (issue #100).\n *\n * Purpose: a blueprint with `shareHistories` plateaus several percent of the\n * pot from equilibrium, so `targetPercent` cannot end it, yet its first\n * decisions go on settling and are what a caller reads (issue #85). This\n * reads them cheaply: the average strategy at two nodes, with no\n * best-response pass, so a check costs a tiny fraction of an iteration.\n *\n * The root play is the decision opening the spot (out of position) and, after\n * a check there, in position's: neither player has acted before them, so each\n * decision is played by the whole range and is weighted by it. Its movement\n * between two strategies is, per decision, the total variation of each hand's\n * action mix (half the summed absolute change), averaged over the range by\n * weight; the larger of the two decisions counts. 0.01 means the range's\n * play moved by 1% of its mass. #85 called the root play still once both\n * decisions moved under 1% between checks 20 iterations apart.\n */\n\nimport type { Solution, StrategyView } from './index.ts';\nimport { ActionKind, NodeKind } from './tree.ts';\n\n/** See `SolveOptions.settle`. */\nexport interface SettleOptions {\n\t/** Iterations between checks. Default 20. */\n\treadonly every?: number;\n\t/**\n\t * Movement between consecutive checks, as a share of the range, under\n\t * which the root play counts as still: see `rootPlayMovement`. Default\n\t * 0.01.\n\t */\n\treadonly tolerance?: number;\n\t/** Consecutive still checks before stopping. Default 2. */\n\treadonly patience?: number;\n\t/** Iterations before which no check counts toward `patience`. Default 0. */\n\treadonly minIterations?: number;\n}\n\n/** The strategies `rootPlayMovement` compares; see `rootPlay`. */\nexport interface RootPlay {\n\t/** The root, then in position's decision after a check there, when there is one. */\n\treadonly views: readonly StrategyView[];\n\t/** Range weight per combination of each view's player, indexed like `COMBO_CARDS`. */\n\treadonly weights: readonly Float64Array[];\n}\n\n/** The decisions that make up the root play of a solved spot. */\nexport function rootPlayNodes(solution: Solution): number[] {\n\tconst { tree } = solution.spot;\n\tif (tree.kind[0] !== NodeKind.Decision) return [];\n\tconst nodes = [0];\n\tfor (let e = 0; e < tree.numEdges[0]; e++) {\n\t\tconst edge = tree.firstEdge[0] + e;\n\t\tconst child = tree.edgeChild[edge];\n\t\tif (tree.edgeAction[edge] === ActionKind.Check && tree.kind[child] === NodeKind.Decision) nodes.push(child);\n\t}\n\treturn nodes;\n}\n\n/**\n * The root play of a solution as it stands: the average strategy at the\n * root and at in position's decision after a check. Cheap: two strategy\n * reads, no best-response pass.\n */\nexport function rootPlay(solution: Solution): RootPlay {\n\tconst views = rootPlayNodes(solution).map((node) => solution.strategyAt(node, 0));\n\treturn { views, weights: views.map((view) => solution.spot.players[view.player].weights) };\n}\n\n/**\n * How far the root play moved from `before` to `after`, two readings of the\n * same spot: per decision, the range-weighted mean of each hand's total\n * variation, and the larger over the decisions. 0 is unmoved, 1 is every\n * hand switching to actions it never took.\n */\nexport function rootPlayMovement(before: RootPlay, after: RootPlay): number {\n\tif (before.views.length !== after.views.length) throw new Error('Root plays of different spots cannot be compared');\n\tlet worst = 0;\n\tfor (let d = 0; d < after.views.length; d++) {\n\t\tconst a = before.views[d];\n\t\tconst b = after.views[d];\n\t\tconst actions = b.actions.length;\n\t\tif (a.node !== b.node || a.actions.length !== actions || a.combos.length !== b.combos.length) {\n\t\t\tthrow new Error('Root plays of different spots cannot be compared');\n\t\t}\n\t\tconst weights = after.weights[d];\n\t\tlet moved = 0;\n\t\tlet mass = 0;\n\t\tfor (let i = 0; i < b.combos.length; i++) {\n\t\t\tconst w = weights[b.combos[i]];\n\t\t\tif (!(w > 0)) continue;\n\t\t\tlet tv = 0;\n\t\t\tfor (let k = 0; k < actions; k++) tv += Math.abs(b.probs[i * actions + k] - a.probs[i * actions + k]);\n\t\t\tmoved += (w * tv) / 2;\n\t\t\tmass += w;\n\t\t}\n\t\tif (mass > 0) worst = Math.max(worst, moved / mass);\n\t}\n\treturn worst;\n}\n\n/** Validated settle settings, defaults filled in. */\nexport function settlePlan(options: SettleOptions): Required<SettleOptions> {\n\tconst plan = {\n\t\tevery: options.every ?? 20,\n\t\ttolerance: options.tolerance ?? 0.01,\n\t\tpatience: options.patience ?? 2,\n\t\tminIterations: options.minIterations ?? 0,\n\t};\n\tif (!(Number.isInteger(plan.every) && plan.every > 0)) throw new Error(`settle.every must be a positive whole number; got ${plan.every}`);\n\tif (!(plan.tolerance >= 0)) throw new Error(`settle.tolerance must be 0 or more; got ${plan.tolerance}`);\n\tif (!(Number.isInteger(plan.patience) && plan.patience > 0)) {\n\t\tthrow new Error(`settle.patience must be a positive whole number; got ${plan.patience}`);\n\t}\n\tif (!(plan.minIterations >= 0)) throw new Error(`settle.minIterations must be 0 or more; got ${plan.minIterations}`);\n\treturn plan;\n}\n\n/**\n * A running settle check for a caller that steps a run itself. Feed it a\n * snapshot after each `every` iterations; it says when the root play has\n * stayed still for `patience` checks in a row.\n */\nexport interface SettleTracker {\n\t/** Record a snapshot taken after `iterations` in all; true once settled. */\n\tcheck(solution: Solution, iterations: number): boolean;\n\t/** Movement at the last check, or NaN before the second. */\n\treadonly movement: number;\n\t/** Whether the last check settled it. */\n\treadonly settled: boolean;\n}\n\n/** Start a settle check; see `SettleTracker`. */\nexport function trackSettle(options: SettleOptions = {}): SettleTracker {\n\tconst plan = settlePlan(options);\n\tlet previous: RootPlay | null = null;\n\tlet still = 0;\n\tlet movement = Number.NaN;\n\tlet settled = false;\n\treturn {\n\t\tcheck(solution, iterations) {\n\t\t\tconst play = rootPlay(solution);\n\t\t\tmovement = previous ? rootPlayMovement(previous, play) : Number.NaN;\n\t\t\tprevious = play;\n\t\t\t// A check before `minIterations` does not count toward patience.\n\t\t\tstill = iterations >= plan.minIterations && movement <= plan.tolerance ? still + 1 : 0;\n\t\t\tsettled = still >= plan.patience;\n\t\t\treturn settled;\n\t\t},\n\t\tget movement() {\n\t\t\treturn movement;\n\t\t},\n\t\tget settled() {\n\t\t\treturn settled;\n\t\t},\n\t};\n}\n","/**\n * History merging: turn and river storage shared between betting histories\n * (issue #49). An imperfect-recall abstraction of the betting history.\n *\n * Purpose: decide which decision nodes share one block of storage.\n *\n * Every flop line gets its own copy of the turn and river below it, but a\n * round's subtree depends only on where the round starts: the pot and stacks.\n * Lines that reach the same start — check, bet 33%, call against bet 33%,\n * call — have identical subtrees. Aliasing their nodes' storage lets every\n * history keep its own walk (its own reach, its own values) while regrets and\n * strategy sums accumulate in one place.\n *\n * A round root is the first decision of a later round, the child of a chance\n * node. Only the last round's roots share. Roots with identical subtrees form\n * a group; within a group every root is walked in step with the first one and\n * each node is aliased to its counterpart.\n */\n\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { NodeKind } from './tree.ts';\n\nexport interface HistoryShareOptions {\n\t/** Nodes marked 1 never share: a marked round root keeps its own subtree. */\n\treadonly keep?: Uint8Array;\n}\n\nexport interface HistoryShare {\n\t/** Each node's storage owner: itself, or the node it shares with. */\n\treadonly alias: Int32Array;\n\t/** Round roots per round, and how many groups the shared round formed. */\n\treadonly roots: Int32Array;\n\treadonly groups: Int32Array;\n}\n\n/** Intern strings as small integers. */\nfunction interner(): (key: string) => number {\n\tconst ids = new Map<string, number>();\n\treturn (key) => {\n\t\tlet id = ids.get(key);\n\t\tif (id === undefined) ids.set(key, (id = ids.size));\n\t\treturn id;\n\t};\n}\n\n/**\n * Subtree signatures: equal exactly when two subtrees are identical, amounts\n * included, so nothing below the nodes changes the game.\n */\nfunction signatures(tree: Tree): Int32Array {\n\tconst exact = new Int32Array(tree.nodeCount);\n\tconst exactId = interner();\n\t// Children always come after their parent, so a reverse sweep sees them first.\n\tfor (let node = tree.nodeCount - 1; node >= 0; node--) {\n\t\tlet e = `${tree.kind[node]},${tree.player[node]},${tree.round[node]},${tree.pot[node]},${tree.payoff[node]}`;\n\t\tconst first = tree.firstEdge[node];\n\t\tfor (let i = 0; i < tree.numEdges[node]; i++) {\n\t\t\tconst edge = first + i;\n\t\t\te += `|${tree.edgeAction[edge]}:${tree.edgeTarget[edge]}:${exact[tree.edgeChild[edge]]}`;\n\t\t}\n\t\texact[node] = exactId(e);\n\t}\n\treturn exact;\n}\n\n/** Decide which nodes share storage. */\nexport function aliasHistories(tree: Tree, runouts: Runouts, options: HistoryShareOptions = {}): HistoryShare {\n\tconst exact = signatures(tree);\n\tconst alias = new Int32Array(tree.nodeCount);\n\tfor (let node = 0; node < tree.nodeCount; node++) alias[node] = node;\n\n\t// Round roots, by round. Children come after parents, so these are in tree order.\n\tconst rootsByRound: number[][] = Array.from({ length: runouts.rounds }, () => []);\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (tree.kind[node] !== NodeKind.Chance) continue;\n\t\tconst child = tree.edgeChild[tree.firstEdge[node]];\n\t\tif (tree.kind[child] === NodeKind.Decision) rootsByRound[tree.round[child]].push(child);\n\t}\n\n\tconst walk = (rep: number, member: number): void => {\n\t\talias[member] = rep;\n\t\tconst a = tree.firstEdge[rep];\n\t\tconst b = tree.firstEdge[member];\n\t\tfor (let i = 0; i < tree.numEdges[rep]; i++) walk(tree.edgeChild[a + i], tree.edgeChild[b + i]);\n\t};\n\n\tconst roots = new Int32Array(runouts.rounds);\n\tconst groups = new Int32Array(runouts.rounds);\n\tconst last = runouts.rounds - 1;\n\tif (last >= 1) {\n\t\tconst reps = new Map<number, number>();\n\t\tfor (const root of rootsByRound[last]) {\n\t\t\tif (options.keep?.[root]) continue;\n\t\t\tconst rep = reps.get(exact[root]);\n\t\t\tif (rep === undefined) reps.set(exact[root], root);\n\t\t\telse walk(rep, root);\n\t\t}\n\t\tgroups[last] = reps.size;\n\t}\n\tfor (let round = 1; round < runouts.rounds; round++) roots[round] = rootsByRound[round].length;\n\n\treturn { alias, roots, groups };\n}\n","/**\n * The betting tree from a spot's settings (issue #115).\n *\n * Purpose: one place that turns `SpotConfig`'s betting into the tree\n * builder's settings, for `defineSpot` and for the presets, which compare the\n * caller's tree with their own to report the sizes they cut.\n */\n\nimport { parseCards } from './cards.ts';\nimport type { SpotConfig } from './index.ts';\nimport type { BetSize, PerPlayer, Tree } from './tree.ts';\nimport { buildTree, isPerPlayer } from './tree.ts';\n\n/** Sub-chip resolution, so pot-fraction sizing is exact: units per chip unless `SpotConfig.chipScale` says otherwise. */\nexport const DEFAULT_CHIP_SCALE = 100;\n\n/** `config.betSizes` as one row per round for each player, checked against the board's rounds. */\nexport function betRows(config: SpotConfig, rounds: number): PerPlayer<readonly (readonly BetSize[])[]> {\n\tconst rowsFor = (sizes: readonly (readonly BetSize[])[], who: string): readonly (readonly BetSize[])[] => {\n\t\tconst expanded = sizes.length === 1 ? Array.from({ length: rounds }, () => sizes[0]) : sizes;\n\t\tif (expanded.length !== rounds) {\n\t\t\tthrow new Error(\n\t\t\t\t`${who}betSizes has ${sizes.length} rows but this board has ${rounds} ` +\n\t\t\t\t\t'betting rounds; give one row per round, or a single row for all of them',\n\t\t\t);\n\t\t}\n\t\treturn expanded;\n\t};\n\treturn isPerPlayer(config.betSizes)\n\t\t? { oop: rowsFor(config.betSizes.oop, 'oop '), ip: rowsFor(config.betSizes.ip, 'ip ') }\n\t\t: rowsFor(config.betSizes, '');\n}\n\n/** The tree builder's settings for `config`, sizes given as `betRows` gives them. */\nexport function treeConfig(config: SpotConfig, rows: PerPlayer<readonly (readonly BetSize[])[]>): Parameters<typeof buildTree>[0] {\n\tconst chipScale = config.chipScale ?? DEFAULT_CHIP_SCALE;\n\treturn {\n\t\tpotUnits: Math.round(config.pot * chipScale),\n\t\tstackUnits: Math.round(config.stack * chipScale),\n\t\tbetSizes: rows,\n\t\traiseSizes: config.raiseSizes,\n\t\tmaxRaises: config.maxRaises ?? 1,\n\t\tallowAllIn: config.allowAllIn ?? false,\n\t\tallInThreshold: config.allInThreshold,\n\t\tnoDonk: config.noDonk,\n\t\tmergeSizes: config.mergeSizes,\n\t\tremoveActions: config.removeActions,\n\t\tthinSizes: config.thinSizes,\n\t\tchipScale,\n\t\tminRaiseUnits: chipScale,\n\t};\n}\n\n/**\n * The betting tree `defineSpot(config)` would build, alone: no ranges,\n * runouts or storage, so it is cheap for any tree, and `maxBytes` is not\n * checked.\n */\nexport function bettingTree(config: SpotConfig): Tree {\n\tconst rounds = 6 - parseCards(config.board).length;\n\tif (rounds < 1 || rounds > 3) throw new Error(`A postflop board has 3, 4 or 5 cards; got ${config.board}`);\n\treturn buildTree(treeConfig(config, betRows(config, rounds)), { rounds });\n}\n","/**\n * Nested subgame re-solving (issue #47).\n *\n * Purpose: refine one player's strategy below a node of a solved spot — a\n * blueprint whose later streets were simplified to fit — by solving that\n * subgame again with a richer tree. Opt-in: nothing else in the solver calls\n * this.\n *\n * `Solution.subgameAt` already builds the subgame; this solves it with the\n * ranges the blueprint brings to the node held fixed (unsafe re-solving), and\n * can measure what each opponent hand gets against the result next to what it\n * had against the blueprint.\n *\n * Nested: a re-solved subgame is a `Solution` like any other, so a node below\n * it can be re-solved from it in turn.\n *\n * Measured (issue #47; Ks 9s 4s, a flop blueprint with three flop sizes and\n * one turn/river size, its turns re-solved at three sizes with raises,\n * against a full-tree reference): an opponent's best response under the\n * reference's ranges gained, weighted by how often each turn is reached,\n * about 3.5–4% of the subgame's pot against plain re-solving, and more\n * against every safe gadget tried (4.2–6.2%: Burch, Johanson & Bowling's\n * re-solve gadget and Moravčík et al.'s and Brown & Sandholm's maxmargin\n * ones). Most of what is left is the refined player's own range at the node,\n * which comes from the blueprint and which no gadget changes, so the gadgets\n * were removed before 0.5.0 (issue #125). To make re-solves from a shared\n * blueprint trustworthy, keep the busiest lines unshared\n * (`ShareHistories.keepLines` with `linesWithin`).\n */\n\nimport { COMBO_CARDS, COMBOS } from './cards.ts';\nimport type { Solution, SolveOptions, SubgameBetting } from './index.ts';\nimport { createRun, defineSpot } from './index.ts';\nimport type { Context } from './cfr.ts';\nimport { makeBuffers, Mode, traverse } from './cfr.ts';\n\n/** Settings for {@link resolveSubgame}. */\nexport interface ResolveOptions {\n\t/** The player whose strategy is refined. */\n\treadonly player: 0 | 1;\n\t/** The subgame's betting; unset, the blueprint's carries over. */\n\treadonly betting?: SubgameBetting;\n\t/** Iterations to run. Default 200. */\n\treadonly iterations?: number;\n\t/**\n\t * Also report `alternative` and `entered`, at the cost of a best-response\n\t * pass over the blueprint below the node and one over the subgame.\n\t */\n\treadonly measure?: boolean;\n\t/** Solver settings for the subgame; `iterations` and warm starts are this function's. */\n\treadonly solve?: Pick<SolveOptions, 'workers' | 'precision' | 'algorithm' | 'engine' | 'simd' | 'wasmStorage'>;\n}\n\n/** A re-solved subgame. */\nexport interface ResolvedSubgame {\n\t/**\n\t * The subgame's solution. Its ranges are the ones the blueprint brings to\n\t * the node; read the refined player's strategy from it.\n\t */\n\treadonly solution: Solution;\n\treadonly player: 0 | 1;\n\t/**\n\t * Each opponent hand's best-response value at the node against the\n\t * blueprint, in chips on `Solver.valuesAt`'s half-pot baseline (not\n\t * `Solution.ev`'s share of the pot), indexed like `COMBO_CARDS`; NaN off\n\t * its range.\n\t * Null unless `measure`.\n\t */\n\treadonly alternative: Float64Array | null;\n\t/**\n\t * Each opponent hand's best-response value in the re-solved subgame\n\t * against the refined strategy, in chips; NaN off its range. Where it\n\t * exceeds `alternative` the re-solve gave that hand more than the\n\t * blueprint did. Null unless `measure`.\n\t */\n\treadonly entered: Float64Array | null;\n\treadonly iterations: number;\n}\n\n/**\n * Re-solve the subgame at a node of `blueprint` for one player.\n *\n * @param blueprint a solved spot\n * @param node a decision opening a betting round (see `Solution.subgameAt`)\n * @param board the board index at that node's round\n */\nexport function resolveSubgame(blueprint: Solution, node: number, board: number, options: ResolveOptions): ResolvedSubgame {\n\tconst { player } = options;\n\tconst opponent = (1 - player) as 0 | 1;\n\tconst iterations = options.iterations ?? 200;\n\tif (!(Number.isInteger(iterations) && iterations > 0)) {\n\t\tthrow new Error(`iterations must be a positive whole number; got ${iterations}`);\n\t}\n\tconst spot = defineSpot(blueprint.subgameAt(node, board, options.betting));\n\tconst base = spot.players[opponent].weights;\n\tconst mine = spot.players[player].weights;\n\t// Mass of the refined player's range each opponent hand does not block.\n\tconst open = options.measure === true ? openMass(mine) : null;\n\n\t// The blueprint's values below the node, worked out before the\n\t// subgame's storage and threads are taken.\n\tconst live = liveCombos(spot.players);\n\tconst blueprintValues = open ? bestResponseAt(blueprint.solver.ctx, node, board, opponent, base, mine) : null;\n\n\tconst run = createRun(spot, { ...options.solve });\n\ttry {\n\t\trun.step(iterations);\n\t\tlet alternative: Float64Array | null = null;\n\t\tlet entered: Float64Array | null = null;\n\t\tif (open && blueprintValues) {\n\t\t\tconst { ctx } = run.solver;\n\t\t\tconst deals = ctx.runoutWeight[0];\n\t\t\talternative = new Float64Array(COMBOS).fill(Number.NaN);\n\t\t\tfor (const combo of live) {\n\t\t\t\tif (base[combo] > 0 && open[combo] > 0) alternative[combo] = blueprintValues[combo] / (open[combo] * deals);\n\t\t\t}\n\t\t\t// Each opponent hand's best response to the refined strategy, by\n\t\t\t// the traversal's root hands.\n\t\t\tconst lists = ctx.active;\n\t\t\tconst slot = lists.roundBase[0] * 2 + opponent;\n\t\t\tconst from = lists.start[slot];\n\t\t\tconst response = run.solver.root(Mode.BestResponse, opponent, 0);\n\t\t\tentered = new Float64Array(COMBOS).fill(Number.NaN);\n\t\t\tfor (let i = 0; i < lists.count[slot]; i++) {\n\t\t\t\tconst combo = lists.list[from + i];\n\t\t\t\tif (!Number.isFinite(alternative[combo])) continue;\n\t\t\t\tconst chips = response[i] / (open[combo] * deals);\n\t\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) entered[lists.memberCombo[m]] = chips;\n\t\t\t}\n\t\t}\n\t\treturn { solution: run.snapshot(), player, alternative, entered, iterations };\n\t} finally {\n\t\trun.close();\n\t}\n}\n\n/**\n * Best-response values below `node`, as `Solver.valuesAt` gives average\n * ones. A best response is not linear in the opponent's reach, so the reach\n * must be the same for mirrored hands, as any reach a solve produces is.\n */\nexport function bestResponseAt(ctx: Context, node: number, board: number, traverser: 0 | 1, reachMe: Float64Array, reachOpp: Float64Array): Float64Array {\n\tconst lists = ctx.active;\n\tconst round = ctx.tree.round[node];\n\tconst listOf = (player: 0 | 1): [number, number] => {\n\t\tconst slot = (lists.roundBase[round] + board) * 2 + player;\n\t\treturn [lists.start[slot], lists.count[slot]];\n\t};\n\tconst gather = (source: Float64Array, player: 0 | 1): Float64Array => {\n\t\tconst [from, count] = listOf(player);\n\t\tconst into = new Float64Array(COMBOS);\n\t\tfor (let i = 0; i < count; i++) into[i] = source[lists.list[from + i]];\n\t\treturn into;\n\t};\n\tconst opponent = (1 - traverser) as 0 | 1;\n\tconst [oppFrom, oppCount] = listOf(opponent);\n\tfor (let j = 0; j < oppCount; j++) {\n\t\tconst own = reachOpp[lists.list[oppFrom + j]];\n\t\tfor (let m = lists.memberStart[oppFrom + j] + 1; m < lists.memberStart[oppFrom + j + 1]; m++) {\n\t\t\tif (reachOpp[lists.memberCombo[m]] !== own) throw new Error('Best-response values need reach that mirrored hands share');\n\t\t}\n\t}\n\t// Mirrored deals below need not see symmetric reach, so they are walked.\n\tconst expanded = ctx.expandOrbits;\n\tctx.expandOrbits = true;\n\ttry {\n\t\tconst buffers = makeBuffers(ctx.tree, ctx.layout.maxActions, ctx.simd);\n\t\tconst value = traverse(ctx, buffers, Mode.BestResponse, traverser, 0, node, board, gather(reachMe, traverser), gather(reachOpp, opponent), 0);\n\t\tconst result = new Float64Array(COMBOS);\n\t\tconst [from, count] = listOf(traverser);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tfor (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) result[lists.memberCombo[m]] = value[i];\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\tctx.expandOrbits = expanded;\n\t}\n}\n\n/** Combinations either player holds. */\nfunction liveCombos(players: readonly { readonly weights: Float64Array }[]): Uint16Array {\n\tconst live: number[] = [];\n\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\tif (players[0].weights[combo] > 0 || players[1].weights[combo] > 0) live.push(combo);\n\t}\n\treturn Uint16Array.from(live);\n}\n\n/**\n * For each combination, the mass of `range` it does not block. Summed\n * directly rather than by inclusion-exclusion over cards, so a hand with\n * nothing to face gets exactly zero, not a rounding residue that passes a\n * `> 0` check and is then divided by.\n */\nexport function openMass(range: Float64Array): Float64Array {\n\tconst held: number[] = [];\n\tfor (let h = 0; h < COMBOS; h++) if (range[h] > 0) held.push(h);\n\tconst open = new Float64Array(COMBOS);\n\tfor (let h = 0; h < COMBOS; h++) {\n\t\tconst a = COMBO_CARDS[h * 2];\n\t\tconst b = COMBO_CARDS[h * 2 + 1];\n\t\tlet mass = 0;\n\t\tfor (const other of held) {\n\t\t\tconst c = COMBO_CARDS[other * 2];\n\t\t\tconst d = COMBO_CARDS[other * 2 + 1];\n\t\t\tif (c !== a && c !== b && d !== a && d !== b) mass += range[other];\n\t\t}\n\t\topen[h] = mass;\n\t}\n\treturn open;\n}\n","/**\n * Hybrid history sharing (issue #101): share later-street storage between\n * histories except along the lines most often played.\n *\n * Purpose: a solve with `shareHistories` keeps its flop play, but the ranges\n * it brings to a turn are trained against river values that several\n * histories share, so a turn re-solved from it starts from distorted ranges.\n * `ShareHistories.keepLines` gives named lines storage of their own, and\n * `turnLineReach` ranks the flop lines by how often they are reached, and\n * `linesWithin` picks the most-reached ones a storage budget allows.\n */\n\nimport type { Precision, Solution, SpotConfig } from './index.ts';\nimport { defineSpot, storageCost } from './index.ts';\nimport { matchupMass } from './cfr.ts';\nimport { NodeKind } from './tree.ts';\n\n/** A flop line opening the turn, and its share of the root's hand pairs. */\nexport interface LineReach {\n\t/** The turn's first decision, as `Solution.path` names it, e.g. `\"check check /\"`. */\n\treadonly line: string;\n\t/** The turn's first decision node. */\n\treadonly node: number;\n\t/** Weighted hand pairs reaching the turn by this line over those at the root, 0 to 1. */\n\treadonly share: number;\n}\n\n/**\n * Every line from the spot's first round into the next, most reached first.\n * Reach comes from the average strategy, so take it from a solve that has\n * run a while; the order settles long before the strategy does.\n */\nexport function turnLineReach(solution: Solution): LineReach[] {\n\tconst { tree, players } = solution.spot;\n\tif (solution.spot.runouts.rounds < 2) return [];\n\tconst rootMass = matchupMass(players[0].weights, players[1].weights);\n\tconst lines: LineReach[] = [];\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (tree.kind[node] !== NodeKind.Chance || tree.round[node] !== 0) continue;\n\t\tconst child = tree.edgeChild[tree.firstEdge[node]];\n\t\tif (tree.kind[child] !== NodeKind.Decision) continue;\n\t\t// Only the first round's decisions lie on the path, so any board serves.\n\t\tconst share = matchupMass(solution.reachAt(child, 0, 0), solution.reachAt(child, 0, 1)) / rootMass;\n\t\tlines.push({ line: solution.path(child), node: child, share });\n\t}\n\treturn lines.sort((a, b) => b.share - a.share);\n}\n\n/**\n * The most-reached lines of `solution` (`turnLineReach`) that\n * `ShareHistories.keepLines` can keep in `options.config` with its storage\n * at `options.precision` (compact storage included) at most `maxBytes`: the\n * longest prefix of the ranking that fits, with any lines the config already\n * keeps. Throws if the spot is over budget keeping only those. Keeping a line never shrinks storage, so the\n * prefix is found by bisection.\n *\n * The spot the lines are for, `options.config`, defaults to the one\n * `solution` solved. The ranking can come from a cheaper spot with the same first\n * round: the reach of a flop line is the flop play alone, so a solve with\n * the river checked down ranks the lines much as the real one does, in a\n * fraction of its memory (see `ShareHistories.keepLines`).\n */\nexport function linesWithin(solution: Solution, maxBytes: number, options: LinesWithinOptions = {}): string[] {\n\tconst config = options.config ?? solution.spot.source;\n\tconst precision = options.precision ?? 'f32';\n\tconst asked = config.shareHistories;\n\tif (!asked) throw new Error('linesWithin picks lines to keep out of shareHistories; this spot shares nothing');\n\tconst share = asked === true ? {} : asked;\n\tconst ranked = turnLineReach(solution).map((l) => l.line);\n\tconst lines = (count: number): string[] => [...new Set([...(share.keepLines ?? []), ...ranked.slice(0, count)])];\n\tconst bytes = (count: number): number =>\n\t\tstorageCost(defineSpot({ ...config, maxBytes: Number.MAX_SAFE_INTEGER, shareHistories: { ...share, keepLines: lines(count) } }), precision);\n\tconst least = bytes(0);\n\tif (least > maxBytes) {\n\t\tthrow new Error(`linesWithin: the spot needs ${least} bytes keeping no more lines, over the budget of ${maxBytes}`);\n\t}\n\t// bytes(low) fits; find the largest count that does.\n\tlet low = 0;\n\tlet high = ranked.length;\n\twhile (low < high) {\n\t\tconst mid = Math.ceil((low + high) / 2);\n\t\tif (bytes(mid) <= maxBytes) low = mid;\n\t\telse high = mid - 1;\n\t}\n\treturn lines(low);\n}\n\n/** Settings for {@link linesWithin}. */\nexport interface LinesWithinOptions {\n\t/** The spot the lines are kept in; unset, the one the ranking solution solved. */\n\treadonly config?: SpotConfig;\n\t/** The precision the spot will be solved at, which the budget is for; default 'f32'. */\n\treadonly precision?: Precision;\n}\n","/*!\n * Vendored from https://github.com/DarraghGeo/poker-rangecompress (dist/range-compress.js) by\n * scripts/vendor-range-compress.ts: an ES module, single-threaded. Do not edit here.\n *\n * range-compress.js — shrink a poker range for a postflop solver while keeping how the range plays.\n *\n * What it does: given a player's range, the opponent's range and a flop, it keeps a subset of the combos\n * and re-weights them so that, on every turn and river the solver will deal, the range still has the same\n * distribution of hand strength. The result is an ordinary range (combos with weights 0..1).\n *\n * What it preserves: how often the range as a whole takes each action, and how its strong / medium / weak\n * parts act. What it does not preserve: what an individual combo does (see README).\n *\n * No dependencies. Works in browsers (global `RangeCompress`), web workers and Node (CommonJS).\n * Cards are 4*rank+suit with rank 0..12 = 2..A and suit 0..3 = c,d,h,s.\n *\n * Speed notes (v2): hands are never evaluated one by one. On each board the 91 rank classes are valued once\n * from rank-count bit masks (the suit-lane idea of poker-bitvaljs), flushes are patched in from a 13-bit\n * lane table, equities with exact card removal come from per-card prefix tables instead of sorting, and\n * the linear algebra works on suit orbits with a Cholesky inverse and triangular updates.\n */\nfunction factory() {\n\n\tconst RANKS = '23456789TJQKA', SUITS = 'cdhs';\n\tconst cardFromStr = (s) => RANKS.indexOf(s[0]) * 4 + SUITS.indexOf(s[1]);\n\tconst cardToStr = (c) => RANKS[c >> 2] + SUITS[c & 3];\n\tconst handToStr = (a, b) => (a > b ? cardToStr(a) + cardToStr(b) : cardToStr(b) + cardToStr(a));\n\tconst hid = (h) => h.a * 52 + h.b;\n\tconst cls = (h) => { const r1 = h.a >> 2, r2 = h.b >> 2, hi = Math.max(r1, r2), lo = Math.min(r1, r2); return (h.a & 3) === (h.b & 3) ? hi * 13 + lo : lo * 13 + hi; };\n\n\t/** Parses \"[w]AhKh, ...[/w], AsKs, ...\" (weights in percent) into [{a,b,w}] with a<b, w in 0..1. */\n\tfunction parseRange(text) {\n\t\tconst out = new Map();\n\t\tconst re = /\\[(\\d+(?:\\.\\d+)?)\\]([^\\[]*)\\[\\/\\1\\]|([^\\[\\],\\s]+)/g;\n\t\tlet m;\n\t\tconst add = (tok, w) => {\n\t\t\ttok = tok.trim();\n\t\t\tif (!tok) return;\n\t\t\tif (tok.length !== 4) throw new Error('unsupported token ' + tok);\n\t\t\tlet a = cardFromStr(tok.slice(0, 2)), b = cardFromStr(tok.slice(2, 4));\n\t\t\tif (a > b) { const t = a; a = b; b = t; }\n\t\t\tout.set(a * 52 + b, { a, b, w });\n\t\t};\n\t\twhile ((m = re.exec(text))) {\n\t\t\tif (m[2] !== undefined) { const w = parseFloat(m[1]) / 100; const parts = m[2].split(','); for (let i = 0; i < parts.length; i++) add(parts[i], w); }\n\t\t\telse add(m[3], 1);\n\t\t}\n\t\treturn [...out.values()].filter((h) => h.w > 0).sort((x, y) => x.a - y.a || x.b - y.b);\n\t}\n\n\tfunction rangeToString(hands) {\n\t\tconst groups = new Map();\n\t\tfor (const h of hands) {\n\t\t\tconst k = (Math.round(h.w * 10000) / 100).toFixed(2);\n\t\t\tif (!groups.has(k)) groups.set(k, []);\n\t\t\tgroups.get(k).push(handToStr(h.a, h.b));\n\t\t}\n\t\tconst parts = [];\n\t\tfor (const [k, v] of [...groups.entries()].sort((x, y) => x[0] - y[0])) {\n\t\t\tif (k === '100.00') parts.push(v.join(', '));\n\t\t\telse parts.unshift('[' + k + ']' + v.join(', ') + '[/' + k + ']');\n\t\t}\n\t\treturn parts.join(', ');\n\t}\n\n\t// ------------------------------------------------------------------ WebAssembly kernels (optional)\n\t// The feature matrix, the matrix inverse and the elimination updates also exist as WebAssembly (SIMD) and are\n\t// used when available; the JavaScript versions below are the reference and the fallback, and give identical\n\t// results. Source: assembly/kernels.ts, embedded here by js/build-wasm.js.\n\tconst KERNELS_B64 = 'AGFzbQEAAAABQAdgBH9/f38Bf2AHf39/f39/fwF/YAV/f39/fwF/YAV/f39/fwBgBH9/f38AYAF/AGANf39/f39/f39/f39/fAACDwEDZW52Bm1lbW9yeQIAAAMIBwABAgMEBQYGEAN/AUEAC38BQQALfwFBAAsHSwcJaW52ZXJ0U1BEAAQHb2JzUGljawACCW9ic1JlbW92ZQABCGFkZFN0YXRlAAYEbm5scwADCmVxdWl0eVBhc3MABQZtZW1vcnkCAArJNgelAwEBfyADBEBBHyADZ2siAUEQdEGAgMADckEfIABBfiABd3Fna0EMdHIPCyABIAJBf3NxIQEgAgRAIAJBfkEfIAJnayICd3EiAwRAIAJBEHRBgICAA3JBHyADZ2tBDHRyDwsgAQRAIAJBEHRBgICAA3JBHyABZ2tBDHRyDwsjASAAaiwAACIBQQBOBEAgAUEQdEGAgIACcg8LIAJBEHRBgIDAAXJBHyAAQX4gAndxIgBnayIBQQx0ckEfIABBfiABd3Fna0EIdHIPCyMBIABqLAAAIgJBAE4EQCACQRB0QYCAgAJyDwsgAQRAIAFBfkEfIAFnayIBdyICcSIDBEAgAUEQdEGAgIABckEfIANnayIBQQx0ckEfIAAgAnFBfiABd3Fna0EIdHIPC0EfQX5BHyAAQX4gAXdxIgBnayICdyAAcSIAZ2shAyABQRB0QYCAwAByIAJBDHRyIANBCHRyQR8gAEF+IAN3cWdrQQR0cg8LQRAhAQNAIAFBAE4EQCAEQR8gAGdrIgIgAXRyIQQgAEF+IAJ3cSEAIAFBBGshAQwBCwsgBAv6BAMGfwN8AXsgBCAGQQJ0aigCACABIAZsIQsDQCAGIAdOBEAgBSAHQQN0aiAAIAcgC2pBA3RqKwMAOQMAIAdBAWohBwwBCwsgBkEBaiEHA0AgAiAHSgRAIA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qIR4MAQsLCyA7QQFqITsMAQsLC6sFAgd/AnwgBEECayENIARBAWu3IRQDQCAEIA5KBEAgCCAOQQJ0akEANgIAIA5BAWohDgwBCwsDQCACIA9KBEAgACABIA9BAnRqKAIAQQJ0Ig5qKgIAuyIVIBVhBEAgAyAOaigCACERIA1EAAAAAAAAAABEAAAAAAAA8D8gFSAVRAAAAAAAAPA/ZBsgFUQAAAAAAAAAAGMbIBSiIhX8AiIOSARAIA0hDgsgFSAOt6EiFUQAAAAAAADwP2MEQCAFIA5sIRIgCCAOQQJ0aigCACITBH8gBiASIBNqQQFrQQJ0aigCACARRgVBAAsEQCAHIBIgE2pBAWtBA3RqIhIgEisDAEQAAAAAAADwPyAVoaA5AwAFIAYgEiATaiISQQJ0aiARNgIAIAcgEkEDdGpEAAAAAAAA8D8gFaE5AwAgCCAOQQJ0aiATQQFqNgIACwsgFUQAAAAAAAAAAGQEQCAOQQFqIg4gBWwhEiAIIA5BAnRqKAIAIhMEfyAGIBIgE2pBAWtBAnRqKAIAIBFGBUEACwRAIAcgEiATakEBa0EDdGoiDiAOKwMAIBWgOQMABSAGIBIgE2oiEkECdGogETYCACAHIBJBA3RqIBU5AwAgCCAOQQJ0aiATQQFqNgIACwsLIA9BAWohDwwBCwsDQCAEIBBKBEAgBSAQbCIAIAggEEECdGooAgBqIQIDQCAAIAJIBEAgCiAGIABBAnRqKAIAIgFBA3RqIgMgAysDACAHIABBA3RqKwMAIhQgDKIiFSAUoqA5AwAgCSABIAtsQQN0aiEDIABBAWohAQNAIAEgAkgEQCADIAYgAUECdGooAgBBA3RqIg0gDSsDACAVIAcgAUEDdGorAwCioDkDACABQQFqIQEMAQsLIABBAWohAAwBCwsgEEEBaiEQDAELCws=';\n\tlet WK = null, arena = false, wasmOn = true, wasmP = null; const FULL = { full: true };\n\tfunction wasm() {\n\t\tif (WK !== null) return WK; WK = false;\n\t\tif (!KERNELS_B64 || typeof WebAssembly === 'undefined') return WK;\n\t\tlet bin, mem, imports;\n\t\tconst setup = (inst) => {\n\t\t\t// lookup tables for the equity kernel sit just below the arena\n\t\t\tnew Uint8Array(mem.buffer, 16384, 8192).set(POPC); new Int8Array(mem.buffer, 16384 + 8192, 8192).set(STRT); new Int32Array(mem.buffer, 16384 + 16384, 8192).set(FLUSHV);\n\t\t\treturn { mem, ex: inst.exports, top: 65536, limit: 0, buf: null, tab: 16384 };\n\t\t};\n\t\ttry {\n\t\t\tbin = typeof atob === 'function' ? Uint8Array.from(atob(KERNELS_B64), (c) => c.charCodeAt(0)) : new Uint8Array(Buffer.from(KERNELS_B64, 'base64'));\n\t\t\tmem = new WebAssembly.Memory({ initial: 64 }); imports = { env: { memory: mem, abort() {} } };\n\t\t\tWK = setup(new WebAssembly.Instance(new WebAssembly.Module(bin), imports));\n\t\t} catch (e) {\n\t\t\t// browsers refuse to compile a module this size synchronously on the main thread: do it in the background\n\t\t\t// and use the JavaScript path until it is ready\n\t\t\tWK = false;\n\t\t\ttry { if (bin && mem) wasmP = WebAssembly.instantiate(bin, imports).then((r) => { WK = setup(r.instance); return true; }, () => false); } catch (e2) { wasmP = null; }\n\t\t}\n\t\treturn WK;\n\t}\n\t/** Lets go of the WebAssembly memory (tens of megabytes after a large call). The next call sets it up again,\n\t * which takes about a millisecond. For memory-tight callers; workers keep their own. */\n\tfunction releaseMemory() { if (!arena) { WK = null; wasmP = null; } }\n\t/** Resolves to true once the WebAssembly kernels are usable on this thread (false if they are not supported). */\n\tfunction ready() { const w = wasm(); return w ? Promise.resolve(true) : wasmP || Promise.resolve(false); }\n\t/** Runs fn with the big arrays placed in WebAssembly memory (so the kernels can work on them in place). The\n\t * memory is reused by the next call, so nothing made inside may be kept except plain results. */\n\tfunction withArena(bytes, fn) {\n\t\tconst w = wasmOn && !arena ? wasm() : false; if (!w) return fn();\n\t\ttry {\n\t\t\tconst need = 65536 + bytes, have = w.mem.buffer.byteLength; if (need > have) w.mem.grow(Math.ceil((need - have) / 65536));\n\t\t\tw.top = 65536; w.buf = w.mem.buffer; w.limit = w.buf.byteLength; arena = true;\n\t\t\treturn fn();\n\t\t} catch (e) { if (e !== FULL) throw e; arena = false; return fn(); } finally { arena = false; }\n\t}\n\t/** A typed array: in WebAssembly memory while an arena is open, an ordinary one otherwise. */\n\tfunction mk(Type, n, zero) {\n\t\tif (!arena) return new Type(n);\n\t\tconst p = (WK.top + 15) & ~15, bytes = n * Type.BYTES_PER_ELEMENT; if (p + bytes > WK.limit) throw FULL;\n\t\tWK.top = p + bytes; const a = new Type(WK.buf, p, n); if (zero) a.fill(0); return a;\n\t}\n\tconst inW = (a) => arena && a.buffer === WK.buf;\n\n\t// ------------------------------------------------------------------ hand values\n\t// A value is category * 2^20 + up to five rank nibbles; higher is better.\n\tconst POPC = new Uint8Array(8192), STRT = new Int8Array(8192).fill(-1), FLUSHV = new Int32Array(8192);\n\tconst top5 = (m) => { let v = 0; for (let sh = 16; sh >= 0; sh -= 4) { const r = 31 - Math.clz32(m); v |= r << sh; m &= ~(1 << r); } return v; };\n\tfor (let m = 1; m < 8192; m++) {\n\t\tPOPC[m] = POPC[m >> 1] + (m & 1);\n\t\tfor (let hi = 12; hi >= 4; hi--) if (((m >> (hi - 4)) & 31) === 31) { STRT[m] = hi; break; }\n\t\tif (STRT[m] < 0 && (m & 0x100f) === 0x100f) STRT[m] = 3;\n\t}\n\tfor (let m = 1; m < 8192; m++) if (POPC[m] >= 5) FLUSHV[m] = STRT[m] >= 0 ? (8 << 20) | (STRT[m] << 16) : (5 << 20) | top5(m);\n\n\t/** Value of the best non-flush hand, from masks of the ranks held at least 1, 2, 3 and 4 times. */\n\tfunction rankEval(m1, m2, m3, m4) {\n\t\tif (m4) { const q = 31 - Math.clz32(m4); return (7 << 20) | (q << 16) | ((31 - Math.clz32(m1 & ~(1 << q))) << 12); }\n\t\tconst pairs = m2 & ~m3;\n\t\tif (m3) {\n\t\t\tconst t = 31 - Math.clz32(m3); const rest = m3 & ~(1 << t);\n\t\t\tif (rest) return (6 << 20) | (t << 16) | ((31 - Math.clz32(rest)) << 12);\n\t\t\tif (pairs) return (6 << 20) | (t << 16) | ((31 - Math.clz32(pairs)) << 12);\n\t\t\tconst st = STRT[m1]; if (st >= 0) return (4 << 20) | (st << 16);\n\t\t\tlet r = m1 & ~(1 << t); const k1 = 31 - Math.clz32(r); r &= ~(1 << k1);\n\t\t\treturn (3 << 20) | (t << 16) | (k1 << 12) | ((31 - Math.clz32(r)) << 8);\n\t\t}\n\t\tconst st = STRT[m1]; if (st >= 0) return (4 << 20) | (st << 16);\n\t\tif (pairs) {\n\t\t\tconst p1 = 31 - Math.clz32(pairs); const rest = pairs & ~(1 << p1);\n\t\t\tif (rest) { const p2 = 31 - Math.clz32(rest); return (2 << 20) | (p1 << 16) | (p2 << 12) | ((31 - Math.clz32(m1 & ~(1 << p1) & ~(1 << p2))) << 8); }\n\t\t\tlet r = m1 & ~(1 << p1); const k1 = 31 - Math.clz32(r); r &= ~(1 << k1); const k2 = 31 - Math.clz32(r); r &= ~(1 << k2);\n\t\t\treturn (1 << 20) | (p1 << 16) | (k1 << 12) | (k2 << 8) | ((31 - Math.clz32(r)) << 4);\n\t\t}\n\t\treturn top5(m1);\n\t}\n\n\t/** Reference evaluator for seven cards (slow path, used for checks only). */\n\tfunction eval7(c0, c1, c2, c3, c4, c5, c6) {\n\t\tconst cs = [c0, c1, c2, c3, c4, c5, c6]; const lane = [0, 0, 0, 0]; let m1 = 0, m2 = 0, m3 = 0, m4 = 0;\n\t\tfor (const c of cs) { const bit = 1 << (c >> 2); lane[c & 3] |= bit; if (m3 & bit) m4 |= bit; else if (m2 & bit) m3 |= bit; else if (m1 & bit) m2 |= bit; else m1 |= bit; }\n\t\tlet v = rankEval(m1, m2, m3, m4);\n\t\tfor (let s = 0; s < 4; s++) if (POPC[lane[s]] >= 5 && FLUSHV[lane[s]] > v) v = FLUSHV[lane[s]];\n\t\treturn v;\n\t}\n\n\t// ------------------------------------------------------------------ boards\n\t/** Boards the solver will deal, with multiplicities. `flop` is the starting board: a flop, a flop and turn, or\n\t * all five cards. Every entry of `rivers` is a complete board, written as the two cards that follow the first\n\t * three of the starting board; `base` is those first three and `fixed` the starting board's other cards.\n\t * blankMask = suits dealt as one representative per rank (flops only). */\n\tfunction deckStates(flop, blankMask = 0) {\n\t\tif (flop.length > 3) {\n\t\t\tif (blankMask) throw new Error('blankSuits is only for a three-card flop');\n\t\t\tconst base = flop.slice(0, 3), fixed = flop.slice(3), rivers = [];\n\t\t\tif (fixed.length === 2) rivers.push([Math.min(fixed[0], fixed[1]), Math.max(fixed[0], fixed[1]), 1]);\n\t\t\telse for (let y = 0; y < 52; y++) if (!flop.includes(y)) rivers.push([Math.min(fixed[0], y), Math.max(fixed[0], y), 1]);\n\t\t\treturn { rivers, turns: [], blankMask: 0, base, fixed };\n\t\t}\n\t\tconst fm = new Set(flop); const blank = (s) => (blankMask >> s) & 1;\n\t\tconst fc = [0, 0, 0, 0]; flop.forEach((c) => fc[c & 3]++);\n\t\tconst pri = [0, 1, 2, 3].filter(blank).sort((x, y) => fc[x] - fc[y] || x - y);\n\t\tconst proxy = (card, dead) => { if (!blank(card & 3)) return card; for (const s of pri) { const c = (card & ~3) | s; if (!dead.has(c)) return c; } throw new Error('no proxy'); };\n\t\tconst tw = new Map();\n\t\tfor (let x = 0; x < 52; x++) if (!fm.has(x)) { const t = proxy(x, fm); tw.set(t, (tw.get(t) || 0) + 1); }\n\t\tconst rivers = [], rIdx = new Map(), turns = [];\n\t\tfor (const [t, wt] of tw) {\n\t\t\tconst dead = new Set(flop); dead.add(t); const rw = new Map();\n\t\t\tfor (let y = 0; y < 52; y++) if (!dead.has(y)) { const u = proxy(y, dead); rw.set(u, (rw.get(u) || 0) + 1); }\n\t\t\tconst rivs = [];\n\t\t\tfor (const [u, wu] of rw) {\n\t\t\t\tconst key = Math.min(t, u) * 52 + Math.max(t, u);\n\t\t\t\tif (!rIdx.has(key)) { rIdx.set(key, rivers.length); rivers.push([Math.min(t, u), Math.max(t, u), 0]); }\n\t\t\t\tconst i = rIdx.get(key); rivers[i][2] += wt * wu; rivs.push([i, wu]);\n\t\t\t}\n\t\t\tturns.push({ card: t, w: wt, rivs });\n\t\t}\n\t\treturn { rivers, turns, blankMask, base: flop, fixed: [] };\n\t}\n\t/** Names board k of `st.rivers` by the cards dealt after the starting board, after the suit relabelling p. */\n\tfunction dealtKey(st, k, p) {\n\t\tconst r = st.rivers[k], fx = st.fixed; let a = -1, b = -1;\n\t\tfor (let q = 0; q < 2; q++) { let c = r[q]; if (fx.length && fx.includes(c)) continue; if (p) c = (c & ~3) | p[c & 3]; if (a < 0) a = c; else b = c; }\n\t\treturn b < 0 ? a : a < b ? a * 52 + b + 52 : b * 52 + a + 52;\n\t}\n\n\t// ------------------------------------------------------------------ equities for both players in one pass\n\tconst DCAP = 91 + 64;\n\n\tfunction side(h, other, R, T, want) {\n\t\tconst n = h.length; const o = new Map(); for (const x of other) o.set(hid(x), x.w);\n\t\tconst s = { hands: h, n, want, ca: mk(Uint8Array, n), cb: mk(Uint8Array, n), cl: mk(Uint8Array, n), w: mk(Float64Array, n), same: mk(Float64Array, n), id: mk(Uint8Array, n), dd: mk(Uint8Array, n),\n\t\t\tstart: mk(Int32Array, DCAP + 3), ord: mk(Int32Array, n), totC: mk(Float64Array, 52), tot: 0,\n\t\t\tE: want ? mk(Float32Array, R * n).fill(NaN) : null, fS: mk(Float64Array, n, true), fW: mk(Float64Array, n, true), tS: want ? mk(Float64Array, T * n, true) : null, tW: want ? mk(Float64Array, T * n, true) : null };\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst a = h[i].a, b = h[i].b; s.ca[i] = a; s.cb[i] = b; s.w[i] = h[i].w; s.same[i] = o.get(hid(h[i])) || 0;\n\t\t\tconst r1 = a >> 2, r2 = b >> 2, hi = r1 > r2 ? r1 : r2, lo = r1 > r2 ? r2 : r1; s.cl[i] = (hi * (hi + 1)) / 2 + lo;\n\t\t}\n\t\treturn s;\n\t}\n\n\t/** River equity of every hand of each range against the other range, on every board, with exact card removal.\n\t * Returns for each side: E (board-major, NaN where the hand is dead), flop equity, turn equities. */\n\tfunction equitiesBoth(hA, hB, flop, states, wantA = true, wantB = true, perms = null, only = null) {\n\t\tconst R = states.rivers.length, T = states.turns.length;\n\t\tconst S = [side(hA, hB, R, T, wantA), side(hB, hA, R, T, wantB)];\n\t\t// Mirrored boards (suit permutations that fix the flop, when both ranges are symmetric): the equities on a\n\t\t// mirrored board are those of the original with the hands relabelled, so only one board of each set is worked out.\n\t\tconst mir = [];\n\t\tif (perms && perms.length > 1) {\n\t\t\tconst ridx = new Map(states.rivers.map((r, k) => [dealtKey(states, k), k]));\n\t\t\tfor (const p of perms) {\n\t\t\t\tif (p[0] === 0 && p[1] === 1 && p[2] === 2 && p[3] === 3) continue;\n\t\t\t\tconst bmap = mk(Int32Array, R); for (let k = 0; k < R; k++) bmap[k] = ridx.get(dealtKey(states, k, p));\n\t\t\t\tconst hmap = S.map((s) => { const idx = new Map(s.hands.map((h, i) => [hid(h), i])); const out = mk(Int32Array, s.n); s.hands.forEach((h, i) => { let a = (h.a & ~3) | p[h.a & 3], b = (h.b & ~3) | p[h.b & 3]; if (a > b) { const t = a; a = b; b = t; } out[i] = idx.get(a * 52 + b); }); return out; });\n\t\t\t\tmir.push({ bmap, hmap });\n\t\t\t}\n\t\t}\n\t\t// boards already dealt with; when `only` is given (one slice of the boards), every other board starts as done\n\t\tconst done = mk(Uint8Array, R, true); if (only) for (let k = 0; k < R; k++) done[k] = only[k] ? 0 : 1;\n\t\t// rank classes that occur in either range\n\t\tconst present = mk(Uint8Array, 91, true); for (const s of S) for (let i = 0; i < s.n; i++) present[s.cl[i]] = 1;\n\t\t// which turn cards each river board belongs to\n\t\tconst t1 = mk(Int32Array, R).fill(-1), t2 = mk(Int32Array, R).fill(-1), u1 = mk(Float64Array, R, true), u2 = mk(Float64Array, R, true);\n\t\tstates.turns.forEach((t, ti) => { for (const [k, wu] of t.rivs) { if (t1[k] < 0) { t1[k] = ti; u1[k] = wu; } else { t2[k] = ti; u2[k] = wu; } } });\n\t\tconst fl = [0, 0, 0, 0]; let f1 = 0, f2 = 0, f3 = 0, f4 = 0;\n\t\tfor (const c of states.base || flop) { const bit = 1 << (c >> 2); fl[c & 3] |= bit; if (f3 & bit) f4 |= bit; else if (f2 & bit) f3 |= bit; else if (f1 & bit) f2 |= bit; else f1 |= bit; }\n\t\tconst cv = mk(Int32Array, 91), keys = mk(Float64Array, DCAP), denseOf = mk(Uint8Array, DCAP);\n\t\tconst fStamp = mk(Int32Array, 8192).fill(-1), fSlot = mk(Uint8Array, 8192), lane = new Int32Array(4), ltC = mk(Float64Array, 52, true), eqC = mk(Float64Array, 52, true);\n\t\tif (arena && WK.ex.equityPass) {\n\t\t\t// hand the whole pass to WebAssembly: a block of fields for the pass and one per side (see assembly/kernels.ts)\n\t\t\tconst rT = mk(Uint8Array, R), rR = mk(Uint8Array, R), rW = mk(Float64Array, R); for (let k = 0; k < R; k++) { rT[k] = states.rivers[k][0]; rR[k] = states.rivers[k][1]; rW[k] = states.rivers[k][2]; }\n\t\t\tconst sb = S.map((s) => { const tot = mk(Float64Array, 1), b = mk(Int32Array, 18); const o = (a) => (a ? a.byteOffset : 0);\n\t\t\t\tb.set([s.n, s.want ? 1 : 0, o(s.ca), o(s.cb), o(s.cl), o(s.w), o(s.same), o(s.id), o(s.dd), o(s.start), o(s.ord), o(s.totC), o(s.E), o(s.fS), o(s.fW), o(s.tS), o(s.tW), o(tot)]); return b; });\n\t\t\tconst mb = mk(Int32Array, Math.max(1, mir.length * 3)); mir.forEach((x, q) => { mb[q * 3] = x.bmap.byteOffset; mb[q * 3 + 1] = x.hmap[0].byteOffset; mb[q * 3 + 2] = x.hmap[1].byteOffset; });\n\t\t\tconst pb = mk(Int32Array, 32);\n\t\t\tpb.set([R, mir.length, rT.byteOffset, rR.byteOffset, rW.byteOffset, t1.byteOffset, t2.byteOffset, u1.byteOffset, u2.byteOffset, done.byteOffset, present.byteOffset, cv.byteOffset, keys.byteOffset, denseOf.byteOffset, fStamp.byteOffset, fSlot.byteOffset, ltC.byteOffset, eqC.byteOffset,\n\t\t\t\tfl[0], fl[1], fl[2], fl[3], f1, f2, f3, f4, sb[0].byteOffset, sb[1].byteOffset, mb.byteOffset, WK.tab, WK.tab + 8192, WK.tab + 16384]);\n\t\t\tWK.ex.equityPass(pb.byteOffset);\n\t\t} else for (let k = 0; k < R; k++) {\n\t\t\tif (done[k]) continue;\n\t\t\tconst t = states.rivers[k][0], r = states.rivers[k][1], wgt = states.rivers[k][2];\n\t\t\t// rank masks and suit lanes of the board\n\t\t\tlet m1 = f1, m2 = f2, m3 = f3, m4 = f4; lane[0] = fl[0]; lane[1] = fl[1]; lane[2] = fl[2]; lane[3] = fl[3];\n\t\t\tlet bit = 1 << (t >> 2); lane[t & 3] |= bit; if (m3 & bit) m4 |= bit; else if (m2 & bit) m3 |= bit; else if (m1 & bit) m2 |= bit; else m1 |= bit;\n\t\t\tbit = 1 << (r >> 2); lane[r & 3] |= bit; if (m3 & bit) m4 |= bit; else if (m2 & bit) m3 |= bit; else if (m1 & bit) m2 |= bit; else m1 |= bit;\n\t\t\t// value of each rank class on this board (suits ignored)\n\t\t\tlet c = 0, nk = 0;\n\t\t\tfor (let hi = 0; hi < 13; hi++) {\n\t\t\t\tconst bh = 1 << hi; let a1 = m1, a2 = m2, a3 = m3, a4 = m4;\n\t\t\t\tif (a3 & bh) a4 |= bh; else if (a2 & bh) a3 |= bh; else if (a1 & bh) a2 |= bh; else a1 |= bh;\n\t\t\t\tfor (let lo = 0; lo <= hi; lo++) {\n\t\t\t\t\tconst bl = 1 << lo; let b1 = a1, b2 = a2, b3 = a3, b4 = a4;\n\t\t\t\t\tif (b3 & bl) b4 |= bl; else if (b2 & bl) b3 |= bl; else if (b1 & bl) b2 |= bl; else b1 |= bl;\n\t\t\t\t\tif (!present[c]) { c++; continue; }\n\t\t\t\t\tconst v = rankEval(b1, b2, b3, b4); cv[c] = v; keys[nk++] = v * 256 + c; c++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// flush suit, if the board holds three or more of one suit\n\t\t\tlet F = -1, need = 9, fLane = 0;\n\t\t\tfor (let s = 0; s < 4; s++) if (POPC[lane[s]] >= 3) { F = s; fLane = lane[s]; need = 5 - POPC[lane[s]]; }\n\t\t\tlet slot = 91;\n\t\t\tfor (let p = 0; p < 2; p++) {\n\t\t\t\tconst s = S[p], n = s.n, ca = s.ca, cb = s.cb, cl = s.cl, id = s.id;\n\t\t\t\tif (F < 0) { for (let i = 0; i < n; i++) { const a = ca[i], b = cb[i]; id[i] = a === t || a === r || b === t || b === r ? 255 : cl[i]; } }\n\t\t\t\telse {\n\t\t\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\t\t\tconst a = ca[i], b = cb[i];\n\t\t\t\t\t\tif (a === t || a === r || b === t || b === r) { id[i] = 255; continue; }\n\t\t\t\t\t\tlet cnt = 0, mk = fLane; if ((a & 3) === F) { cnt++; mk |= 1 << (a >> 2); } if ((b & 3) === F) { cnt++; mk |= 1 << (b >> 2); }\n\t\t\t\t\t\tif (cnt >= need) {\n\t\t\t\t\t\t\tconst fv = FLUSHV[mk];\n\t\t\t\t\t\t\tif (fv > cv[cl[i]]) { if (fStamp[mk] !== k) { fStamp[mk] = k; fSlot[mk] = slot; keys[nk++] = fv * 256 + slot; slot++; } id[i] = fSlot[mk]; continue; }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tid[i] = cl[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// dense rank of every distinct value on this board\n\t\t\tconst ks = nk === DCAP ? keys : keys.subarray(0, nk); ks.sort();\n\t\t\tlet D = -1, prev = -1;\n\t\t\tfor (let q = 0; q < nk; q++) { const key = ks[q]; const v = (key / 256) >>> 0; if (v !== prev) { D++; prev = v; } denseOf[key - v * 256] = D; }\n\t\t\tD++;\n\t\t\t// order each side's live hands by dense rank (counting sort), and total each side's weight per card\n\t\t\tfor (let p = 0; p < 2; p++) {\n\t\t\t\tconst s = S[p], n = s.n, ca = s.ca, cb = s.cb, id = s.id, dd = s.dd, w = s.w, totC = s.totC, start = s.start, ord = s.ord;\n\t\t\t\tstart.fill(0, 0, D + 2); totC.fill(0); let tot = 0;\n\t\t\t\tfor (let i = 0; i < n; i++) { const x = id[i]; if (x === 255) continue; const d = denseOf[x]; dd[i] = d; start[d + 2]++; const wi = w[i]; totC[ca[i]] += wi; totC[cb[i]] += wi; tot += wi; }\n\t\t\t\tfor (let d = 2; d <= D + 1; d++) start[d] += start[d - 1];\n\t\t\t\tfor (let i = 0; i < n; i++) { if (id[i] === 255) continue; ord[start[dd[i] + 1]++] = i; } // now start[d]..start[d+1] is group d\n\t\t\t\ts.tot = tot;\n\t\t\t}\n\t\t\t// equity of each hand against the other side: walk both sides in rank order, keeping per-card running weights\n\t\t\tconst ta = t1[k], tb = t2[k], wa = u1[k], wb = u2[k];\n\t\t\tfor (let p = 0; p < 2; p++) {\n\t\t\t\tconst s = S[p]; if (!s.want) continue; const v = S[1 - p];\n\t\t\t\tconst n = s.n, ca = s.ca, cb = s.cb, same = s.same, E = s.E, fS = s.fS, fW = s.fW, tS = s.tS, tW = s.tW, hs = s.start, ho = s.ord;\n\t\t\t\tconst va = v.ca, vb = v.cb, vw = v.w, vs = v.start, vo = v.ord, totC = v.totC, tot = v.tot; const base = k * n, oa = ta * n, ob = tb * n;\n\t\t\t\tltC.fill(0); let ltT = 0;\n\t\t\t\tfor (let d = 0; d < D; d++) {\n\t\t\t\t\tconst v0 = vs[d], v1 = vs[d + 1], h0 = hs[d], h1 = hs[d + 1]; let eqT = 0;\n\t\t\t\t\tif (h0 < h1) {\n\t\t\t\t\t\tfor (let q = v0; q < v1; q++) { const j = vo[q], wj = vw[j]; eqC[va[j]] += wj; eqC[vb[j]] += wj; eqT += wj; }\n\t\t\t\t\t\tfor (let q = h0; q < h1; q++) {\n\t\t\t\t\t\t\tconst i = ho[q], a = ca[i], b = cb[i], sw = same[i];\n\t\t\t\t\t\t\tconst all = tot - totC[a] - totC[b] + sw;\n\t\t\t\t\t\t\tconst e = all > 1e-12 ? (ltT - ltC[a] - ltC[b] + 0.5 * (eqT - eqC[a] - eqC[b] + sw)) / all : 0.5;\n\t\t\t\t\t\t\tE[base + i] = e; fS[i] += wgt * e; fW[i] += wgt;\n\t\t\t\t\t\t\tif (ta >= 0) { tS[oa + i] += wa * e; tW[oa + i] += wa; }\n\t\t\t\t\t\t\tif (tb >= 0) { tS[ob + i] += wb * e; tW[ob + i] += wb; }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (let q = v0; q < v1; q++) { const j = vo[q], wj = vw[j]; const a = va[j], b = vb[j]; ltC[a] += wj; ltC[b] += wj; eqC[a] = 0; eqC[b] = 0; }\n\t\t\t\t\t\tltT += eqT;\n\t\t\t\t\t} else { for (let q = v0; q < v1; q++) { const j = vo[q], wj = vw[j]; ltC[va[j]] += wj; ltC[vb[j]] += wj; ltT += wj; } }\n\t\t\t\t}\n\t\t\t}\n\t\t\t// fill in the mirrored boards\n\t\t\tfor (let q = 0; q < mir.length; q++) {\n\t\t\t\tconst k2 = mir[q].bmap[k]; if (k2 === k || done[k2]) continue; done[k2] = 1;\n\t\t\t\tconst w2 = states.rivers[k2][2], ta2 = t1[k2], tb2 = t2[k2], wa2 = u1[k2], wb2 = u2[k2];\n\t\t\t\tfor (let p = 0; p < 2; p++) {\n\t\t\t\t\tconst s = S[p]; if (!s.want) continue; const n = s.n, id = s.id, E = s.E, hm = mir[q].hmap[p], fS = s.fS, fW = s.fW, tS = s.tS, tW = s.tW; const b1 = k * n, b2 = k2 * n, oa = ta2 * n, ob = tb2 * n;\n\t\t\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\t\t\tif (id[i] === 255) continue; const e = E[b1 + i], j = hm[i]; E[b2 + j] = e; fS[j] += w2 * e; fW[j] += w2;\n\t\t\t\t\t\tif (ta2 >= 0) { tS[oa + j] += wa2 * e; tW[oa + j] += wa2; }\n\t\t\t\t\t\tif (tb2 >= 0) { tS[ob + j] += wb2 * e; tW[ob + j] += wb2; }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn S.map((s) => {\n\t\t\tif (!s.want) return null; const n = s.n;\n\t\t\tconst ef = mk(Float32Array, n), et = mk(Float32Array, T * n);\n\t\t\tfor (let i = 0; i < n; i++) ef[i] = s.fW[i] ? s.fS[i] / s.fW[i] : 0.5;\n\t\t\tfor (let q = 0; q < T * n; q++) et[q] = s.tW[q] ? s.tS[q] / s.tW[q] : NaN;\n\t\t\treturn { E: s.E, ef, et, fS: s.fS, fW: s.fW, tS: s.tS, tW: s.tW };\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------ suit symmetry\n\tconst ALL_PERMS = (() => { const out = []; const rec = (a, rest) => { if (!rest.length) return out.push(a); rest.forEach((x, i) => rec(a.concat(x), rest.filter((_, j) => j !== i))); }; rec([], [0, 1, 2, 3]); return out; })();\n\tfunction flopPerms(flop) {\n\t\tconst key = (cs) => cs.slice().sort((x, y) => x - y).join(','); const k0 = key(flop);\n\t\treturn ALL_PERMS.filter((p) => key(flop.map((c) => (c & ~3) | p[c & 3])) === k0);\n\t}\n\t/** Suit permutations that leave the flop unchanged, and the orbits of the range under them. */\n\tfunction orbits(hero, flop, symmetric) {\n\t\tconst perms = symmetric ? flopPerms(flop) : [[0, 1, 2, 3]];\n\t\tconst idx = new Map(hero.map((h, i) => [hid(h), i])); const orb = new Int32Array(hero.length).fill(-1); const list = [];\n\t\thero.forEach((h, i) => {\n\t\t\tif (orb[i] >= 0) return; const o = list.length, mem = [];\n\t\t\tfor (const p of perms) { let a = (h.a & ~3) | p[h.a & 3], b = (h.b & ~3) | p[h.b & 3]; if (a > b) { const t = a; a = b; b = t; } const j = idx.get(a * 52 + b); if (j !== undefined && orb[j] < 0) { orb[j] = o; mem.push(j); } }\n\t\t\tlist.push(mem);\n\t\t});\n\t\treturn { orb, list, perms };\n\t}\n\t/** True when a range is unchanged by every suit permutation that fixes the flop. */\n\tfunction isSymmetric(hands, perms) {\n\t\tconst idx = new Map(hands.map((h) => [hid(h), h.w]));\n\t\tfor (const p of perms) for (const h of hands) { let a = (h.a & ~3) | p[h.a & 3], b = (h.b & ~3) | p[h.b & 3]; if (a > b) { const t = a; a = b; b = t; } const w = idx.get(a * 52 + b); if (w === undefined || Math.abs(w - h.w) > 1e-9) return false; }\n\t\treturn true;\n\t}\n\n\t// ------------------------------------------------------------------ preparation\n\t/** Everything the matcher needs about both ranges on one flop. Each range is described against the other. */\n\tfunction prepareBoth(hA, hB, flop, states, wantA = true, wantB = true, only = null) {\n\t\tstates = states || deckStates(flop, 0);\n\t\tconst perms = states.blankMask ? [[0, 1, 2, 3]] : flopPerms(flop);\n\t\tconst sym = perms.length > 1 && isSymmetric(hA, perms) && isSymmetric(hB, perms);\n\t\tconst eq = equitiesBoth(hA, hB, flop, states, wantA, wantB, sym ? perms : null, only);\n\t\tconst one = (h, e, v) => e && { hero: h, villain: v, flop, states, n: h.length, R: states.rivers.length, E: e.E, ef: e.ef, et: e.et, boardSym: sym, perms, sums: e };\n\t\treturn [one(hA, eq[0], hB), one(hB, eq[1], hA)];\n\t}\n\tlet lastPair = null;\n\t/** One range against the other (kept for the experiment scripts; the pair is computed once and reused). */\n\tfunction prepare(hero, villain, flop, states) {\n\t\tstates = states || deckStates(flop, 0);\n\t\tif (lastPair && lastPair.states === states && lastPair.a === villain && lastPair.b === hero) return lastPair.res[1];\n\t\tconst res = prepareBoth(hero, villain, flop, states); lastPair = { a: hero, b: villain, states, res }; return res[0];\n\t}\n\n\t/** Weighted RMS distance between two hands' river-equity vectors (only needed for stand-ins). */\n\tfunction distances(P) {\n\t\tif (P.D) return P.D; const { n, R, E, states } = P; const D = new Float32Array(n * n), S2 = new Float64Array(n * n), C2 = new Float64Array(n * n);\n\t\tconst live = new Int32Array(n), ev = new Float64Array(n);\n\t\tfor (let k = 0; k < R; k++) {\n\t\t\tconst w = states.rivers[k][2], base = k * n; let c = 0;\n\t\t\tfor (let i = 0; i < n; i++) { const e = E[base + i]; if (e === e) { live[c] = i; ev[c] = e; c++; } }\n\t\t\tfor (let p = 0; p < c; p++) { const row = live[p] * n, ep = ev[p]; for (let q = p + 1; q < c; q++) { const d = ep - ev[q]; S2[row + live[q]] += w * d * d; C2[row + live[q]] += w; } }\n\t\t}\n\t\tfor (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) { const c = C2[i * n + j]; D[i * n + j] = D[j * n + i] = c ? Math.sqrt(S2[i * n + j] / c) : 1; }\n\t\treturn (P.D = D);\n\t}\n\n\t// ------------------------------------------------------------------ feature Gram matrix (orbit level)\n\t// The features are \"mass of the range in each equity bin on each board\" (hat-shaped bins), summed over suit\n\t// orbits. The Gram matrix of those features is all the elimination needs.\n\n\t/** Orbits, and a function that visits every board state as (equity array, offset, weight). */\n\tfunction walker(P, opts = {}) {\n\t\tconst B = opts.bins || 16, sw = opts.streetWeights || [1, 1, 1]; const symmetric = opts.symmetric !== false && !P.states.blankMask;\n\t\tconst rsOpt = opts.riverSample || 1; const key = B + '|' + sw.join(',') + '|' + symmetric + '|' + rsOpt; if (P.walkKey === key) return P.walk;\n\t\tconst { hero, flop, n, R, states } = P; const ob = orbits(hero, flop, symmetric);\n\t\tconst list = [['ef', 0, sw[0]]];\n\t\tconst tw = states.turns.reduce((s, t) => s + t.w, 0); states.turns.forEach((t, ti) => list.push(['et', ti * n, (sw[1] * t.w) / tw]));\n\t\t// river boards (optionally every rs-th one, weights rescaled); mirrored boards contribute the same thing at\n\t\t// orbit level, so one of each mirrored set is used and scaled\n\t\tconst rws = [], rks = []; const mirrored = symmetric && P.boardSym && ob.perms.length > 1;\n\t\tconst done = new Uint8Array(R), ridx = mirrored ? new Map(states.rivers.map((r, k) => [dealtKey(states, k), k])) : null, repQ = new Int32Array(R);\n\t\tfor (let k = 0; k < R; k++) {\n\t\t\tif (done[k]) continue; let wsum = states.rivers[k][2]; repQ[k] = rks.length;\n\t\t\tif (mirrored) { wsum = 0; for (const p of ob.perms) { const j = ridx.get(dealtKey(states, k, p)); if (!done[j]) { done[j] = 1; repQ[j] = rks.length; wsum += states.rivers[j][2]; } } }\n\t\t\trks.push(k); rws.push(wsum);\n\t\t}\n\t\t// 'auto' keeps at least about 300 distinct river boards\n\t\tconst rs = rsOpt === 'auto' ? Math.max(1, Math.min(3, Math.floor(rks.length / 300))) : rsOpt;\n\t\tlet rw = 0; const use = []; for (let q = 0; q < rks.length; q++) if (q % rs === 0) { use.push(q); rw += rws[q]; }\n\t\t// entries are [which array ('ef', 'et' or 'E'), offset, weight]; river entries also carry their set's number\n\t\tconst rivers = use.map((q) => ['E', rks[q] * n, (sw[2] * rws[q]) / rw, q]);\n\t\tP.walkKey = key; P.gramKey = null; P.walk = { key, B, ob, m: ob.list.length, fixed: list, rivers, sets: rks.length, repQ };\n\t\treturn P.walk;\n\t}\n\n\t/** Puts one state's hands into bins. `order` lists the hands to use and `keyOf` their target index; hands with\n\t * the same key that arrive together in a bin are merged. */\n\tfunction fillBins(arr, off, order, cnt, keyOf, B, n, binK, binV, binN) {\n\t\tconst Bm1 = B - 1, Bm2 = B - 2; binN.fill(0);\n\t\tfor (let q = 0; q < cnt; q++) {\n\t\t\tconst i = order[q]; const e = arr[off + i]; if (e !== e) continue; const o = keyOf[i];\n\t\t\tconst x = (e < 0 ? 0 : e > 1 ? 1 : e) * Bm1; let b0 = x | 0; if (b0 > Bm2) b0 = Bm2; const f = x - b0;\n\t\t\tif (f < 1) { const base = b0 * n, c = binN[b0]; if (c && binK[base + c - 1] === o) binV[base + c - 1] += 1 - f; else { binK[base + c] = o; binV[base + c] = 1 - f; binN[b0] = c + 1; } }\n\t\t\tif (f > 0) { const b1 = b0 + 1, base = b1 * n, c = binN[b1]; if (c && binK[base + c - 1] === o) binV[base + c - 1] += f; else { binK[base + c] = o; binV[base + c] = f; binN[b1] = c + 1; } }\n\t\t}\n\t}\n\t/** Adds v v' * lam for the entries [from, to) of one bin into U (pairs once, above the diagonal) and diag. */\n\tfunction addPairs(U, diag, stride, binK, binV, from, to, lam) {\n\t\tfor (let p = from; p < to; p++) {\n\t\t\tconst op = binK[p], v = binV[p], vp = v * lam, row = op * stride; diag[op] += vp * v; let q = p + 1;\n\t\t\tfor (const e = to - 3; q < e; q += 4) { U[row + binK[q]] += vp * binV[q]; U[row + binK[q + 1]] += vp * binV[q + 1]; U[row + binK[q + 2]] += vp * binV[q + 2]; U[row + binK[q + 3]] += vp * binV[q + 3]; }\n\t\t\tfor (; q < to; q++) U[row + binK[q]] += vp * binV[q];\n\t\t}\n\t}\n\tconst symmetrize = (U, diag, m) => { for (let a = 0; a < m; a++) { U[a * m + a] = diag[a] + 2 * U[a * m + a]; for (let b = a + 1; b < m; b++) { const v = U[a * m + b] + U[b * m + a]; U[a * m + b] = v; U[b * m + a] = v; } } return U; };\n\n\t/** Adds the given states to U (pairs once, above the diagonal) and diag; makes them if not supplied. */\n\tfunction accumulate(P, W, entries, U, diag) {\n\t\tconst { n } = P, { B, ob, m } = W, orb = ob.orb;\n\t\tconst order = mk(Int32Array, n); { let c = 0; for (const mem of ob.list) for (const i of mem) order[c++] = i; }\n\t\tU = U || mk(Float64Array, m * m, true); diag = diag || mk(Float64Array, m, true);\n\t\tconst binK = mk(Int32Array, B * n), binV = mk(Float64Array, B * n), binN = mk(Int32Array, B);\n\t\tconst src = (e) => P[e[0]];\n\t\tif (entries.length && inW(U) && entries.every((e) => inW(src(e)))) {\n\t\t\tconst key = mk(Int32Array, n); key.set(orb); const ex = WK.ex;\n\t\t\tfor (const e of entries) ex.addState(src(e).byteOffset + e[1] * 4, order.byteOffset, n, key.byteOffset, B, n, binK.byteOffset, binV.byteOffset, binN.byteOffset, U.byteOffset, diag.byteOffset, m, e[2]);\n\t\t} else for (const e of entries) { fillBins(src(e), e[1], order, n, orb, B, n, binK, binV, binN); for (let b = 0; b < B; b++) addPairs(U, diag, m, binK, binV, b * n, b * n + binN[b], e[2]); }\n\t\treturn { U, diag };\n\t}\n\n\t/** The whole Gram matrix. */\n\tfunction gram(P, opts = {}) {\n\t\tconst W = walker(P, opts); if (P.gramKey === W.key) return P.gramRes;\n\t\tconst a = accumulate(P, W, W.fixed.concat(W.rivers)); const Go = symmetrize(a.U, a.diag, W.m);\n\t\tif (P.states.fixed && P.states.fixed.length === 2 && P.villain) addOpponentSide(P, W, Go);\n\t\tP.gramKey = W.key; P.gramRes = { Go, ob: W.ob, m: W.m }; return P.gramRes;\n\t}\n\n\t/** River spots only. With no cards to come, a histogram of equity on the one board says too little: what the\n\t * other player's hands face is what matters. This adds features from their side: for every hand they hold,\n\t * how much of the range beats it, ties it and loses to it, leaving out the hands that share a card with it.\n\t * Go (the histograms' matrix, orbit level) becomes the sum of both, each scaled to weigh the same.\n\t *\n\t * Two hands of the range fall in the same group against an opponent hand when it is weaker than both,\n\t * stronger than both, or tied with both. So each pair's entry is the opponent weight in those strength\n\t * bands, less the hands holding one of the pair's cards (running sums per card, by strength). */\n\tfunction addOpponentSide(P, W, Go) {\n\t\tconst { hero, villain, n } = P, bd = P.states.base.concat(P.states.fixed), m = W.m, orb = W.ob.orb, nv = villain.length;\n\t\tconst hv = hero.map((h) => eval7(h.a, h.b, bd[0], bd[1], bd[2], bd[3], bd[4])), vv = villain.map((h) => eval7(h.a, h.b, bd[0], bd[1], bd[2], bd[3], bd[4]));\n\t\tconst vals = Array.from(new Set(hv.concat(vv))).sort((x, y) => x - y), rank = new Map(vals.map((v, d) => [v, d])), D = vals.length, D1 = D + 1;\n\t\tconst cumT = new Float64Array(D1), cumC = new Float64Array(52 * D1), at = new Int32Array(52 * 52).fill(-1), vr = new Int32Array(nv), vw = new Float64Array(nv);\n\t\tlet vt = 0; for (const v of villain) vt += v.w; if (!(vt > 0)) return;\n\t\tvillain.forEach((v, j) => { const d = rank.get(vv[j]), w = v.w / vt; vr[j] = d; vw[j] = w; cumT[d + 1] += w; cumC[v.a * D1 + d + 1] += w; cumC[v.b * D1 + d + 1] += w; at[v.a * 52 + v.b] = j; at[v.b * 52 + v.a] = j; });\n\t\tfor (let d = 1; d <= D; d++) cumT[d] += cumT[d - 1];\n\t\tfor (let c = 0; c < 52; c++) { const o = c * D1; for (let d = 1; d <= D; d++) cumC[o + d] += cumC[o + d - 1]; }\n\t\tconst hr = Int32Array.from(hv, (v) => rank.get(v)), Gv = new Float64Array(m * m), U = [0, 0, 0, 0];\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst a = hero[i].a, b = hero[i].b, ri = hr[i], oi = orb[i];\n\t\t\tfor (let j = i; j < n; j++) {\n\t\t\t\tconst a2 = hero[j].a, b2 = hero[j].b, rj = hr[j], x = ri < rj ? ri : rj, y = ri < rj ? rj : ri, tie = x === y;\n\t\t\t\tlet nu = 2; U[0] = a; U[1] = b; if (a2 !== a && a2 !== b) U[nu++] = a2; if (b2 !== a && b2 !== b) U[nu++] = b2;\n\t\t\t\tlet g = cumT[x] + cumT[D] - cumT[y + 1] + (tie ? cumT[x + 1] - cumT[x] : 0);\n\t\t\t\tfor (let q = 0; q < nu; q++) {\n\t\t\t\t\tconst o = U[q] * D1; g -= cumC[o + x] + cumC[o + D] - cumC[o + y + 1] + (tie ? cumC[o + x + 1] - cumC[o + x] : 0);\n\t\t\t\t\tfor (let r = q + 1; r < nu; r++) { const k = at[U[q] * 52 + U[r]]; if (k >= 0) { const d = vr[k]; if (d < x || d > y || (tie && d === x)) g += vw[k]; } }\n\t\t\t\t}\n\t\t\t\tGv[oi * m + orb[j]] += g; if (j !== i) Gv[orb[j] * m + oi] += g;\n\t\t\t}\n\t\t}\n\t\tconst w0 = new Float64Array(m); W.ob.list.forEach((mem, o) => { let t = 0; for (const i of mem) t += hero[i].w; w0[o] = t / mem.length; });\n\t\tconst quad = (M) => { let t = 0; for (let x = 0; x < m; x++) { let r = 0; const o = x * m; for (let y = 0; y < m; y++) r += M[o + y] * w0[y]; t += w0[x] * r; } return t; };\n\t\tconst cv = quad(Gv), ch = quad(Go); if (!(cv > 0) || !(ch > 0)) return;\n\t\tfor (let q = 0; q < m * m; q++) Go[q] = Go[q] / ch + Gv[q] / cv;\n\t}\n\n\t/** Inverse of a symmetric positive definite matrix; only the lower triangle of the result is filled. */\n\tfunction invertSPD(A, m) { // reads only the lower triangle of A\n\t\tconst L = new Float64Array(m * m);\n\t\tfor (let i = 0; i < m; i++) {\n\t\t\tconst ri = i * m;\n\t\t\tfor (let j = 0; j <= i; j++) {\n\t\t\t\tconst rj = j * m; let s0 = A[ri + j], s1 = 0, s2 = 0, s3 = 0, k = 0;\n\t\t\t\tfor (const e = j - 3; k < e; k += 4) { s0 -= L[ri + k] * L[rj + k]; s1 -= L[ri + k + 1] * L[rj + k + 1]; s2 -= L[ri + k + 2] * L[rj + k + 2]; s3 -= L[ri + k + 3] * L[rj + k + 3]; }\n\t\t\t\tfor (; k < j; k++) s0 -= L[ri + k] * L[rj + k];\n\t\t\t\tconst s = s0 + s1 + s2 + s3;\n\t\t\t\tL[ri + j] = i === j ? Math.sqrt(s > 0 ? s : 1e-300) : s / L[rj + j];\n\t\t\t}\n\t\t}\n\t\t// X = inverse of L (lower triangular), built row by row\n\t\tconst X = new Float64Array(m * m);\n\t\tfor (let i = 0; i < m; i++) {\n\t\t\tconst ri = i * m, d = 1 / L[ri + i];\n\t\t\tfor (let k = 0; k < i; k++) {\n\t\t\t\tconst f = L[ri + k]; if (!f) continue; const rk = k * m; let j = 0;\n\t\t\t\tfor (const e = k - 2; j < e; j += 4) { X[ri + j] -= f * X[rk + j]; X[ri + j + 1] -= f * X[rk + j + 1]; X[ri + j + 2] -= f * X[rk + j + 2]; X[ri + j + 3] -= f * X[rk + j + 3]; }\n\t\t\t\tfor (; j <= k; j++) X[ri + j] -= f * X[rk + j];\n\t\t\t}\n\t\t\tfor (let j = 0; j < i; j++) X[ri + j] *= d; X[ri + i] = d;\n\t\t}\n\t\t// P = X' X, lower triangle\n\t\tconst Pm = L.fill(0);\n\t\tfor (let k = 0; k < m; k++) {\n\t\t\tconst rk = k * m;\n\t\t\tfor (let a = 0; a <= k; a++) {\n\t\t\t\tconst xa = X[rk + a]; if (!xa) continue; const ra = a * m; let b = 0;\n\t\t\t\tfor (const e = a - 2; b < e; b += 4) { Pm[ra + b] += xa * X[rk + b]; Pm[ra + b + 1] += xa * X[rk + b + 1]; Pm[ra + b + 2] += xa * X[rk + b + 2]; Pm[ra + b + 3] += xa * X[rk + b + 3]; }\n\t\t\t\tfor (; b <= a; b++) Pm[ra + b] += xa * X[rk + b];\n\t\t\t}\n\t\t}\n\t\treturn Pm;\n\t}\n\n\t// ------------------------------------------------------------------ elimination\n\t/** Elimination state over the variables `idx` of the matrix M (dim x dim): the inverse of their ridged Gram\n\t * block, kept compact, and their current weights. Position q holds variable act[q]. Starts from `w0`, or from\n\t * the least-squares fit to `bvec` when w0 is null. */\n\tfunction obsState(M, dim, idx, eps, w0, bvec) {\n\t\tconst k = idx.length, A = mk(Float64Array, k * k);\n\t\tfor (let q = 0; q < k; q++) { const o = idx[q] * dim, r = q * k; for (let p = 0; p <= q; p++) A[r + p] = M[o + idx[p]]; A[r + q] += eps; }\n\t\tlet Pm; if (arena) { Pm = mk(Float64Array, k * k); const X = mk(Float64Array, k * k); WK.ex.invertSPD(A.byteOffset, Pm.byteOffset, X.byteOffset, k); } else Pm = invertSPD(A, k);\n\t\tconst wp = mk(Float64Array, k);\n\t\tif (w0) for (let q = 0; q < k; q++) wp[q] = w0[idx[q]];\n\t\telse for (let q = 0; q < k; q++) { let s = 0; const r = q * k; for (let p = 0; p <= q; p++) s += Pm[r + p] * bvec[idx[p]]; for (let p = q + 1; p < k; p++) s += Pm[p * k + q] * bvec[idx[p]]; wp[q] = s; }\n\t\tconst act = mk(Int32Array, k); act.set(idx);\n\t\treturn { Pm, k, na: k, act, wp, col: mk(Float64Array, k), sal: 0, w: arena, salp: arena ? mk(Float64Array, 1) : null };\n\t}\n\t/** Cheapest removal: returns its position, or -1. `st.sal` is the increase in squared error it causes. */\n\tfunction obsPick(st, skip) {\n\t\tconst { Pm, k, na, wp, act } = st;\n\t\tif (st.w && !skip) { const q = WK.ex.obsPick(Pm.byteOffset, k, na, wp.byteOffset, st.salp.byteOffset); st.sal = st.salp[0]; return q; }\n\t\tlet bq = -1, bs = Infinity, sal = 0;\n\t\tfor (let q = 0; q < na; q++) {\n\t\t\tif (skip && skip(act[q])) continue;\n\t\t\tconst wj = wp[q], cost = (wj * wj) / Pm[q * k + q], s = wj < 0 ? -1e30 + wj : cost;\n\t\t\tif (s < bs) { bs = s; bq = q; sal = cost; }\n\t\t}\n\t\tst.sal = sal; return bq;\n\t}\n\t/** Removes position bq, re-fitting the others exactly (rank-one update of the inverse). Returns the variable removed. */\n\tfunction obsRemove(st, bq) {\n\t\tconst { Pm, k, wp, act, col } = st; let na = st.na;\n\t\tif (st.w) { const id = WK.ex.obsRemove(Pm.byteOffset, k, na, wp.byteOffset, act.byteOffset, col.byteOffset, bq); st.na = na - 1; return id; }\n\t\tconst bj = act[bq];\n\t\tconst rb = bq * k; for (let q = 0; q <= bq; q++) col[q] = Pm[rb + q]; for (let q = bq + 1; q < na; q++) col[q] = Pm[q * k + bq];\n\t\tconst pj = col[bq], f = wp[bq] / pj, inv = 1 / pj, last = na - 1;\n\t\tif (bq !== last) {\n\t\t\tconst rl = last * k; for (let q = 0; q < bq; q++) Pm[rb + q] = Pm[rl + q]; for (let q = bq + 1; q < last; q++) Pm[q * k + bq] = Pm[rl + q]; Pm[rb + bq] = Pm[rl + last];\n\t\t\tcol[bq] = col[last]; wp[bq] = wp[last]; act[bq] = act[last];\n\t\t}\n\t\tna = last;\n\t\tfor (let q = 0; q < na; q++) {\n\t\t\tconst ci = col[q]; wp[q] -= f * ci; const s = ci * inv; if (!s) continue; const row = q * k; let p = 0;\n\t\t\tfor (const e = q - 2; p < e; p += 4) { Pm[row + p] -= s * col[p]; Pm[row + p + 1] -= s * col[p + 1]; Pm[row + p + 2] -= s * col[p + 2]; Pm[row + p + 3] -= s * col[p + 3]; }\n\t\t\tfor (; p <= q; p++) Pm[row + p] -= s * col[p];\n\t\t}\n\t\tst.na = na; return bj;\n\t}\n\n\t/** Backward elimination: drop the combos (whole suit orbits) the range can best do without, re-fitting the\n\t * weights of the rest each time. Returns snapshots at the requested sizes, or at the tolerance.\n\t *\n\t * Unless `exact` is set, large ranges are first thinned block by block (orbits grouped by flop equity, each\n\t * block eliminating on its own), and only the survivors go through the exact elimination. This reaches the\n\t * same mismatch for a given size, and neither builds nor inverts the full matrix. */\n\tfunction eliminate(P, opts = {}) {\n\t\tconst T = opts.timing, now = T ? () => Number(process.hrtime.bigint()) / 1e6 : null; let t0 = T ? now() : 0; const lap = (k) => { if (T) { const t = now(); T[k] = (T[k] || 0) + t - t0; t0 = t; } };\n\t\tconst { hero } = P; const W = walker(P, opts), ob = W.ob, m = W.m;\n\t\tconst osize = new Int32Array(m); ob.list.forEach((mem, o) => { osize[o] = mem.length; });\n\t\tconst w0 = new Float64Array(m); ob.list.forEach((mem, o) => { let s = 0; for (const i of mem) s += hero[i].w; w0[o] = s / mem.length; });\n\t\tconst targets = (opts.sizes || []).slice().sort((a, b) => b - a); const tol = opts.tolerance;\n\t\tlet hands = hero.length, cum = 0; const path = [], curve = [];\n\t\t// the Gram matrix, G w0 and w0' G w0\n\t\tlet Go = gram(P, opts).Go; const ocls = ob.list.map((mem) => cls(hero[mem[0]]));\n\t\tif (opts.classMu) { Go = Float64Array.from(Go); for (let i = 0; i < m; i++) for (let j = 0; j < m; j++) if (ocls[i] === ocls[j]) Go[i * m + j] += opts.classMu * osize[i] * osize[j]; }\n\t\tlet clsCount = null, skip = null;\n\t\tif (opts.keepClasses) { clsCount = new Map(); ocls.forEach((c) => clsCount.set(c, (clsCount.get(c) || 0) + 1)); skip = (o) => clsCount.get(ocls[o]) <= 1; }\n\t\tlet tr = 0; for (let i = 0; i < m; i++) tr += Go[i * m + i]; const eps = ((opts.ridge || 1e-6) * tr) / m;\n\t\tconst bl = new Float64Array(m); for (let i = 0; i < m; i++) { let s = 0; const o = i * m; for (let j = 0; j < m; j++) s += Go[o + j] * w0[j]; bl[i] = s; }\n\t\tlet c0 = 0; for (let i = 0; i < m; i++) c0 += w0[i] * bl[i];\n\t\tconst M = Go, dim = m; let st = null; lap('gram');\n\n\t\t// ---- stage 1: block-wise thinning\n\t\tconst blockwise = !opts.exact && !opts.classMu && !opts.keepClasses && !opts.fullCurve && m >= (opts.blockMin || 180) && (targets.length === 1 || (tol !== undefined && !targets.length));\n\t\tif (blockwise) {\n\t\t\tconst feq = new Float64Array(m); ob.list.forEach((mem, o) => { let s = 0; for (const i of mem) s += P.ef[i]; feq[o] = s / mem.length; });\n\t\t\tconst order = Array.from({ length: m }, (_, o) => o).sort((x, y) => feq[x] - feq[y]); const G = Math.max(2, Math.round(m / (opts.blockSize || 110)));\n\t\t\tconst seqs = [];\n\t\t\tfor (let q = 0; q < G; q++) {\n\t\t\t\tconst mark = arena ? WK.top : 0;\n\t\t\t\tconst b = obsState(Go, m, order.slice(Math.floor((q * m) / G), Math.floor(((q + 1) * m) / G)), eps, w0, null), seq = [];\n\t\t\t\twhile (b.na > 1) { const bq = obsPick(b); if (bq < 0) break; const sal = b.sal; seq.push([obsRemove(b, bq), sal]); }\n\t\t\t\tseqs.push(seq); if (arena) WK.top = mark;\n\t\t\t}\n\t\t\tlap('blockElim');\n\t\t\t// take removals from the blocks in order of cost, each block's own order respected\n\t\t\tconst head = new Int32Array(G), gone = new Uint8Array(m); let h1 = hands, c1 = 0;\n\t\t\tconst stopHands = targets.length ? Math.ceil(targets[0] * (opts.blockKeep || 1.25)) : 0, stopCost = tol !== undefined ? (tol * (opts.blockTol || 0.6)) ** 2 * c0 : Infinity;\n\t\t\tfor (;;) {\n\t\t\t\tlet bg = -1, bs = Infinity; for (let q = 0; q < G; q++) if (head[q] < seqs[q].length && seqs[q][head[q]][1] < bs) { bs = seqs[q][head[q]][1]; bg = q; }\n\t\t\t\tif (bg < 0) break; const o = seqs[bg][head[bg]][0];\n\t\t\t\tif (targets.length ? h1 - osize[o] < stopHands : c1 + bs > stopCost) break;\n\t\t\t\tgone[o] = 1; h1 -= osize[o]; c1 += bs; head[bg]++;\n\t\t\t}\n\t\t\tconst keep = []; for (let o = 0; o < m; o++) if (!gone[o]) keep.push(o);\n\t\t\tif (keep.length < m) {\n\t\t\t\tst = obsState(Go, m, keep, eps, null, bl); let e1 = c0; for (let q = 0; q < st.k; q++) e1 -= st.wp[q] * bl[keep[q]];\n\t\t\t\tif (tol !== undefined && Math.sqrt(Math.max(0, e1) / c0) > tol) st = null; else { cum = Math.max(0, e1); hands = h1; }\n\t\t\t}\n\t\t\tlap('stage2init');\n\t\t}\n\t\t// ---- the whole range at once\n\t\tif (!st) { const all = new Int32Array(m); for (let i = 0; i < m; i++) all[i] = i; st = obsState(Go, m, all, eps, w0, null); hands = hero.length; cum = 0; }\n\t\tconst snapshot = () => {\n\t\t\t// non-negative re-fit on the surviving orbits (coordinate descent), then the error of that fit\n\t\t\tconst na = st.na, sup = st.act, ww = new Float64Array(m);\n\t\t\tconst gs = mk(Float64Array, na * na), bs = mk(Float64Array, na), x = mk(Float64Array, na);\n\t\t\tfor (let q = 0; q < na; q++) { const o = sup[q] * dim, r = q * na; bs[q] = bl[sup[q]]; x[q] = st.wp[q] > 0 ? st.wp[q] : 0; for (let p = 0; p < na; p++) gs[r + p] = M[o + sup[p]]; }\n\t\t\tif (arena) WK.ex.nnls(gs.byteOffset, bs.byteOffset, x.byteOffset, na, opts.sweeps || 60);\n\t\t\telse for (let s = 0, S = opts.sweeps || 60; s < S; s++) {\n\t\t\t\tlet moved = 0;\n\t\t\t\tfor (let q = 0; q < na; q++) { const r = q * na, gq = gs[r + q]; let v = bs[q] + gq * x[q]; for (let p = 0; p < na; p++) v -= gs[r + p] * x[p]; v = v > 0 ? v / gq : 0; const d = v - x[q]; if (d > moved) moved = d; else if (-d > moved) moved = -d; x[q] = v; }\n\t\t\t\tif (moved < 1e-12) break;\n\t\t\t}\n\t\t\tlet e = 0, hc = 0;\n\t\t\tfor (let q = 0; q < na; q++) { const o = sup[q]; ww[o] = x[q]; if (!x[q]) continue; hc += osize[o]; const r = q * na; let v = 0; for (let p = 0; p < na; p++) v += gs[r + p] * x[p]; e += x[q] * (v - 2 * bs[q]); }\n\t\t\treturn { hands: hc, err: Math.sqrt(Math.max(0, e + c0) / c0), w: ww };\n\t\t};\n\t\tlap('fullInit'); let ti = 0;\n\t\twhile (st.na > 1) {\n\t\t\twhile (ti < targets.length && hands <= targets[ti]) { path.push(Object.assign({ target: targets[ti] }, snapshot())); ti++; }\n\t\t\tif (ti >= targets.length && tol === undefined && !opts.fullCurve) break;\n\t\t\tconst bq = obsPick(st, skip); if (bq < 0) break; const sal = st.sal;\n\t\t\tif (tol !== undefined && Math.sqrt((cum + sal) / c0) > tol) break;\n\t\t\tconst o = obsRemove(st, bq); if (clsCount) clsCount.set(ocls[o], clsCount.get(ocls[o]) - 1);\n\t\t\thands -= osize[o]; cum += sal;\n\t\t\tif (opts.fullCurve) curve.push([hands, Math.sqrt(cum / c0)]);\n\t\t}\n\t\tlap('stage2elim');\n\t\twhile (ti < targets.length) { path.push(Object.assign({ target: targets[ti] }, snapshot())); ti++; }\n\t\tif (tol !== undefined) path.push(Object.assign({ target: tol }, snapshot()));\n\t\tlap('refit');\n\t\treturn { path, ob, curve };\n\t}\n\n\t/** Turns a snapshot into a normal range (weights scaled so the largest is 1). With `top`, also lists for every\n\t * original combo the surviving combos that stand in for it (nearest first). */\n\tfunction materialize(P, snap, ob, opts = {}) {\n\t\tconst { hero, n } = P; const hands = [], reps = [];\n\t\thero.forEach((h, i) => { const x = snap.w[ob.orb[i]]; if (x > 0) { hands.push({ a: h.a, b: h.b, w: x }); reps.push(i); } });\n\t\tlet mx = 0; for (const h of hands) if (h.w > mx) mx = h.w; for (const h of hands) h.w /= mx;\n\t\tif (!opts.top) return { hands, prefs: null, err: snap.err, scale: 1 / mx };\n\t\tconst D = distances(P);\n\t\tconst key = (i, r) => D[i * n + r] + (opts.sameClass && cls(hero[i]) !== cls(hero[r]) ? 10 : 0);\n\t\tconst prefs = hero.map((h, i) => { const top = reps.slice().sort((x, y) => key(i, x) - key(i, y)).slice(0, opts.top); return [hid(h), top.map((r) => hid(hero[r])), top.map((r) => +key(i, r).toFixed(5))]; });\n\t\tif (opts.transport) {\n\t\t\t// Mass-conserving stand-ins: every original combo spreads over surviving combos so that each surviving\n\t\t\t// combo receives exactly the weight it carries in the compressed range (entropic optimal transport).\n\t\t\tconst m = reps.length, eps = opts.transport; const a = hero.map((h) => h.w), b = hands.map((h) => h.w);\n\t\t\tconst sa = a.reduce((x, y) => x + y, 0), sb = b.reduce((x, y) => x + y, 0);\n\t\t\tconst K = new Float64Array(n * m); for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) K[i * m + j] = Math.exp(-D[i * n + reps[j]] / eps);\n\t\t\tconst u = new Float64Array(n).fill(1), v = new Float64Array(m).fill(1);\n\t\t\tfor (let it = 0; it < (opts.transportIters || 300); it++) {\n\t\t\t\tfor (let i = 0; i < n; i++) { let t = 0; const o = i * m; for (let j = 0; j < m; j++) t += K[o + j] * v[j]; u[i] = a[i] / sa / (t || 1e-300); }\n\t\t\t\tfor (let j = 0; j < m; j++) { let t = 0; for (let i = 0; i < n; i++) t += K[i * m + j] * u[i]; v[j] = b[j] / sb / (t || 1e-300); }\n\t\t\t}\n\t\t\thero.forEach((h, i) => {\n\t\t\t\tconst row = []; let tot = 0; for (let j = 0; j < m; j++) { const x = u[i] * K[i * m + j] * v[j]; if (x > 0) row.push([j, x]); tot += x; }\n\t\t\t\trow.sort((x, y) => y[1] - x[1]); const top = row.slice(0, opts.top);\n\t\t\t\tprefs[i] = [hid(h), top.map((x) => hid(hero[reps[x[0]]])), top.map((x) => +D[i * n + reps[x[0]]].toFixed(5)), top.map((x) => +(x[1] / tot).toFixed(5))];\n\t\t\t});\n\t\t}\n\t\treturn { hands, prefs, err: snap.err, scale: 1 / mx };\n\t}\n\n\t// ------------------------------------------------------------------ public API\n\tconst asHands = (r) => (typeof r === 'string' ? parseRange(r) : r.map((h) => { if (!h.hand) return h; let a = cardFromStr(h.hand.slice(0, 2)), b = cardFromStr(h.hand.slice(2, 4)); if (a > b) { const t = a; a = b; b = t; } return { a, b, w: h.weight }; }));\n\t/** The starting board as card numbers: three, four or five different cards. */\n\tconst asFlop = (f) => {\n\t\tconst txt = typeof f === 'string' ? f.replace(/[\\s,]/g, '') : null;\n\t\tconst b = txt !== null ? (/^([2-9TJQKA][cdhs])*$/.test(txt) ? (txt.match(/../g) || []).map(cardFromStr) : []) : Array.isArray(f) ? f.slice() : [];\n\t\tif (b.length < 3 || b.length > 5 || b.some((c) => !(c >= 0 && c < 52) || c !== Math.floor(c)) || new Set(b).size !== b.length) throw new Error('The board must be three, four or five different cards, like \"Td9d6h\" or \"Td9d6h2c\"; got ' + JSON.stringify(f));\n\t\treturn b;\n\t};\n\tconst boardOf = (o) => asFlop(o.board !== undefined ? o.board : o.flop);\n\tconst asMask = (b) => (!b ? 0 : typeof b === 'number' ? b : b.reduce((m, s) => m | (1 << (typeof s === 'string' ? SUITS.indexOf(s) : s)), 0));\n\tconst liveHands = (hands, flop) => hands.filter((h) => h.w > 0 && !flop.includes(h.a) && !flop.includes(h.b));\n\n\t/** Suits that can be dealt as one representative card per rank on this flop: every suit that cannot\n\t * make a flush by the river without two more cards of it (i.e. all suits with fewer than two flop cards). */\n\tfunction blankSuitsFor(flop) {\n\t\tflop = asFlop(flop); const fc = [0, 0, 0, 0]; flop.forEach((c) => fc[c & 3]++);\n\t\treturn [0, 1, 2, 3].filter((s) => fc[s] < 2).map((s) => SUITS[s]);\n\t}\n\n\t/** Rough expected error of range-level action frequencies (percentage points, averaged over decisions)\n\t * for a given mismatch, from the calibration runs. Indicative only. */\n\tconst expectedFrequencyError = (mismatch) => 0.6 + 60 * mismatch;\n\n\t// upper bound on the WebAssembly memory one call needs: the equities, then one range's matrices at a time\n\t/** Histogram bins: 16, or 64 on a river spot, whose one board has to say more. */\n\tconst binsFor = (o, st) => o.bins || (st.fixed.length === 2 ? 64 : 16);\n\tconst arenaBytes = (nA, nB, st, bins) => { const n = Math.max(nA, nB); return (4 * (st.rivers.length + st.turns.length + 2) + 16 * st.turns.length + 96) * (nA + nB) + 56 * n * n + 16 * (bins || 16) * n + 12 * st.rivers.length * 8 + (4 << 20); };\n\tconst elimOpts = (o, n, sym) => {\n\t\tconst opts = { symmetric: o.symmetric !== false && sym, bins: o.bins, streetWeights: o.streetWeights, exact: o.exact, riverSample: o.riverSample || 'auto' };\n\t\tif (o.size) opts.sizes = [Math.min(o.size, n)]; else opts.tolerance = o.tolerance === undefined ? 0.01 : o.tolerance;\n\t\tif (o.curve) opts.fullCurve = true;\n\t\treturn opts;\n\t};\n\t/** The work for one range: returns plain data (so it can cross a worker boundary). */\n\tfunction solveOne(P, o) {\n\t\t// suit orbits are only used when both ranges are suit-symmetric on this flop (or the flop has no symmetry)\n\t\tconst eo = elimOpts(o, P.n, P.boardSym || P.perms.length === 1); eo.bins = binsFor(o, P.states);\n\t\tconst el = eliminate(P, eo); const m = materialize(P, el.path[0], el.ob, { top: o.standIns || 0 });\n\t\treturn { hands: m.hands, prefs: m.prefs, err: m.err, scale: m.scale, n: P.n, curve: o.curve ? el.curve : undefined };\n\t}\n\tfunction present(r, states) {\n\t\tlet standIns = null;\n\t\tif (r.prefs) { standIns = {}; r.prefs.forEach(([id, list]) => { standIns[handToStr((id / 52) | 0, id % 52)] = list.map((x) => handToStr((x / 52) | 0, x % 52)); }); }\n\t\tconst hands = r.hands;\n\t\treturn {\n\t\t\trange: rangeToString(hands), get pio() { return hands.map((h) => handToStr(h.a, h.b) + ':' + h.w.toFixed(4)).join(','); },\n\t\t\thands: hands.map((h) => ({ hand: handToStr(h.a, h.b), weight: h.w })), size: hands.length, originalSize: r.n,\n\t\t\tmismatch: r.err, expectedFrequencyError: expectedFrequencyError(r.err), standIns, curve: r.curve, weightScale: r.scale,\n\t\t\tdeck: states.blankMask ? { blankSuits: [0, 1, 2, 3].filter((s) => (states.blankMask >> s) & 1).map((s) => SUITS[s]), turnCards: states.turns.length, riverBoards: states.rivers.length } : null,\n\t\t};\n\t}\n\n\t/**\n\t * Compress one player's range.\n\t * @param {object} o\n\t * @param {string|Array} o.range range to compress: \"[50.00]AhKd, ...[/50.00], AsKs, ...\" or [{hand:'AhKd', weight:0.5}]\n\t * @param {string|Array} o.opponent the opponent's (uncompressed) range, same formats\n\t * @param {string|number[]} o.flop the starting board, e.g. \"Td9d6h\"; four cards for a spot that starts on the\n\t * turn, five for the river. `o.board` is the same option.\n\t * @param {number} [o.size] number of combos to keep\n\t * @param {number} [o.tolerance] instead of size: keep the fewest combos whose mismatch stays below this (default 0.01)\n\t * @param {string[]|number} [o.blankSuits] only for a solver that deals these suits as one card per rank (see README); flops only\n\t * @param {boolean} [o.symmetric=true] keep the flop's suit symmetry so the solver's isomorphism still applies\n\t * @param {boolean} [o.exact] run the elimination on the whole range at once (slower, same quality)\n\t * @param {number} [o.riverSample] match on every n-th river board (default: automatic, at most every third;\n\t * 1 uses all of them). Turn and flop are always matched in full.\n\t * @param {number} [o.standIns] also return, for every original combo, this many nearest surviving combos (slower)\n\t * @returns {{range:string, pio:string, hands:Array, size:number, originalSize:number, mismatch:number, expectedFrequencyError:number, standIns:Object}}\n\t */\n\tfunction compress(o) {\n\t\tconst flop = boardOf(o); const hero = liveHands(asHands(o.range), flop), villain = liveHands(asHands(o.opponent), flop);\n\t\tconst states = deckStates(flop, asMask(o.blankSuits));\n\t\treturn present(withArena(arenaBytes(hero.length, 0, states, binsFor(o, states)), () => solveOne(prepareBoth(hero, villain, flop, states, true, false)[0], o)), states);\n\t}\n\n\t/** Compress both players' ranges for one flop in one pass. Each is matched against the other's full range.\n\t * Takes `oop` and `ip` instead of `range` and `opponent`; `sizeOop` / `sizeIp` override `size`. */\n\tfunction compressBoth(o) {\n\t\tconst flop = boardOf(o); const a = liveHands(asHands(o.oop), flop), b = liveHands(asHands(o.ip), flop);\n\t\tconst states = deckStates(flop, asMask(o.blankSuits));\n\t\tconst r = withArena(arenaBytes(a.length, b.length, states, binsFor(o, states)), () => {\n\t\t\tconst P = prepareBoth(a, b, flop, states); const mark = arena ? WK.top : 0;\n\t\t\tconst x = solveOne(P[0], Object.assign({}, o, { size: o.sizeOop || o.size })); if (arena) WK.top = mark;\n\t\t\treturn [x, solveOne(P[1], Object.assign({}, o, { size: o.sizeIp || o.size }))];\n\t\t});\n\t\treturn { oop: present(r[0], states), ip: present(r[1], states) };\n\t}\n\n\treturn {\n\t\tcompress, compressBoth, blankSuitsFor, expectedFrequencyError, parseRange, rangeToString, cardFromStr, cardToStr, handToStr,\n\t\t/** true if the WebAssembly kernels loaded; setWasm(false) forces the JavaScript path */\n\t\tget wasm() { return !!wasm(); }, setWasm(on) { wasmOn = !!on; }, ready, releaseMemory,\n\t};\n}\n\nexport default factory();\n","/**\n * Range compression (issue #156): replace each player's range by a smaller,\n * re-weighted subset of its combinations that keeps the range's distribution\n * of equity on the board and on every board that can follow it. A spot that\n * starts on the river has no board to follow, and there the subset also\n * keeps what each of the other player's hands faces: how much of the range\n * beats it, ties it and loses to it (issue #158).\n *\n * Purpose: a solve's time and memory grow with the combinations in play, and\n * a range can lose a third to a half of them before the range as a whole\n * plays differently. The method is poker-rangecompress's, vendored in\n * `vendor/range-compress.js` (`scripts/vendor-range-compress.ts` copies it\n * in); what it costs under Lite is in `bench/range-compress`.\n *\n * What it keeps is how the range plays: how often it takes each action, and\n * how its strong, middling and weak parts act. What it does not keep is what\n * one combination does: a combination that is left out has no strategy, and\n * the ones kept carry the weight of those that were dropped.\n */\n\nimport { COMBO_CARDS, COMBOS, comboIndex, formatCard, formatCombo, parseCard, parseCards } from './cards.ts';\nimport { parseRange } from './range.ts';\nimport RangeCompress from './vendor/range-compress.js';\nimport type { WeightedHand } from './vendor/range-compress.d.ts';\n\n/** How far {@link compressRanges} may go. */\nexport interface CompressRangesOptions {\n\t/**\n\t * The most mismatch allowed: each range keeps the fewest combinations\n\t * whose equity distributions stay this close to the original's, as a\n\t * fraction of it. Default 0.01 on a flop, which measured about one\n\t * percentage point of difference in how often the range takes an\n\t * action; 0.005 was indistinguishable from solving the full range\n\t * again, 0.02 about two points. Default 0.005 on a spot that starts on\n\t * the turn or the river: under Lite the root play was 0.5–2.6 points\n\t * off there at 0.005 and up to 7.8 at 0.01 (`bench/range-compress`).\n\t */\n\treadonly tolerance?: number;\n\t/** Keep this many combinations of each range (or `[oop, ip]`) instead of working to `tolerance`. */\n\treadonly size?: number | readonly [number, number];\n}\n\n/** What {@link compressRanges} did to one range. */\nexport interface RangeCompression {\n\t/** Combinations with weight before, off the board and at or over `minWeight`. */\n\treadonly from: number;\n\t/** Combinations kept. */\n\treadonly to: number;\n\t/** The mismatch reached: 0 is identical. */\n\treadonly mismatch: number;\n}\n\n/** The compressed ranges of a spot, and what changed. */\nexport interface CompressedRanges {\n\t/** A weight per combination, the largest 1, indexed like `COMBO_CARDS`. */\n\treadonly oop: Float64Array;\n\treadonly ip: Float64Array;\n\t/** Out of position's range, then in position's. */\n\treadonly report: readonly [RangeCompression, RangeCompression];\n}\n\n/**\n * Compress both ranges of a spot, each against the other's full range. The\n * board is where the spot starts: a flop, a flop and turn, or all five cards.\n * Give the ranges the players hold there.\n *\n * Combinations on the board and those under `minWeight` are left out first,\n * as `defineSpot` would. Ranges that are the same in every suit the board\n * treats alike stay so, so the solver's suit symmetry still applies.\n *\n * @throws if the board is not 3, 4 or 5 cards, or a range is empty\n */\nexport function compressRanges(\n\tconfig: { readonly board: string; readonly oop: string | Float64Array; readonly ip: string | Float64Array; readonly minWeight?: number },\n\toptions: CompressRangesOptions = {},\n): CompressedRanges {\n\tconst board = parseCards(config.board);\n\tif (board.length < 3 || board.length > 5) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);\n\tconst tolerance = options.tolerance ?? (board.length === 3 ? 0.01 : 0.005);\n\tif (!(tolerance > 0 && tolerance < 1)) throw new Error(`tolerance must be above 0 and under 1; got ${tolerance}`);\n\tconst sizes = options.size === undefined ? undefined : typeof options.size === 'number' ? ([options.size, options.size] as const) : options.size;\n\tif (sizes && !sizes.every((n) => Number.isInteger(n) && n >= 2)) throw new Error(`size must be whole numbers of at least 2; got ${String(options.size)}`);\n\n\tconst onBoard = new Set(board);\n\tconst floor = config.minWeight ?? 0;\n\tconst live = (range: string | Float64Array, who: string): WeightedHand[] => {\n\t\tconst weights = typeof range === 'string' ? parseRange(range) : range;\n\t\tif (weights.length !== COMBOS) throw new Error(`The ${who} range has ${weights.length} weights; one per combination is ${COMBOS}`);\n\t\tconst kept: number[] = [];\n\t\tlet largest = 0;\n\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\tconst weight = weights[combo];\n\t\t\tif (!(weight > 0) || weight < floor) continue;\n\t\t\tif (onBoard.has(COMBO_CARDS[combo * 2]) || onBoard.has(COMBO_CARDS[combo * 2 + 1])) continue;\n\t\t\tkept.push(combo);\n\t\t\tif (weight > largest) largest = weight;\n\t\t}\n\t\tif (kept.length === 0) throw new Error(`The ${who} range is empty once the board's cards${floor > 0 ? ' and the combinations under minWeight' : ''} are removed`);\n\t\t// Only the weights' ratios matter; the largest at 1 keeps the\n\t\t// compressor's absolute tolerances meaningful for a range given on\n\t\t// any scale.\n\t\treturn kept.map((combo) => ({ hand: formatCombo(combo), weight: weights[combo] / largest }));\n\t};\n\tconst oop = live(config.oop, 'out-of-position');\n\tconst ip = live(config.ip, 'in-position');\n\tlet result: ReturnType<typeof RangeCompress.compressBoth>;\n\ttry {\n\t\tresult = RangeCompress.compressBoth({\n\t\t\toop,\n\t\t\tip,\n\t\t\tboard: board.map(formatCard).join(''),\n\t\t\t...(sizes ? { sizeOop: Math.min(sizes[0], oop.length), sizeIp: Math.min(sizes[1], ip.length) } : { tolerance }),\n\t\t});\n\t} finally {\n\t\t// Its WebAssembly memory, tens of MiB for wide ranges, would\n\t\t// otherwise stay resident beside the solve that follows.\n\t\tRangeCompress.releaseMemory();\n\t}\n\tconst weightsOf = (hands: readonly WeightedHand[]): Float64Array => {\n\t\tconst weights = new Float64Array(COMBOS);\n\t\tfor (const { hand, weight } of hands) weights[comboIndex(parseCard(hand.slice(0, 2)), parseCard(hand.slice(2, 4)))] = weight;\n\t\treturn weights;\n\t};\n\treturn {\n\t\toop: weightsOf(result.oop.hands),\n\t\tip: weightsOf(result.ip.hands),\n\t\treport: [\n\t\t\t{ from: oop.length, to: result.oop.size, mismatch: result.oop.mismatch },\n\t\t\t{ from: ip.length, to: result.ip.size, mismatch: result.ip.mismatch },\n\t\t],\n\t};\n}\n","/**\n * What a preset changed (issue #115).\n *\n * Purpose: `solveLite` and `largeTree` take any caller betting and turn it\n * into a cheaper game. Nothing they do may be silent, so each hands back a\n * `PresetChanges`: the bet, raise and shove sizes its tree no longer offers,\n * found by walking the caller's betting tree beside the preset's, the rounds\n * that lost any, and every other setting it set or dropped, each with a\n * sentence a page can show as it is.\n */\n\nimport { bettingTree } from './betting.ts';\nimport { parseCards } from './cards.ts';\nimport type { SamplingOptions } from './cfr.ts';\nimport type { SpotConfig } from './index.ts';\nimport { ActionKind, NodeKind } from './tree.ts';\nimport type { Tree } from './tree.ts';\n\n/** A betting round by name. */\nexport type Street = 'flop' | 'turn' | 'river';\n\n/** Sizes one player's decisions of one kind lost on one round. */\nexport interface SizesCut {\n\treadonly street: Street;\n\treadonly player: 'oop' | 'ip';\n\t/** 'bet' opens the round's betting; 'raise' answers a bet. */\n\treadonly facing: 'bet' | 'raise';\n\t/**\n\t * The sizes cut, ascending: each a fraction of the pot after a call, to\n\t * two places, as `betSizes` and `raiseSizes` give them, or 'allin'.\n\t * Where the caller's sizes resolve to different chips at different pots,\n\t * one caller size can show as neighbouring fractions.\n\t */\n\treadonly sizes: readonly (number | 'allin')[];\n\t/** The caller's decisions of this kind that lost at least one size. */\n\treadonly decisions: number;\n\t/**\n\t * The caller's decisions of this kind, offering any size, that the\n\t * preset's tree still reaches: those below a cut action are gone with\n\t * it and counted in neither number.\n\t */\n\treadonly of: number;\n}\n\n/** A setting a preset set, changed or dropped. */\nexport interface SettingChange {\n\t/** The setting's name: a `SpotConfig` field, or a `SolveOptions` one (`approximations.chanceSampling`, `precision`, ...). */\n\treadonly setting: string;\n\t/** The caller's value; undefined where it was unset. */\n\treadonly from: unknown;\n\t/** The preset's value; undefined where it dropped it. */\n\treadonly to: unknown;\n}\n\n/** Everything a preset changed against the caller's spot. */\nexport interface PresetChanges {\n\t/** Sizes the preset's tree no longer offers, by street, player and kind. */\n\treadonly sizesCut: readonly SizesCut[];\n\t/** Streets whose betting lost any size: the rounds simplified. */\n\treadonly roundsSimplified: readonly Street[];\n\t/** Every other setting set, changed or dropped, the approximations included. */\n\treadonly settings: readonly SettingChange[];\n\t/** One sentence per change, sizes first, in plain words. */\n\treadonly notes: readonly string[];\n}\n\n/**\n * Every bet, raise and shove the caller's tree offers and `preset`'s does\n * not. The trees are walked side by side, an action matched by its kind and\n * the chips it puts in; below a cut action nothing more is counted, and a\n * line `preset` adds (one the caller cut with `removeActions` below a deal,\n * say) is not walked.\n */\nexport function sizesCut(caller: SpotConfig, preset: SpotConfig): SizesCut[] {\n\tconst from = bettingTree(caller);\n\tconst to = bettingTree(preset);\n\tconst rounds = 6 - parseCards(caller.board).length;\n\tconst streets: readonly Street[] = (['flop', 'turn', 'river'] as const).slice(3 - rounds);\n\tconst groups = new Map<string, { cut: Map<string, number | 'allin'>; decisions: number; of: number }>();\n\n\tconst walk = (a: number, b: number, invested: readonly [number, number]): void => {\n\t\tconst kind = from.kind[a];\n\t\tif (kind === NodeKind.Chance) {\n\t\t\t// One edge each: the deal.\n\t\t\twalk(from.edgeChild[from.firstEdge[a]], to.edgeChild[to.firstEdge[b]], invested);\n\t\t\treturn;\n\t\t}\n\t\tif (kind !== NodeKind.Decision) return;\n\t\tconst me = from.player[a];\n\t\tconst owed = Math.max(0, invested[1 - me] - invested[me]);\n\t\tconst facing = owed > 0 ? 'raise' : 'bet';\n\t\tconst key = `${from.round[a]} ${me} ${facing}`;\n\t\tconst group = groups.get(key) ?? { cut: new Map(), decisions: 0, of: 0 };\n\t\tgroups.set(key, group);\n\t\tconst theirs = edgesOf(to, b);\n\t\tlet sized = false;\n\t\tlet lost = false;\n\t\tfor (let e = from.firstEdge[a]; e < from.firstEdge[a] + from.numEdges[a]; e++) {\n\t\t\tconst action = from.edgeAction[e];\n\t\t\tconst target = from.edgeTarget[e];\n\t\t\tconst aggressive = action === ActionKind.Bet || action === ActionKind.Raise || action === ActionKind.AllIn;\n\t\t\tif (aggressive) sized = true;\n\t\t\tconst match = theirs.get(`${action} ${target}`);\n\t\t\tif (match === undefined) {\n\t\t\t\tif (!aggressive) throw new Error(`sizesCut: the preset's tree lost a fold, check or call at node ${a}`);\n\t\t\t\tlost = true;\n\t\t\t\tconst size = action === ActionKind.AllIn ? 'allin' : fraction(from, a, target, invested, me, owed);\n\t\t\t\tgroup.cut.set(String(size), size);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst next: [number, number] = [invested[0], invested[1]];\n\t\t\tnext[me] = target;\n\t\t\twalk(from.edgeChild[e], to.edgeChild[match], next);\n\t\t}\n\t\tif (sized) group.of++;\n\t\tif (lost) group.decisions++;\n\t};\n\twalk(0, 0, [0, 0]);\n\n\tconst out: SizesCut[] = [];\n\tfor (const [key, group] of groups) {\n\t\tif (group.cut.size === 0) continue;\n\t\tconst [round, player, facing] = key.split(' ');\n\t\tconst sizes = [...group.cut.values()].sort((x, y) => (x === 'allin' ? 1 : y === 'allin' ? -1 : x - y));\n\t\tout.push({\n\t\t\tstreet: streets[Number(round)],\n\t\t\tplayer: player === '0' ? 'oop' : 'ip',\n\t\t\tfacing: facing as 'bet' | 'raise',\n\t\t\tsizes,\n\t\t\tdecisions: group.decisions,\n\t\t\tof: group.of,\n\t\t});\n\t}\n\tconst order = (c: SizesCut): number =>\n\t\tstreets.indexOf(c.street) * 4 + (c.player === 'oop' ? 0 : 2) + (c.facing === 'bet' ? 0 : 1);\n\treturn out.sort((x, y) => order(x) - order(y));\n}\n\n/** A node's edges by action and target. */\nfunction edgesOf(tree: Tree, node: number): Map<string, number> {\n\tconst out = new Map<string, number>();\n\tfor (let e = tree.firstEdge[node]; e < tree.firstEdge[node] + tree.numEdges[node]; e++) {\n\t\tout.set(`${tree.edgeAction[e]} ${tree.edgeTarget[e]}`, e);\n\t}\n\treturn out;\n}\n\n/** A sized action as a fraction of the pot after a call, to two places. */\nfunction fraction(tree: Tree, node: number, target: number, invested: readonly [number, number], me: number, owed: number): number {\n\tconst potAfterCall = tree.pot[node] + owed;\n\treturn Math.round(((target - invested[me] - owed) / potAfterCall) * 100) / 100;\n}\n\n/** Assemble a report: the sizes cut, the rounds they leave simplified, the other settings, and a sentence each. */\nexport function presetChanges(caller: SpotConfig, preset: SpotConfig, settings: readonly SettingChange[], notes: readonly string[]): PresetChanges {\n\tconst cuts = sizesCut(caller, preset);\n\tconst roundsSimplified = (['flop', 'turn', 'river'] as const).filter((s) => cuts.some((c) => c.street === s));\n\tconst sizeNotes = cuts.map((c) => {\n\t\tconst sizes = c.sizes.map((s) => (s === 'allin' ? 'all-in' : String(s))).join(', ');\n\t\tconst who = c.player === 'oop' ? 'OOP' : 'IP';\n\t\tconst what = c.facing === 'bet' ? 'bet' : 'raise';\n\t\treturn `${c.street}: ${who} loses the ${what} size${c.sizes.length > 1 ? 's' : ''} ${sizes} at ${c.decisions} of the ${c.of} such decisions the preset keeps`;\n\t});\n\treturn { sizesCut: cuts, roundsSimplified, settings, notes: [...sizeNotes, ...notes] };\n}\n\n/** What a `chanceSampling` setting does, in a sentence. */\nexport function samplingNote(sampling: SamplingOptions): string {\n\tconst which = sampling.rounds ? `the deals of rounds ${sampling.rounds.join(', ')}` : \"every later round's deals\";\n\treturn sampling.every\n\t\t? `${which} walked once every ${sampling.every} iterations, in rotation`\n\t\t: `${which} sampled at p ${sampling.p ?? 0.35}`;\n}\n","/**\n * Lite mode (issue #100): one opt-in that turns the caller's betting into the\n * phone/laptop blueprint issue #85 measured, solves it until its root play\n * settles, and re-solves later streets at the caller's full betting on demand.\n *\n * Purpose: the recipe needs a dozen settings — the flop betting kept, one\n * size on the turn and river, `shareHistories`, `runoutBuckets`,\n * `chanceSampling`, a stop on the root play rather than on exploitability —\n * and callers should not have to assemble it. Nothing else in the package\n * calls this; unused, it changes nothing.\n *\n * What is measured, and what each default costs, is in `solveLite`'s notes.\n */\n\nimport { parseCards } from './cards.ts';\nimport type { SamplingOptions } from './cfr.ts';\nimport type { CompressRangesOptions } from './compress.ts';\nimport { compressRanges } from './compress.ts';\nimport { linesWithin } from './hybrid.ts';\nimport { activeCombos, parseRange } from './range.ts';\nimport type { ShareHistories, Solution, SolveOptions, SolveRun, SpotConfig, SubgameBetting } from './index.ts';\nimport { createRun, defineSpot, RangeNotInPlaceError, runToStop, solve } from './index.ts';\nimport type { PresetChanges, SettingChange } from './presets.ts';\nimport { presetChanges, samplingNote } from './presets.ts';\nimport type { ResolvedSubgame, ResolveOptions } from './resolve.ts';\nimport { resolveSubgame } from './resolve.ts';\nimport type { SettleOptions } from './settle.ts';\nimport { settlePlan } from './settle.ts';\nimport type { BetSize, PerPlayer, RaiseSizes } from './tree.ts';\nimport { mapPlayers, perRound, raisesPerRound } from './tree.ts';\nimport { warmStart } from './warm.ts';\n\n/** How `liteConfig` simplifies the caller's betting. */\nexport interface LiteOptions {\n\t/**\n\t * The turn and river keep one bet size: the caller's pot-fraction size\n\t * nearest this. Default 0.75.\n\t */\n\treadonly laterSize?: number;\n\t/**\n\t * Keep one raise on the turn and river, of the caller's raise size\n\t * nearest `laterSize`. Default false: a bet and no raise, as issue #85\n\t * measured. A raise nearly doubles the tree: on issue #47's rainbow\n\t * betting 707 MiB unshared became 1375 (173 shared became 261), an\n\t * iteration cost 1.74 times as much and Node peaked at 546 MiB.\n\t */\n\treadonly laterRaise?: boolean;\n\t/**\n\t * Cap the flop's aggressions, the opening bet the first. Default: the\n\t * caller's. A speed trim, off by default: see `solveLite`'s notes for\n\t * what it saved and cost.\n\t */\n\treadonly flopMaxRaises?: number;\n\t/**\n\t * Forbid donk bets on the turn and river (`SpotConfig.noDonk`). Default:\n\t * the caller's setting. A speed trim, off by default: see `solveLite`'s\n\t * notes for what it saved and cost.\n\t */\n\treadonly noDonk?: boolean;\n\t/** `SpotConfig.runoutBuckets` for the blueprint. Default 3. */\n\treadonly runoutBuckets?: number;\n\t/**\n\t * `SpotConfig.shareHistories` for the blueprint. Default true, the river.\n\t *\n\t * For better turn re-solves, keep the most-reached flop lines unshared\n\t * within a memory budget: `SolveLiteOptions.keepBudget` (issue #113),\n\t * which picks them with `linesWithin` for you. Lines given here in\n\t * `keepLines` are kept besides.\n\t */\n\treadonly shareHistories?: boolean | ShareHistories;\n\t/**\n\t * Compress both ranges before the blueprint is solved (`compressRanges`,\n\t * issue #156): each keeps the fewest of its combinations, re-weighted,\n\t * whose equity distributions on this board and those that can follow it\n\t * stay within `tolerance` (default 0.01 on a flop, 0.005 on a spot that\n\t * starts later) of the full range's. Default off. True for the\n\t * defaults. On a river spot there is next to no time to save.\n\t *\n\t * It keeps how the range plays, not what one combination does: the\n\t * blueprint and its re-solves hold a strategy only for the combinations\n\t * kept. `minWeight` is applied before compressing, not after.\n\t */\n\treadonly compressRanges?: boolean | CompressRangesOptions;\n}\n\n/** Settings for {@link solveLite}. */\nexport interface SolveLiteOptions\n\textends LiteOptions,\n\t\tPick<SolveOptions, 'workers' | 'precision' | 'wasmStorage' | 'algorithm' | 'onProgress' | 'targetPercent'> {\n\t/** Iteration cap. Default 2000; the solve normally settles well before. */\n\treadonly iterations?: number;\n\t/** The stop on the root play (`SolveOptions.settle`); false to run to `iterations`. Default {}, its own defaults; tolerance 0.005 unless given when `keepBudget` keeps lines. */\n\treadonly settle?: SettleOptions | false;\n\t/**\n\t * `Approximations.chanceSampling` for the blueprint, or false for none.\n\t * Default {}: sampled at p 0.35, on `workers` threads.\n\t */\n\treadonly sampling?: SamplingOptions | false;\n\t/**\n\t * Keep the most-reached first-round lines' later streets unshared\n\t * (`ShareHistories.keepLines`, issue #101), as many as this many bytes\n\t * of storage at `precision` (default 'f32') allow; `keepWithin` picks\n\t * them, and the blueprint with them kept is solved from cold. It is for\n\t * turn re-solves: on issue #47's flops it cut their gain by a third to a\n\t * half at the settle point, more when run longer, root play unchanged.\n\t * 150 MiB with `precision: 'i16'` and `wasmStorage` kept 3–19 lines and\n\t * peaked at 317–534 MiB in Chromium, re-solve included. When it keeps a\n\t * line, `settle` stops later: its tolerance defaults to 0.005, not 0.01, as the kept\n\t * lines' turn ranges go on improving after the root play settles (issue\n\t * #123); give `settle.tolerance` to choose. Throws if the shared\n\t * blueprint alone is over the budget, or if it shares nothing. Unset,\n\t * off. Measures are in `solveLite`'s notes.\n\t */\n\treadonly keepBudget?: number;\n\t/** Iterations of the picking solve under `keepBudget`. Default 80, as issue #101 measured. */\n\treadonly pickIterations?: number;\n}\n\n/** Settings for `LiteSolution.resolve`. */\nexport interface LiteResolveOptions extends Omit<ResolveOptions, 'betting'> {\n\t/** Overrides on the caller's own betting for the subgame. */\n\treadonly betting?: SubgameBetting;\n}\n\n/** What {@link litePreset} returns: the blueprint spot and the solve's settings, and what they changed. */\nexport interface LitePreset {\n\t/** The blueprint spot (`liteConfig`'s). */\n\treadonly config: SpotConfig;\n\t/** The blueprint solve's settings: `iterations`, `settle`, sampling and the solve options given. */\n\treadonly options: SolveOptions;\n\t/** Everything the preset changed against the caller's spot. */\n\treadonly changes: PresetChanges;\n}\n\n/** What {@link solveLite} returns. */\nexport interface LiteSolution {\n\t/** The blueprint's solution. */\n\treadonly solution: Solution;\n\t/** The blueprint spot that was solved (`liteConfig`'s, with `keepBudget` its kept lines). */\n\treadonly blueprint: SpotConfig;\n\t/** The lines kept unshared (`ShareHistories.keepLines`); empty without `keepBudget` or kept lines of the caller's. */\n\treadonly kept: readonly string[];\n\t/** The caller's spot, full betting. */\n\treadonly source: SpotConfig;\n\t/**\n\t * What the blueprint changed against `source`: the sizes cut on each\n\t * street (the flop's own only with `flopMaxRaises`), the streets\n\t * simplified, and the sharing, buckets, sampling and stop rule switched\n\t * on. `resolve` puts the cut sizes back below the node it re-solves.\n\t */\n\treadonly changes: PresetChanges;\n\t/**\n\t * Re-solve the subgame at a node opening the turn or river, at the\n\t * caller's full betting for the streets from there, the caller's cuts\n\t * below the node included: `resolveSubgame` with 200 iterations\n\t * unless `options` say otherwise, with the blueprint's `workers`,\n\t * `precision` and `wasmStorage`.\n\t */\n\tresolve(node: number, board: number, options: LiteResolveOptions): ResolvedSubgame;\n}\n\n/**\n * The blueprint of `config`: its first round's betting as given, every later\n * round one bet size (the given size nearest `laterSize`) and, with\n * `laterRaise`, one raise; no shove offered after the first round; and\n * `shareHistories` and `runoutBuckets: 3`. Ranges, pot, stacks and everything\n * else carry over, the ranges compressed first with `compressRanges`\n * (which takes `minWeight` with it). Per-player betting is simplified side\n * by side.\n *\n * Bet and raise cuts (`removeActions`) on the first round carry over, but\n * for those past `flopMaxRaises`; those below a deal are dropped, as the\n * later rounds' sizes no longer exist (`LiteSolution.resolve` puts them\n * back). The caller's own `shareHistories` stands unless `options` give one.\n */\nexport function liteConfig(config: SpotConfig, options: LiteOptions = {}): SpotConfig {\n\tconst target = options.laterSize ?? 0.75;\n\tif (!(target > 0)) throw new Error(`laterSize must be above 0; got ${target}`);\n\tconst rounds = 6 - parseCards(config.board).length;\n\tif (!(rounds >= 1 && rounds <= 3)) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);\n\tconst flopCap = options.flopMaxRaises;\n\tif (flopCap !== undefined && !(Number.isInteger(flopCap) && flopCap >= 1)) {\n\t\tthrow new Error(`flopMaxRaises must be a whole number of at least 1; got ${flopCap}`);\n\t}\n\n\tconst betSizes = mapPlayers(config.betSizes, (rows) =>\n\t\tperRound(rows, true, rounds, 'betSizes').map((row, r) => (r === 0 ? row : nearest(row, target))),\n\t);\n\t// Unset raise sizes follow the bet sizes, which are already down to one.\n\tconst raiseSizes =\n\t\tconfig.raiseSizes === undefined\n\t\t\t? undefined\n\t\t\t: mapPlayers(config.raiseSizes, (side: RaiseSizes | undefined): RaiseSizes | undefined =>\n\t\t\t\t\tside === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: raiseRows(side, rounds).map((row, r) => (r === 0 ? row : nearest(row, target))),\n\t\t\t\t);\n\tconst maxRaises = mapPlayers(config.maxRaises ?? 1, (side) =>\n\t\tperRound(side, Array.isArray(side), rounds, 'maxRaises').map((n, r) =>\n\t\t\tr === 0 ? (flopCap === undefined ? n : Math.min(n, flopCap)) : Math.min(n, options.laterRaise ? 2 : 1),\n\t\t),\n\t);\n\tconst allowAllIn = mapPlayers(config.allowAllIn ?? false, (side) =>\n\t\tperRound(side, Array.isArray(side), rounds, 'allowAllIn').map((on, r) => (r === 0 ? on : false)),\n\t);\n\t// Cuts below a deal name sizes the blueprint no longer has, and cuts past\n\t// the flop cap name raises it no longer has.\n\tconst aggressions = (line: string): number => line.split(' ').filter((w) => w === 'bet' || w === 'raise' || w === 'allin').length;\n\tconst removeActions = config.removeActions?.filter(\n\t\t(line) => !line.includes('/') && (flopCap === undefined || aggressions(line) <= flopCap),\n\t);\n\tconst buckets = options.runoutBuckets ?? 3;\n\tconst given = typeof config.runoutBuckets === 'number' ? config.runoutBuckets : config.runoutBuckets ? 1 : 0;\n\t// Compressed weights are relative to the largest kept, so the caller's\n\t// floor is applied to the ranges as given and not carried over.\n\tconst compressed = options.compressRanges\n\t\t? compressRanges(config, options.compressRanges === true ? {} : options.compressRanges)\n\t\t: undefined;\n\treturn {\n\t\t...config,\n\t\t...(compressed ? { oop: compressed.oop, ip: compressed.ip, minWeight: undefined } : {}),\n\t\tbetSizes: betSizes as SpotConfig['betSizes'],\n\t\t...(raiseSizes === undefined ? {} : { raiseSizes: raiseSizes as SpotConfig['raiseSizes'] }),\n\t\tmaxRaises: maxRaises as SpotConfig['maxRaises'],\n\t\tallowAllIn: allowAllIn as SpotConfig['allowAllIn'],\n\t\t...(options.noDonk === undefined ? {} : { noDonk: options.noDonk }),\n\t\t...(removeActions === undefined ? {} : { removeActions }),\n\t\trunoutBuckets: Math.max(buckets, given),\n\t\tshareHistories: options.shareHistories ?? config.shareHistories ?? true,\n\t};\n}\n\n/** Raise sizes as one row per round. */\nfunction raiseRows(side: RaiseSizes, rounds: number): (readonly BetSize[])[] {\n\treturn raisesPerRound(side)\n\t\t? perRound<readonly BetSize[]>(side, true, rounds, 'raiseSizes')\n\t\t: Array.from({ length: rounds }, () => side as readonly BetSize[]);\n}\n\n/** The one size of `row` nearest `target` pot: the nearest pot fraction, else the first size. */\nfunction nearest(row: readonly BetSize[], target: number): BetSize[] {\n\tlet best: BetSize | undefined;\n\tlet gap = Infinity;\n\tfor (const size of row) {\n\t\tif (typeof size !== 'number') continue;\n\t\tconst g = Math.abs(Math.log(size / target));\n\t\tif (g < gap) {\n\t\t\tgap = g;\n\t\t\tbest = size;\n\t\t}\n\t}\n\tif (best === undefined && row.length > 0) best = row[0];\n\treturn best === undefined ? [] : [best];\n}\n\n/**\n * Solve `config`'s lite blueprint (`liteConfig`) until its root play settles,\n * and hand back a re-solver for later streets at the full betting.\n *\n * Defaults: `shareHistories` on the river, `runoutBuckets: 3`,\n * `chanceSampling` at p 0.35, and `settle` with its defaults (every 20\n * iterations, under 1% of the range moved, twice running).\n *\n * Measured (issue #100) on issue #47's betting (0.33 / 0.75 / 1.5 pot, a\n * 0.75 raise, all-in, three aggressions; pot 55, stack 975, the bench\n * ranges), so the blueprint plays 0.75 and no raise on the turn and river.\n * Headless Chromium, `poker-flopsolve/threads`; the clock counts solving\n * and the settle checks. Root play loss is the EV OOP's root mix and IP's\n * mix after a check lose at the unshared blueprint's per-action values\n * (solved to 0.05% of pot), % of pot, with that blueprint's own loss as the\n * floor; it measures what sharing, sampling and stopping early cost, not\n * distance to the full game. Re-solve gain is the opponent's best response\n * against a turn re-solved at the full betting (300 iterations),\n * under the unshared blueprint's ranges, % of the subgame's pot, weighted\n * over 3 lines × 3 turns by how often each is reached:\n *\n * | flop | settled | Chromium, 1 / 2 / 4 threads | peak RSS | root play loss (floor) | per-hand EV error | re-solve gain (unshared) | re-solve, 1 / 2 / 4 threads |\n * |---|---|---|---|---|---|---|---|\n * | As Kh 7d | 400 it | 103 / 59 / 35 s | 511 MiB | 0.023 / 0.014 (0.009 / 0.008) | 0.75 / 0.85 | 3.1 / 2.7 (0.67 / 0.50) | 38 / 22 / 14 s |\n * | Ts 9s 4h | 320 it | 64 / 38 / 21 s | 426 MiB | 0.118 / 0.076 (0.116 / 0.052) | 0.54 / 0.60 | 4.0 / 3.3 (0.48 / 0.55) | 42 / 23 / 13 s |\n * | Ks 9s 4s | 360 it | 31 / 19 / 12 s | 253 MiB | 0.059 / 0.037 (0.047 / 0.025) | 1.5 / 1.9 | 3.6 / 3.6 (0.44 / 0.47) | 28 / 17 / 10 s |\n *\n * Sampling runs on the threads (issue #99): the same iterations settle the\n * root on every count, within 0.002% of pot. Unsampled, the rainbow\n * blueprint took 473 ms an iteration on 4 threads in Node against 251\n * sampled on one, and settled later. Peak memory counts the page, the\n * blueprint and a re-solve; it is the most a phone must give. The rainbow root play's loss is\n * 0.014% of pot over its floor for OOP; `settle: { every: 40, tolerance:\n * 0.02, patience: 3 }` brings it to 0.009 in 120 s instead of 104 (Node).\n *\n * Against exact solves of the full game, which separate what the turn and\n * river simplification costs:\n * - issue #51's T₀ on As Kh 7d (0.33 / 0.75 / 1.5 on every street, all-in\n * raises, two aggressions, solved to 0.22% of pot): OOP's root play lost\n * 0.072% of pot at T₀'s per-action values, the simplified blueprint\n * unshared and solved to 0.04% lost 0.057; per-hand root EVs were 3.9 /\n * 2.9% of pot off, unshared 4.1 / 3.1. Simplifying is the cost; sharing,\n * sampling and the stop add 0.015. T₀ stores no strategy, so there is no\n * floor from its own play.\n * - napkinpoker's postflop-solver solves (issue #87; two flop sizes, 75% on\n * the turn and river with 3× raises and all-in, weighted BU/CO/SB ranges,\n * SRP and 3-bet pots, 0.3% of pot), 8 spots across textures, one thread in\n * Node: root play lost 0.034 / 0.135% of pot on average at the stored\n * per-action values, where the stored solve's own play lost 0.027 /\n * 0.131; settled in 38-176 s. Wide single-raised ranges took up to\n * 452 MiB of storage, near a browser's default `maxBytes` of 512: give it\n * room, or `compactStorage` with `wasmStorage` (on rainbow, 300 MiB peak\n * in Node against 411, 27% slower). `minWeight: 0.05` there cut 2-5% of\n * storage and up to 15% of the time, root play unchanged; it edits the\n * ranges, so it is the caller's to set.\n *\n * `laterRaise`'s cost is on it; the trims `flopMaxRaises` and `noDonk`, and\n * what was rejected, are in docs/APPROXIMATIONS.md.\n *\n * `keepBudget` (issue #113) recovers part of the re-solve gain above, and\n * stops later (issue #123): `settle`'s tolerance 0.005, not 0.01. With\n * `keepBudget: 150 * 2 ** 20, precision: 'i16', wasmStorage` (the recipe\n * issue #101 measured), the same measures, the pick included in the time,\n * on 4 threads (Chromium; the rest Node):\n *\n * | flop | kept, storage | settled | Chromium | peak RSS | root play loss | per-hand EV error | re-solve gain | at tolerance 0.01 |\n * |---|---|---|---|---|---|---|---|---|\n * | As Kh 7d | 3 lines, 150 MiB | 580 it | 45 s | 534 MiB | 0.022 / 0.008 | 0.44 / 0.52 | 1.78 / 1.42 | 440 it, 35 s, 2.46 / 1.70 |\n * | Ts 9s 4h | 6 lines, 141 MiB | 440 it | 29 s | 467 MiB | 0.104 / 0.047 | 0.28 / 0.27 | 1.51 / 1.20 | 320 it, 22 s, 1.78 / 1.24 |\n * | Ks 9s 4s | all 19, 97 MiB | 460 it | 13 s | 315 MiB | 0.056 / 0.031 | 0.50 / 0.63 | 1.80 / 1.24 | 360 it, 11 s, 2.51 / 1.88 |\n *\n * At the old stop, on 1 / 2 / 4 threads in Chromium, As Kh 7d took 123 / 61\n * / 35 s and peaked at 489 / 509 / 534 MiB, Ts 9s 4h 69 / 37 / 22 s and 437\n * / 463 / 469, Ks 9s 4s 32 / 19 / 11 s and 290 / 301 / 317; on 4 threads\n * the later stop adds 16–32% to the time in Chromium (25–31% in Node), the\n * same peak.\n *\n * Root play is as without it; the re-solve gain falls by a third to a half\n * at the old stop, and the later one takes off 15–28% more for out of\n * position, 3–34% for in position, still over the unshared blueprint's\n * 0.4–0.7. The rest is still the stop: the root play settles before the\n * ranges it brings to the turn do. A stop that also waited for the kept\n * lines' turn ranges stopped no better than a tighter root tolerance\n * (`bench/lite/turn-stop.ts`); 0.0035 stopped at 680 / 540 / 540 iterations,\n * re-solving at 1.57 / 1.30, 1.36 / 1.23 and 1.50 / 1.00 for 39–51% more\n * time than 0.01. Run to 800 iterations (`settle: false, iterations: 800`),\n * As Kh 7d re-solves at 1.33 / 1.14 in 59 s in Chromium, peaking at 533\n * MiB, where plain sharing gives 2.23 / 2.41. A re-solve times as without\n * it.\n *\n * Its memory: the picking solve's WebAssembly memory is freed only once the\n * caller yields to the event loop, so it stays resident beside the\n * blueprint's. The pick samples the turn but not the checked-down river,\n * whose baselines would be most of it (182 MiB resident on As Kh 7d sampled\n * on both, 56 on the turn alone, the same lines kept on all three flops);\n * sampling both, rainbow peaked at 661 MiB on 4 threads.\n */\nexport function solveLite(config: SpotConfig, options: SolveLiteOptions = {}): LiteSolution {\n\tconst preset = litePreset(config, options);\n\treturn liteSolution(solve(defineSpot(preset.config), preset.options), config, preset.config, preset.changes, options);\n}\n\n/** A blueprint's solution with the re-solver for its later streets. */\nfunction liteSolution(\n\tsolution: Solution,\n\tconfig: SpotConfig,\n\tblueprint: SpotConfig,\n\tchanges: PresetChanges,\n\toptions: SolveLiteOptions,\n): LiteSolution {\n\tconst share = blueprint.shareHistories;\n\tconst kept = typeof share === 'object' ? [...(share.keepLines ?? [])] : [];\n\tconst subgameSolve = pick(options, ['workers', 'precision', 'wasmStorage']);\n\tconst { tree } = solution.spot;\n\tconst scale = solution.spot.chipScale;\n\treturn {\n\t\tsolution,\n\t\tblueprint,\n\t\tkept,\n\t\tsource: config,\n\t\tchanges,\n\t\tresolve(node, board, resolveOptions) {\n\t\t\tconst round = tree.round[node];\n\t\t\t// The caller's cuts below the node, re-rooted there as `subgameAt`\n\t\t\t// does its own: chips count from what each player has put in.\n\t\t\tconst prefix = `${solution.path(node)} `;\n\t\t\tconst invested = (tree.pot[node] - solution.spot.potUnits) / 2;\n\t\t\tconst removeActions = (config.removeActions ?? [])\n\t\t\t\t.filter((line) => line.startsWith(prefix))\n\t\t\t\t.map((line) =>\n\t\t\t\t\tline\n\t\t\t\t\t\t.slice(prefix.length)\n\t\t\t\t\t\t.split(' ')\n\t\t\t\t\t\t.map((word) => (/^-?[\\d.]+$/.test(word) ? String((Math.round(Number(word) * scale) - invested) / scale) : word))\n\t\t\t\t\t\t.join(' '),\n\t\t\t\t);\n\t\t\treturn resolveSubgame(solution, node, board, {\n\t\t\t\t...resolveOptions,\n\t\t\t\tbetting: { ...bettingFrom(config, round), removeActions, ...resolveOptions.betting },\n\t\t\t\tsolve: { ...subgameSolve, ...resolveOptions.solve },\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * The iteration count a session's blueprint resumes from after a change of\n * range (`SetRangeOptions.resume`): more than an exact solve's 10, which\n * chance sampling made unstable.\n */\nconst LITE_RESUME = 30;\n\n/** A Lite blueprint kept live, so its ranges can change without solving it again; see {@link openLite}. */\nexport interface LiteSession {\n\t/**\n\t * The blueprint as it stands. It reads the session's live storage, so it\n\t * is good until the next `setRange`, and after `close` on this thread.\n\t * Its `changes` are those of the blueprint as opened: under\n\t * `compressRanges` the counts they give are the opening ranges'.\n\t */\n\treadonly current: LiteSolution;\n\t/**\n\t * Change a player's range and settle the blueprint again from where it\n\t * stands. Any range is taken. Where every hand of it is stored and it\n\t * keeps the blueprint's suit symmetries, it changes in place\n\t * (`SolveRun.setRange`): the tree, the storage and every regret are\n\t * kept. Otherwise, and with `compressRanges`, which picks other hands\n\t * for every range, a new run is created on the new ranges and started\n\t * from this one's regrets (`SolveOptions.warmStart`), which costs a\n\t * run's setup and holds both blueprints for a moment. Either way it\n\t * settles in a fraction of the iterations a new `solveLite` takes. The\n\t * settle rule starts over, with `resettle` laid over the session's own.\n\t * Returns the new `current`; the one before it is stale.\n\t *\n\t * @param player 0 out of position, 1 in position\n\t * @param range the whole new range\n\t * @throws if the range is empty or cannot be held against the other,\n\t * changing nothing; or from the settling after it (a throwing\n\t * `onProgress`, a failed thread), with the range changed and\n\t * `current` the blueprint as far as it got\n\t */\n\tsetRange(player: 0 | 1, range: string | Float64Array): LiteSolution;\n\t/**\n\t * Run `iterations` more on the range as it stands, with no stop: what a\n\t * page does while the slider is at rest, since a blueprint goes on\n\t * improving past its settle point. Returns the new `current`.\n\t */\n\trefine(iterations: number): LiteSolution;\n\t/** Iterations run since the session opened, over every range. */\n\treadonly iterations: number;\n\t/** Release the threads. `current` stays readable. */\n\tclose(): void;\n}\n\n/** Settings for {@link openLite}. */\nexport interface OpenLiteOptions extends SolveLiteOptions {\n\t/**\n\t * Changes to `settle` for the stop after a `setRange`. Default none:\n\t * the same rule, which with the play before the move as its first\n\t * reading can stop after two checks, 40 iterations. With `settle:\n\t * false` it is the whole rule for the moves, the first solve running to\n\t * `iterations`.\n\t */\n\treadonly resettle?: SettleOptions;\n}\n\n/**\n * {@link solveLite}, kept live for a range slider: solve the blueprint until\n * its root play settles, then let `setRange` move either range and settle it\n * again from there.\n *\n * Measured (`bench/lite/slider.ts`) on issue #47's betting and the bench\n * ranges, 4 threads in Node, out of position's range moved five times (two\n * classes added, nine added, back, two dropped, a third dropped), nine\n * classes in reserve:\n *\n * | flop | five moves | five `solveLite` | a move | iterations a move | less exploitable | first solve |\n * |---|---|---|---|---|---|---|\n * | As Kh 7d | 95 s | 163 s | 12–27 s against 28–44 | 120–260 against 400–420 | 4 moves of 5 | 46 s against 30 |\n * | Ts 9s 4h | 69 s | 103 s | 11–20 s against 19–25 | 140–280 against 320 | 5 of 5 | 24 s against 18 |\n * | Ks 9s 4s | 27 s | 52 s | 3–8 s against 9–14 | 80–240 against 340–380 | 2 of 5 | 12 s against 10 |\n *\n * Exploitability in the blueprint's own game: 2.97–4.66% of pot against\n * `solveLite`'s 3.16–5.45 on the first two, lower in 9 moves of 10; on the\n * monotone flop the three moves that dropped hands ended 0.6–1.8 higher. The range's root action\n * frequencies were closer to a 1000-iteration blueprint's than `solveLite`'s\n * in 11 moves of 15; hand by hand they were further in 10, by 0.5–8 points,\n * the reserve's different buckets being part of it. The reserve cost 27–42%\n * an iteration.\n *\n * `oopReserve` and `ipReserve` on `config` are optional. With the widest\n * ranges the slider can reach in them, every move changes in place; a\n * stored hand costs what a held one does, though (27–42% an iteration for\n * nine classes). Without them the blueprint costs what `solveLite`'s does,\n * and a move that adds a hand it does not store gets a new run started from\n * the old one's regrets, which stores that hand and every hand stored\n * before it. A range that breaks a suit symmetry gets one too, and the\n * session then stays without that symmetry. The same five\n * moves with no reserve took 27 s on Ks 9s 4s against 51 for `solveLite`,\n * as the reserve's did.\n *\n * `compressRanges` compresses both ranges again at every move and gets a new\n * run each time. `algorithm: 'cfr+'` clears its average at a move and keeps\n * its count, and settles to half the tolerance unless `resettle` gives one.\n *\n * @param config the caller's spot, full betting\n * @param options `solveLite`'s, and `resettle`\n */\nexport function openLite(config: SpotConfig, options: OpenLiteOptions = {}): LiteSession {\n\tconst preset = litePreset(config, options);\n\tconst { settle, ...rest } = preset.options;\n\t// The stop after a move: `resettle` over the session's own, or alone where that is off.\n\tconst moved = settle || options.resettle ? { ...settle, ...options.resettle } : null;\n\t// CFR+ clears its average at a move, and the fresh one stops moving\n\t// before it is as good: half the tolerance unless one is given.\n\tconst resettle = moved && options.algorithm === 'cfr+' && options.resettle?.tolerance === undefined\n\t\t? { ...moved, tolerance: settlePlan(moved).tolerance / 2 }\n\t\t: moved;\n\t// Validated before anything is solved.\n\tif (resettle) settlePlan(resettle);\n\tconst compress = options.compressRanges ? (options.compressRanges === true ? {} : options.compressRanges) : null;\n\tlet run = createRun(defineSpot(preset.config), preset.options);\n\tlet source = config;\n\t// Iterations of the runs before this one: a range that cannot change in place gets a new run.\n\tlet earlier = 0;\n\t/** The blueprint as it stands. */\n\tconst reading = (solution: Solution): LiteSolution => liteSolution(solution, source, run.spot.source, preset.changes, options);\n\t/** `solve`'s loop on the live run: to the cap, the target or the settle stop. */\n\tconst settleRun = (plan: SettleOptions | null | undefined): LiteSolution =>\n\t\treading(runToStop(run, plan ? { ...rest, settle: plan } : rest));\n\t/** Where a changed range's count resumes: early under DCFR, kept under CFR+ (`SolveRun.setRange`). */\n\tconst resumed = (): number => (options.algorithm === 'cfr+' ? run.totalIterations : Math.min(run.totalIterations, LITE_RESUME));\n\n\tlet current: LiteSolution;\n\ttry {\n\t\tcurrent = settleRun(settle);\n\t} catch (error) {\n\t\trun.close();\n\t\tthrow error;\n\t}\n\treturn {\n\t\tget current() {\n\t\t\treturn current;\n\t\t},\n\t\tget iterations() {\n\t\t\treturn earlier + run.completed;\n\t\t},\n\t\tsetRange(player, range) {\n\t\t\tconst next: SpotConfig = { ...source, [player === 0 ? 'oop' : 'ip']: typeof range === 'string' ? range : range.slice() };\n\t\t\tlet inPlace = false;\n\t\t\tif (!compress) {\n\t\t\t\t// In place where every hand is stored and the symmetries hold; a\n\t\t\t\t// range that is none throws here, with nothing changed.\n\t\t\t\ttry {\n\t\t\t\t\trun.setRange(player, range, { resume: LITE_RESUME });\n\t\t\t\t\tinPlace = true;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof RangeNotInPlaceError)) throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!inPlace) {\n\t\t\t\t// A new run on the new ranges, started from this one's regrets.\n\t\t\t\t// Under `compressRanges` always: both ranges are compressed again,\n\t\t\t\t// each against the other, and keep other hands. Otherwise it\n\t\t\t\t// stores what this one does as well, so a hand once stored stays\n\t\t\t\t// stored and the way back is in place.\n\t\t\t\tconst ranges = compress ? compressRanges(next, compress) : next;\n\t\t\t\tconst stored = (index: { readonly slot: Int32Array }): Float64Array => Float64Array.from(index.slot, (slot) => (slot >= 0 ? 1 : 0));\n\t\t\t\tconst blueprint: SpotConfig = {\n\t\t\t\t\t...preset.config,\n\t\t\t\t\toop: ranges.oop,\n\t\t\t\t\tip: ranges.ip,\n\t\t\t\t\t...(compress ? {} : { oopReserve: stored(run.spot.players[0]), ipReserve: stored(run.spot.players[1]) }),\n\t\t\t\t};\n\t\t\t\t// Defined before anything is let go: a spot that cannot be throws here, with nothing changed.\n\t\t\t\tconst spot = defineSpot(blueprint);\n\t\t\t\t// The old run's threads first, which the new one needs where\n\t\t\t\t// threads are borrowed (a browser); its storage stays readable.\n\t\t\t\tconst count = resumed();\n\t\t\t\trun.close();\n\t\t\t\tlet replacement: SolveRun;\n\t\t\t\ttry {\n\t\t\t\t\treplacement = createRun(spot, { ...preset.options, warmStart: run, warmIteration: count });\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Back on the ranges it had: the same spot, so the average comes too.\n\t\t\t\t\trun = createRun(run.spot, { ...preset.options, warmStart: run });\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tearlier += run.completed;\n\t\t\t\trun = replacement;\n\t\t\t}\n\t\t\tsource = next;\n\t\t\ttry {\n\t\t\t\tcurrent = settleRun(resettle);\n\t\t\t} catch (error) {\n\t\t\t\t// The range has changed all the same: `current` must not read the new storage as the old range's.\n\t\t\t\tcurrent = reading(run.snapshot([], 'iterations'));\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\treturn current;\n\t\t},\n\t\trefine(count) {\n\t\t\tif (!(Number.isInteger(count) && count > 0)) throw new Error(`refine: iterations must be a positive whole number; got ${count}`);\n\t\t\trun.step(count);\n\t\t\tcurrent = reading(run.snapshot([], 'iterations'));\n\t\t\treturn current;\n\t\t},\n\t\tclose() {\n\t\t\trun.close();\n\t\t},\n\t};\n}\n\n/**\n * `settle`'s tolerance under `keepBudget` (issue #123): half its default, so\n * the solve runs on past the root play's settling while the kept lines' turn\n * ranges are still improving.\n */\nconst KEEP_TOLERANCE = 0.005;\n\n/**\n * What {@link solveLite} solves, without solving it: `liteConfig`'s\n * blueprint, the solve's settings (`iterations` 2000, `settle` at its\n * defaults, or tolerance 0.005 when `keepBudget` keeps lines, `chanceSampling`\n * at p 0.35, and the solve options given), and a\n * report of everything changed against `config`. With `keepBudget` it\n * does solve: the short picking solve `keepWithin` ranks lines on, whose\n * kept lines are in the blueprint and the report. For a page that steps its\n * own run: `createRun(defineSpot(preset.config), preset.options)`, with\n * `trackSettle(preset.options.settle)` for the stop, and `resolveSubgame` with `bettingFrom(config,\n * round)` for the re-solves `LiteSolution.resolve` would make.\n */\nexport function litePreset(config: SpotConfig, options: SolveLiteOptions = {}): LitePreset {\n\tconst blueprint = keepWithin(liteConfig(config, options), options);\n\tconst sampling = options.sampling === undefined ? {} : options.sampling;\n\tconst asked = options.settle === undefined ? {} : options.settle;\n\t// Kept lines bring better turn ranges, but only once the solve runs past\n\t// the root play's settling (issue #123): a later stop unless asked otherwise.\n\tconst share = blueprint.shareHistories;\n\tconst keeps = options.keepBudget !== undefined && typeof share === 'object' && (share.keepLines?.length ?? 0) > 0;\n\tconst settle = asked && keeps && asked.tolerance === undefined ? { ...asked, tolerance: KEEP_TOLERANCE } : asked;\n\t// Validated before the report reads it.\n\tconst tolerance = settle ? settlePlan(settle).tolerance : 0;\n\tconst solveOptions: SolveOptions = {\n\t\titerations: options.iterations ?? 2000,\n\t\t...(settle ? { settle } : {}),\n\t\t...(sampling ? { approximations: { chanceSampling: sampling } } : {}),\n\t\t...pick(options, ['workers', 'precision', 'wasmStorage', 'algorithm', 'onProgress', 'targetPercent']),\n\t};\n\n\t// Each setting compared by what it does, so equivalent spellings\n\t// (unset and false, true and a gap of 1) are no change.\n\tconst settings: SettingChange[] = [];\n\tconst notes: string[] = [];\n\tconst change = (setting: string, from: unknown, to: unknown, note: string): void => {\n\t\tsettings.push({ setting, from, to });\n\t\tnotes.push(`${setting}: ${note}`);\n\t};\n\tconst rounds = 6 - parseCards(config.board).length;\n\tconst streets = ['flop', 'turn', 'river'].slice(3 - rounds);\n\tconst donks = (value: SpotConfig['noDonk']): boolean[] => perRound(value ?? false, Array.isArray(value), rounds, 'noDonk');\n\tconst [donkFrom, donkTo] = [donks(config.noDonk), donks(blueprint.noDonk)];\n\tif (donkFrom.join() !== donkTo.join()) {\n\t\tconst on = streets.filter((_, r) => donkTo[r]);\n\t\tchange('noDonk', config.noDonk, blueprint.noDonk, on.length\n\t\t\t? `donk bets forbidden on the ${on.join(' and ')}, a speed trim that changes the game`\n\t\t\t: 'donk bets allowed on every street');\n\t}\n\tconst gap = (value: SpotConfig['runoutBuckets']): number => (value === true ? 1 : typeof value === 'number' ? value : 0);\n\tif (gap(config.runoutBuckets) !== gap(blueprint.runoutBuckets)) {\n\t\tconst to = gap(blueprint.runoutBuckets);\n\t\tchange('runoutBuckets', config.runoutBuckets, blueprint.runoutBuckets, to > 0\n\t\t\t? `gap ${to}: turn and river cards that play alike are solved once (approximate; folds nothing on ranges with no rank symmetry)`\n\t\t\t: 'off: every turn and river card solved');\n\t}\n\tconst sharing = (value: SpotConfig['shareHistories']): string => JSON.stringify(value === true ? {} : value || null);\n\tif (sharing(config.shareHistories) !== sharing(blueprint.shareHistories)) {\n\t\tconst kept = typeof blueprint.shareHistories === 'object' ? (blueprint.shareHistories.keepLines?.length ?? 0) : 0;\n\t\tchange('shareHistories', config.shareHistories, blueprint.shareHistories, blueprint.shareHistories\n\t\t\t? `lines that meet share river storage${kept ? `, but for ${kept} line${kept > 1 ? 's' : ''} kept apart` : ''} (approximate: exploitability plateaus a few % of pot from equilibrium; read the root play)`\n\t\t\t: 'off: every line stores its own river');\n\t}\n\tconst dropped = (config.removeActions?.length ?? 0) - (blueprint.removeActions?.length ?? 0);\n\tif (dropped > 0) {\n\t\tchange('removeActions', config.removeActions, blueprint.removeActions, `${dropped} line${dropped > 1 ? 's' : ''} below a deal or past the flop cap left out of the blueprint; resolve puts those below a deal back`);\n\t}\n\tif (options.compressRanges) {\n\t\tconst count = (range: string | Float64Array): number => activeCombos(typeof range === 'string' ? parseRange(range) : range).length;\n\t\tchange('compressRanges', undefined, options.compressRanges, `compressed to ${count(blueprint.oop)} and ${count(blueprint.ip)} re-weighted combinations (out of position, in position) that keep each range's equity distribution on this board and those that can follow it; approximate: the blueprint has no strategy for a combination left out, and what one combination does is not preserved`);\n\t}\n\tif (sampling) change('approximations.chanceSampling', undefined, sampling, samplingNote(sampling));\n\tif (settle) {\n\t\tchange('settle', undefined, settle, `stops once the root play moves under ${+(100 * tolerance).toFixed(2)}% of the range between checks, not at an exploitability target${settle === asked ? '' : ' (later than its default, for the kept lines\\' turn ranges)'}`);\n\t}\n\treturn { config: blueprint, options: solveOptions, changes: presetChanges(config, blueprint, settings, notes) };\n}\n\n/**\n * `blueprint` keeping the lines `options.keepBudget` allows, picked with\n * `linesWithin` from `options.pickIterations` of `checkedDown(blueprint)`;\n * `blueprint` itself without a budget. What `solveLite` solves; exported so\n * a caller stepping its own run can do the same. The picking solve uses\n * `options`' `workers`, `precision`, `wasmStorage`, `algorithm` and\n * `sampling`, the last on every round but the checked-down one.\n */\nexport function keepWithin(blueprint: SpotConfig, options: SolveLiteOptions = {}): SpotConfig {\n\tconst budget = options.keepBudget;\n\tif (budget === undefined) return blueprint;\n\tif (!(budget > 0)) throw new Error(`keepBudget must be a number of bytes above 0; got ${budget}`);\n\tconst its = options.pickIterations ?? 80;\n\tif (!(Number.isInteger(its) && its >= 1)) throw new Error(`pickIterations must be a whole number of at least 1; got ${its}`);\n\tconst asked = blueprint.shareHistories;\n\tif (!asked) throw new Error('keepBudget keeps lines out of shareHistories; this blueprint shares nothing');\n\tconst cheap = defineSpot(checkedDown(blueprint));\n\tconst picked = solve(cheap, {\n\t\titerations: its,\n\t\t...pickSampling(options.sampling === undefined ? {} : options.sampling, cheap.runouts.rounds),\n\t\t...pick(options, ['workers', 'precision', 'wasmStorage', 'algorithm']),\n\t});\n\tconst keepLines = linesWithin(picked, budget, { config: blueprint, precision: options.precision ?? 'f32' });\n\treturn { ...blueprint, shareHistories: { ...(asked === true ? {} : asked), keepLines } };\n}\n\n/**\n * The picking solve's sampling: the blueprint's, but not on the last round,\n * which `checkedDown` leaves without bets. Its baselines are most of a\n * sampled solve's memory (on As Kh 7d, 126 of 182 MiB), and `solveLite`\n * cannot let the picking solve's memory go before the blueprint starts, as\n * WebAssembly memory is freed only once the caller yields. Sampling the\n * turn alone ranked the same lines on all three of issue #47's flops.\n */\nfunction pickSampling(sampling: SamplingOptions | false, rounds: number): { approximations?: { chanceSampling: SamplingOptions } } {\n\tif (!sampling) return {};\n\tconst asked = sampling.rounds ?? Array.from({ length: rounds - 1 }, (_, i) => i + 1);\n\tconst kept = asked.filter((r) => r < rounds - 1);\n\treturn kept.length > 0 ? { approximations: { chanceSampling: { ...sampling, rounds: kept } } } : {};\n}\n\n/**\n * `config` with its last round checked down: no bet or all-in there, and\n * cuts naming that round's actions dropped. Its first rounds are the same\n * game tree, so how often each line reaches the next round\n * (`turnLineReach`) comes out much as the real spot's, at a fraction of its\n * storage: what `solveLite`'s `keepBudget` ranks lines on (issue #101: on\n * As Kh 7d the lite blueprint so cut stores 57 MiB, against 173, and ranked\n * the same top 3). `shareHistories.keepLines` is dropped, as it may name\n * nodes the cut removes.\n */\nexport function checkedDown(config: SpotConfig): SpotConfig {\n\tconst rounds = 6 - parseCards(config.board).length;\n\tif (!(rounds >= 1 && rounds <= 3)) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);\n\tconst last = rounds - 1;\n\tconst betSizes = mapPlayers(config.betSizes, (rows) =>\n\t\tperRound(rows, true, rounds, 'betSizes').map((row, r) => (r === last ? [] : row)),\n\t);\n\tconst allowAllIn = mapPlayers(config.allowAllIn ?? false, (side) =>\n\t\tperRound(side, Array.isArray(side), rounds, 'allowAllIn').map((on, r) => (r === last ? false : on)),\n\t);\n\t// A cut's round is the number of deals ('/') before its last action.\n\tconst removeActions = config.removeActions?.filter((line) => line.split('/').length - 1 < last);\n\tconst asked = config.shareHistories;\n\tconst shareHistories = typeof asked === 'object' ? (({ keepLines: _kept, ...rest }) => rest)(asked) : asked;\n\treturn {\n\t\t...config,\n\t\tbetSizes: betSizes as SpotConfig['betSizes'],\n\t\tallowAllIn: allowAllIn as SpotConfig['allowAllIn'],\n\t\t...(removeActions === undefined ? {} : { removeActions }),\n\t\t...(shareHistories === undefined ? {} : { shareHistories }),\n\t};\n}\n\n/** Only the listed keys of `from` that are set. */\nfunction pick<T extends object, K extends keyof T>(from: T, keys: readonly K[]): Partial<Pick<T, K>> {\n\tconst out: Partial<Pick<T, K>> = {};\n\tfor (const key of keys) if (from[key] !== undefined) out[key] = from[key];\n\treturn out;\n}\n\n/**\n * `config`'s tree-shaping betting for a subgame opening round `round`: each\n * setting given per round loses the rounds before it, as\n * `Solution.subgameAt` does with the spot's own.\n */\nexport function bettingFrom(config: SpotConfig, round: number): SubgameBetting {\n\tconst rounds = 6 - parseCards(config.board).length;\n\tconst from = <T>(value: T | readonly T[], listed: boolean, name: string): T | readonly T[] =>\n\t\tlisted ? perRound(value as readonly T[], true, rounds, name).slice(round) : value;\n\tconst each = <T>(value: PerPlayer<T> | undefined, listed: (side: T) => boolean, name: string): PerPlayer<T> | undefined =>\n\t\tvalue === undefined ? undefined : (mapPlayers(value, (side) => from(side, listed(side), name) as T) as PerPlayer<T>);\n\tconst out: Record<string, unknown> = {\n\t\tbetSizes: each(config.betSizes, () => true, 'betSizes'),\n\t\traiseSizes: each(config.raiseSizes, (side) => side !== undefined && raisesPerRound(side), 'raiseSizes'),\n\t\tmaxRaises: each(config.maxRaises ?? 1, Array.isArray, 'maxRaises'),\n\t\tallowAllIn: each(config.allowAllIn ?? false, Array.isArray, 'allowAllIn'),\n\t\tallInThreshold: each(config.allInThreshold, Array.isArray, 'allInThreshold'),\n\t\t// The blueprint may forbid donk bets where the caller did not.\n\t\tnoDonk: from(config.noDonk ?? false, Array.isArray(config.noDonk), 'noDonk'),\n\t};\n\t// `subgameAt` reads these with `in`, so an unset one stays present and\n\t// says \"none\" rather than carrying the blueprint's over.\n\treturn out as SubgameBetting;\n}\n\n/**\n * How exploitable a Lite solve's play is in the caller's full game, % of the\n * pot (issue #154). Lite cannot measure itself: its exploitability is that\n * of the simplified game, sizes cut, runouts bucketed, histories shared.\n *\n * `exact` is a run of the caller's own spot, solved as far as the caller\n * likes. Every decision of it that `lite` also has takes `lite`'s average\n * strategy, as a warm start copies it, so an action `lite` lacks there gets\n * none; the decisions only reachable through such an action (a size Lite\n * cut, a raise) keep `exact`'s play, the best answer at hand. The figure is\n * then the exploitability of that strategy: what Lite's own decisions cost,\n * with no penalty for the ones it never made. `exact`'s own exploitability\n * is its floor, since what Lite lacks is played no better than `exact`\n * plays it. A combination Lite left out (`compressRanges`) keeps `exact`'s\n * play too, so the figure covers only the combinations Lite solved.\n *\n * `exact` is spent: its strategy is overwritten, so read anything else from\n * it first and close it after.\n *\n * @param lite the Lite solve, or any solve of the same board\n * @param exact a run of the full game: same board, unshared histories\n * @throws if the boards differ or `exact` shares histories\n */\nexport function exploitabilityInExact(lite: Solution | SolveRun, exact: SolveRun): number {\n\t// Shared storage would let one history's copy overwrite another's.\n\tif (exact.solver.ctx.layout.shared) throw new Error('The Exact run shares histories; measure in one that keeps them apart');\n\twarmStart(exact.solver.ctx, lite.solver.ctx, true);\n\treturn exact.exploitabilityPercent();\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 type { PerPlayer } from './tree.ts';\nimport { actionLabel, buildTree, forPlayer, mapPlayers, NodeKind, raisesPerRound } from './tree.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { ResolvedBoard } from './runouts.ts';\nexport { rankSwap } 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 } from './range.ts';\nimport type { ShowdownTable } from './showdown.ts';\nimport { buildShowdownTable } from './showdown.ts';\nimport type { HandSpace } from './hands.ts';\nimport { buildHandSpace } from './hands.ts';\nimport { createEngine, threadProfiles } from './engine.ts';\nimport type { WasmStorage } from './engine.ts';\nimport type { WarmStartReport } from './warm.ts';\nimport { warmStart } from './warm.ts';\nimport type { SettleOptions } from './settle.ts';\nimport { settlePlan, trackSettle } from './settle.ts';\nimport { aliasHistories } from './history-merge.ts';\nimport { betRows, DEFAULT_CHIP_SCALE, treeConfig } from './betting.ts';\nimport type { Pool } from './parallel.ts';\nimport { defaultWorkerCount, planShards, startPool } from './parallel.ts';\nimport { DEFAULT_MAX_BYTES, PLATFORM, spawnEngineWorker, threadAdvice, threadLimit, warmEngineThreads } from './platform/node.ts';\nimport type { ActiveLists, CompactPlan, Context, Layout, PlayerIndex, RegretStore, RootValues, SamplingOptions, Solver, SumStore } from './cfr.ts';\nimport {\n\tbuildActiveLists,\n\tbuildLayout,\n\tbuildPlayerIndex,\n\tmakeSampling,\n\tplanSampling,\n\tsampledRounds,\n\tsamplingBytes,\n\tmakeSolver,\n\tmakeTerminalScratch,\n\tmatchupMass,\n\tMode,\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 { resolveSubgame } from './resolve.ts';\nexport { rootPlay, rootPlayMovement, rootPlayNodes, trackSettle } from './settle.ts';\nexport type { RootPlay, SettleOptions, SettleTracker } from './settle.ts';\nexport { linesWithin, turnLineReach } from './hybrid.ts';\nexport type { LineReach, LinesWithinOptions } from './hybrid.ts';\nexport type { ResolvedSubgame, ResolveOptions } from './resolve.ts';\nexport { simdAvailable } from './kernels.ts';\nexport type { BetSize } from './tree.ts';\nexport type { SamplingOptions, Solver } from './cfr.ts';\nexport type { WasmStorage } from './engine.ts';\nexport { ACTION_LABELS, ActionKind, NodeKind } from './tree.ts';\nexport type { PerPlayer, RaiseSizes } from './tree.ts';\n/** 'node' or 'browser': which build is running. */\nexport { PLATFORM } from './platform/node.ts';\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/**\n\t * The pot `Solution.ev` and `Solution.handEvs` are percentages of, in\n\t * chips. Default `pot`. `Solution.subgameAt` sets it to the original\n\t * spot's, so a re-solved turn or river reports in the flop pot and its\n\t * values read the same way as the flop's down a hand.\n\t */\n\treadonly evPot?: 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/**\n\t * Hands to keep storage for although the out-of-position range gives them\n\t * no weight yet, so `SolveRun.setRange` can add them later without\n\t * building anything: a range, of which only the hands matter, not their\n\t * weights. Every hand a range slider can reach belongs here. A reserved\n\t * hand costs what a held one does, in memory and per iteration, and is\n\t * solved all along, so it has a strategy the moment it gets weight;\n\t * except at nodes that share storage (`shareHistories`), whose updates\n\t * are weighted by the hand's own reach, so there it starts from nothing.\n\t * Unset, only the range's own hands are stored, and `setRange` can\n\t * reweight or drop them but add none.\n\t */\n\treadonly oopReserve?: string | Float64Array;\n\t/** `oopReserve` for the in-position range. */\n\treadonly ipReserve?: string | Float64Array;\n\t/**\n\t * Bet sizes per betting round; a single row applies to every round.\n\t *\n\t * This and every other betting setting below (`raiseSizes`, `maxRaises`,\n\t * `allowAllIn`, `allInThreshold`) can be given apart for each player as\n\t * `{ oop: …, ip: … }`, each side in the setting's usual form:\n\t * `betSizes: { oop: [[0.33]], ip: [[0.5, 1]] }`. They only shape the\n\t * tree, so a solve costs the same either way.\n\t */\n\treadonly betSizes: PerPlayer<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?: PerPlayer<RaiseSizes | undefined>;\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. Given apart, a player may bet\n\t * or raise only while the round's aggressions are under their own limit.\n\t */\n\treadonly maxRaises?: PerPlayer<number | readonly number[]>;\n\t/** Offer a shove alongside the configured sizes; once, or per round. Default false. */\n\treadonly allowAllIn?: PerPlayer<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?: PerPlayer<number | readonly number[] | undefined>;\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/**\n\t * Bets, raises and shoves to cut from the tree, with everything below\n\t * them: each the readable path of the node the action leads to, exactly as\n\t * `Solution.path` writes it — `\"check bet 18.15\"`, `\"bet 41.25 raise\n\t * 133.31\"`, `\"check check / bet 18.15\"`, chips being the actor's total\n\t * investment after the action and `/` a deal. Only the line named goes; the\n\t * same size elsewhere stays. Checks, calls and folds cannot be cut, and a\n\t * path that names no such action in the tree is refused.\n\t *\n\t * For a budgeted tree: keep three sizes where they earn their memory, one\n\t * where they do not. A tree's memory is almost all on the river, and each\n\t * flop or turn action multiplies the river subtrees below it, so cutting a\n\t * line saves what its whole subtree stores. Default none; unset, the tree\n\t * is the one the other settings build, unchanged.\n\t */\n\treadonly removeActions?: readonly string[];\n\t/**\n\t * Thin the bet sizes to a shape that keeps most of what the full ones are\n\t * worth in a fraction of the memory. Every size stays at the root, where\n\t * out of position opens the first round. Everywhere else a decision keeps\n\t * one bet, raise or shove: the one nearest three quarters of the pot, a\n\t * shove where that would be one. Opening the last round after an earlier\n\t * round saw a bet, sizes above the pot and the shove stay as well.\n\t *\n\t * The shape is what growing sizes one at a time by their value per byte\n\t * picked on As Kh 7d and Ks 9s 4s (issue #51). Measured on As Kh 7d, pot\n\t * 55, stack 975, sizes 0.33 / 0.75 / 1.5 with shove-only raises and two\n\t * aggressions: see the #51 entry in docs/APPROXIMATIONS.md for its memory and error.\n\t * It is a fixed rule, so it costs nothing to apply. A subgame from\n\t * `Solution.subgameAt` gets the full sizes back unless its betting sets\n\t * this again, and then it is thinned as a tree of its own: bets on the\n\t * streets before it do not count, so a river after a bet on the flop\n\t * keeps only the 0.75 size, where the whole tree also kept its big sizes\n\t * and shove. Default false; unset, the tree is unchanged.\n\t */\n\treadonly thinSizes?: boolean;\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\t/**\n\t * Share river storage between betting histories that reach the same pot,\n\t * a lossy approximation for fitting a spot in memory (issue #49). Off by\n\t * default.\n\t *\n\t * Every earlier line gets its own copy of the streets below it, yet with\n\t * pot-fraction sizes many lines meet: check, bet, call and bet, call\n\t * reach the same pot, and so does every raise line taken in either order.\n\t * Their subtrees are identical, so their nodes keep one set of regrets and\n\t * strategy sums. Each history is still walked with its own reach, so an\n\t * iteration costs exactly what it did; only storage shrinks. On the\n\t * three-size target spot (AsKh7d, pot 55, stack 975, sizes 33/75/150%, a\n\t * 75% raise and all-in, three aggressions) 173 river starts collapse to 23\n\t * and storage falls 5.9 times: 17.2 GiB to 2.9 at 32 bits, 8.7 to 1.5 at 16.\n\t * There, at 16 bits, a Node solve peaked at 1.6 GiB on one thread and 2.0\n\t * on four (30 s an iteration), and was 12% of pot exploitable after 150\n\t * iterations.\n\t *\n\t * What is lost is recall: a player plays one strategy for every line that\n\t * met, though the ranges each line brings differ. Each history's regret is\n\t * weighted by how often the acting hand plays into it, which cut the cost\n\t * fourfold against plain CFR's sum. Measured on AsKh7d, pot 55, stack\n\t * 975, against the exact solve, 4 threads: with sizes 33/75/150%, an\n\t * all-in raise and two aggressions, 5.8 GiB became 1.22 GiB, and after\n\t * 400 iterations the strategy was 8.0% of pot exploitable, with\n\t * per-combination root EVs 0.72% of pot off on average and 2.5% at worst\n\t * (the exact solve: 0.28%). With one 50% size, 4.0% exploitable after\n\t * 300 iterations, EVs 0.67% off on average and 6.8% at worst.\n\t * Exploitability is measured in the full game, which the strategy covers\n\t * node by node, so it is exact. Do not expect it to approach\n\t * equilibrium: expect a strategy several percent of the pot from it, in\n\t * a spot that otherwise does not fit.\n\t *\n\t * Two consequences of one block serving several histories, both part of\n\t * the approximation: within an iteration, a history visited later plays\n\t * the regrets an earlier one has already updated, so the result depends a\n\t * little on the order of the tree; and under `algorithm: 'cfr+'` each\n\t * history's update is clamped at zero on its own, rather than their sum.\n\t * A spot with it can warm-start only from a solve that shares too.\n\t *\n\t * On issue #47's blueprint (issue #85; T's flop betting, one 0.75 bet on\n\t * the turn and river with no raise, `runoutBuckets: 3`) it saves 4.1 times\n\t * on rainbow, two-tone and monotone flops alike, because the flop's sizes\n\t * and raises still meet at a few turn pots: 196 river decisions keep 44\n\t * blocks. On AsKh7d 707 MiB becomes 173 at 32 bits, so the blueprint stays\n\t * on the WebAssembly engine; in Chromium on 4 threads the tab peaked at\n\t * 327 MiB, against 860 unshared. An iteration costs what an unshared one\n\t * does (458 ms there). Exploitability stops falling near 2.7% of pot by\n\t * 160 iterations and never reaches 0.3%; the root play goes on settling.\n\t * Judged at the unshared blueprint's own per-action values (solved to\n\t * 0.045%), after 300 iterations (138 s) its root play lost 0.011% of pot\n\t * where the unshared blueprint's lost 0.008%, but at 60 s it was 0.054%:\n\t * the unshared one needs 115 s to reach 0.3% itself. Per-hand root EVs\n\t * came out 0.4–0.6% of pot from the unshared ones (2–3% at worst), and\n\t * turns re-solved from it with T's betting gave the opponent 2.2–3.0% of\n\t * their pot under the unshared ranges, against 0.5–0.7% from the unshared\n\t * blueprint. `chanceSampling` composes: on one thread 238 ms an iteration,\n\t * the root settled in 109 s, 453 MiB; on 4 threads (issue #99) 70 ms, the\n\t * root settled in 33 s at the same iteration, 452 MiB. `coarseStart` composes\n\t * but finds no coarser copy at a gap of 3. `bench/blueprint-share/` has\n\t * the scripts and figures.\n\t *\n\t * Where a shared solve stops depends on its first few iterations (issue\n\t * #105). A shared block plays one strategy for every history meeting in\n\t * it, so the game has many stable points, and which one the solve settles\n\t * on is decided early, when regret matching plays nearly pure. Any\n\t * randomness then picks another: chance sampling, 8-bit stochastic\n\t * rounding, even float rounding under CFR+. On #103's turn spot\n\t * (exploitability 5.8% of pot), sampling at p 0.9 ended at 0.3–1.6%\n\t * over six different sets of draws. On a second turn spot (0.7%) it\n\t * changed nothing. On the blueprint above, neither sampling at p 0.9\n\t * (2.9%) nor 8-bit stochastic storage (2.5%) moved the plateau beyond\n\t * that spread, against 2.6% shared alone. Do not count on noise to\n\t * lower it. Of the deterministic changes tried (other regret\n\t * weighting, discount start, uniform play mixed into the first\n\t * iterations), none was a reliable gain. `bench/share-noise/` has the\n\t * measurements.\n\t *\n\t * `true` shares the river. See `ShareHistories` for the turn and for\n\t * lossier buckets.\n\t */\n\treadonly shareHistories?: boolean | ShareHistories;\n\t/**\n\t * Store regrets and strategy sums at 8 bits — an approximation, off by\n\t * default. See `CompactStorage`. Set here rather than on the solve because it\n\t * decides how much memory the spot needs, which `maxBytes` is checked\n\t * against when the spot is defined.\n\t */\n\treadonly compactStorage?: CompactStorage;\n}\n\n/**\n * Compact storage (issue #50): accumulators as 8-bit integers, each hand on\n * each board scaled by its own power of two, instead of 32- or 16-bit\n * values. Regret matching and the average strategy both divide a hand's\n * values by their own total, so a per-hand scale cancels wherever a strategy\n * is read and costs only a byte per hand. Rounding is at random, with odds\n * set by the remainder, so every stored value is right on average; the\n * randomness is a hash of the slot and iteration, so a solve is deterministic\n * at any thread count.\n *\n * Two modes:\n *\n * - With strategy sums (the default): regrets and sums at 8 bits, about 2.75\n * bytes a slot against 16-bit storage's 4 and 32-bit's 8. Measured, it\n * converges like the full solve: on the bench flop (AsKh7d, one size) 0.18%\n * of pot at 80 iterations against 0.18%, 0.058% at 160 against 0.052%; on\n * the monotone flop with three sizes (Ks9s4s, issue #20's T₀) 1.87% at 160\n * against 1.85%. Rounding the sums leaves a floor, near 0.03% of pot on the\n * bench flop and 0.1% on a small, narrow-range spot. On issue #20's T₀\n * (AsKh7d, three sizes, all-in raise, SPR 18), at 320 iterations it was\n * 0.81% of pot exploitable where 32-bit storage was 0.69%, per-hand root\n * EVs 0.23% of pot off a 0.17% reference, every hand's preferred bet size\n * kept, in 1.75 GiB where 32-bit storage took 5.1 and 16-bit 2.6. T itself\n * takes 5.9 GiB, 16-bit storage 8.7.\n * - `sums: false`: no strategy sums, so each node's strategy, wherever one is\n * read (`strategyAt`, `reachAt`, EVs, exploitability), is the current\n * profile, the regret-matched strategy the next iteration plays. About 1.4\n * bytes a slot, 1.03 with `blockScale`: T in 2.2 GiB. Per-hand root EVs stay as close as\n * the average's, as `currentProfileEv` found, but the strategy is far more\n * exploitable: 2 times at equal iterations on the bench flop, 5 to 8 times\n * on deeper or narrower spots (T₀ monotone: 4.0% of pot at 320 iterations\n * against 0.71%), and the bet size each hand prefers at the root agreed with\n * the reference for 62-82% of the hands where it was clear, against all of\n * them for the average. `algorithm: 'cfr+'`, whose current profile swings\n * less, is the better rule for the strategy; DCFR's current profile gives\n * the closer EVs (on T₀ monotone 0.55% of pot against the average's 1.19%,\n * but 4.9% exploitable).\n *\n * Rounding regrets to 8 bits costs training almost nothing: with 32-bit\n * regrets and no sums (`float`) the same runs were no better.\n *\n * Training is otherwise the exact solve's; exploitability is measured\n * exactly, in the full tree. Storage is split in chunks under `chunkBytes`,\n * because browsers refuse a buffer of 2 GiB. Runs on the JavaScript engine\n * and its Node worker threads, where an iteration costs about 1.5 times a\n * 32-bit one, or on the WebAssembly engine, threads included, with\n * `SolveOptions.wasmStorage` (issue #84). Not with `analysisOnly`, which\n * loads float32 sums. `precision` sets the rounds before `from`; a warm\n * start, a coarse start or `runoutBuckets`' measure of the real game reads\n * and writes compact storage, rounded to nearest; `chanceSampling` applies\n * its DCFR catch-up to compact nodes too.\n *\n * With `shareHistories`, a node sharing another's storage shares its compact\n * storage too; together they fit issue #20's target T in 0.99 GiB (0.37\n * without sums). Measured on T₀ at 160 iterations, compact storage did not\n * add to sharing's own loss: 9.0% of pot exploitable against 9.5%, root EVs\n * 0.63% of pot off against 0.66%, and all clear bet-size choices kept\n * against 97%, in a third of the memory.\n *\n * What was measured and left out is with the other approximations, in the\n * comment inside `Approximations`.\n */\nexport interface CompactStorage {\n\t/**\n\t * Keep 8-bit strategy sums, and with them the average strategy. Default\n\t * true; false stores only regrets and plays the current profile.\n\t */\n\treadonly sums?: boolean;\n\t/**\n\t * With `sums: false`, one scale per node and board instead of one per\n\t * hand: about 1.03 bytes a slot instead of 1.4. Under CFR+ it measured\n\t * nearly as accurate (0.077% of pot against 0.064% on the bench flop at\n\t * 320 iterations); under DCFR, whose large negative regrets then crowd\n\t * the scale, clearly less (0.16% against 0.08%).\n\t */\n\treadonly blockScale?: boolean;\n\t/**\n\t * First round stored compactly, from the spot's first (0); earlier rounds\n\t * keep 32-bit regrets and sums. Default 0. With `sums: false`, an earlier\n\t * round's average above the current profile measured worse than the\n\t * current profile throughout (0.053% of pot against 0.035% on the bench\n\t * flop): the two come from different iterations.\n\t */\n\treadonly from?: number;\n\t/**\n\t * Largest single buffer to allocate, in bytes; storage is split in chunks\n\t * no bigger, a node never split. Default 1 GiB: Chromium refuses an\n\t * ArrayBuffer of 2 GiB, but gives several smaller ones.\n\t */\n\treadonly chunkBytes?: number;\n\t/** For measurement: the largest regret magnitude stored, at most 127. */\n\treadonly steps?: number;\n\t/** For measurement: round regrets to nearest instead of at random. */\n\treadonly nearest?: boolean;\n\t/** For measurement, with `sums: false`: keep 32-bit regrets, dropping only the sums. */\n\treadonly float?: boolean;\n}\n\n/** See `SpotConfig.shareHistories`. */\nexport interface ShareHistories {\n\t/**\n\t * Lines whose later streets keep storage of their own, each named as\n\t * `Solution.path` names a node (a flop line opening the turn reads like\n\t * `\"check check /\"`). Every node at or below a listed one is left out of\n\t * sharing, and so is any round root above one. The rest share as\n\t * before. Unset or empty, nothing is kept. A warm start into a spot that\n\t * differs only here, keeping at least the lines its source keeps,\n\t * carries the average strategy too, as for the same spot.\n\t *\n\t * What it is for (issue #101): a turn re-solved from a shared blueprint\n\t * (`resolveSubgame`) inherits only the ranges the blueprint brings to\n\t * it, and sharing distorts those. Its flop play is stored unshared, but\n\t * it learns from river values that several histories share. Keeping the\n\t * few most-reached flop lines unshared gives the flop exact values\n\t * where most of the play is, and that straightens the ranges on the\n\t * lines left shared too. Pick them with `linesWithin` (the most-reached\n\t * lines, `turnLineReach`, that a storage budget allows) from a short\n\t * solve, 80 iterations, of a cheap copy of the spot (below); close that\n\t * and solve the hybrid spot from cold. Continuing from the picking solve\n\t * instead is worse: its average lingers.\n\t *\n\t * Measured on issue #47's blueprint (`1size-b3`), 400 iterations, against\n\t * the unshared blueprint solved to 0.045% of pot. \"Re-solve gain\" is the\n\t * opponent's best response to an unsafe turn re-solve at the full\n\t * three-size betting, under the unshared blueprint's ranges, in % of the\n\t * subgame pot, weighted by line reach, refining OOP / IP; the unshared\n\t * blueprint's own re-solves give 0.67 / 0.50. On AsKh7d:\n\t *\n\t * | kept | storage, f32 | re-solve gain | root EV error, mean |\n\t * |---|---|---|---|\n\t * | none (plain sharing) | 173 MiB | 3.05 / 2.15 | 0.57 / 0.46 |\n\t * | top 1 | 201 MiB | 2.48 / 1.58 | 0.46 / 0.53 |\n\t * | top 3 | 285 MiB | 1.10 / 0.83 | 0.24 / 0.21 |\n\t * | top 6 | 383 MiB | 1.16 / 0.65 | 0.23 / 0.27 |\n\t * | all (unshared) | 707 MiB | 0.67 / 0.50 | 0 |\n\t *\n\t * On Ts9s4h and Ks9s4s plain sharing gives 4.10 / 3.69 and 4.23 /\n\t * 2.72 against 0.48 / 0.55 and 0.44 / 0.47 unshared. Kept by a 300 MiB\n\t * budget (`linesWithin`), two-tone keeps 6 lines in 282 MiB for 0.61 /\n\t * 0.72, and monotone all 19 in 187 MiB. The top 3 alone are not enough\n\t * on two-tone (1.82 / 1.96), so budget the storage, not the count.\n\t *\n\t * In Chromium the picking solve's WebAssembly memory stays resident\n\t * until it is collected, so it adds to the peak. Rank on a cheap copy\n\t * instead: the blueprint with its river checked down (57 MiB on AsKh7d)\n\t * ranked the same top 3 there. Within 512 MiB on AsKh7d, store the\n\t * hybrid at 16 bits (`precision: 'i16'` with `wasmStorage`) with a 150\n\t * MiB budget at that precision. It keeps the same 3 lines, re-solves at\n\t * 1.47 / 0.92, and peaked at 392 MiB on 4 threads, 592 ms an iteration\n\t * against 495 shared, its root play settled in 127 s. Two-tone the same\n\t * way: 0.88 / 0.85. `bench/blueprint-share/` has the scripts and figures.\n\t */\n\treadonly keepLines?: readonly string[];\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\t/** Storage with `compactStorage`, which `maxBytes` is then checked against; else null. */\n\treadonly compactBytes: number | null;\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(estimate.compactBytes !== null\n\t\t\t\t? `This spot needs ~${formatBytes(estimate.compactBytes)} even with compact storage, `\n\t\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/** Each node's storage owner under `shareHistories`; unset without it. */\n\treadonly historyAlias?: Int32Array;\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\tif (config.evPot !== undefined && !(Number.isFinite(config.evPot) && config.evPot > 0)) {\n\t\tthrow new Error(`evPot must be a positive number of chips; got ${config.evPot}`);\n\t}\n\n\tconst rows = betRows(config, rounds);\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\t// Which hands are reserved, board cards removed; null without a reserve.\n\tconst reserved = (range: string | Float64Array | undefined, who: string): Float64Array | null => {\n\t\tif (range === undefined) return null;\n\t\tconst hands = typeof range === 'string' ? parseRange(range) : range;\n\t\tif (hands.length !== COMBOS) {\n\t\t\tthrow new Error(`The ${who} reserve has ${hands.length} weights; one per combination is ${COMBOS}`);\n\t\t}\n\t\tconst mask = new Float64Array(COMBOS);\n\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\tif (hands[combo] > 0 && !onBoard.has(COMBO_CARDS[combo * 2]) && !onBoard.has(COMBO_CARDS[combo * 2 + 1])) mask[combo] = 1;\n\t\t}\n\t\treturn mask;\n\t};\n\tconst reserves = [reserved(config.oopReserve, 'out-of-position'), reserved(config.ipReserve, 'in-position')];\n\tconst players: [PlayerIndex, PlayerIndex] = [\n\t\tbuildPlayerIndex(trim(config.oop, 'out-of-position'), reserves[0] ?? undefined),\n\t\tbuildPlayerIndex(trim(config.ip, 'in-position'), reserves[1] ?? undefined),\n\t];\n\tif (!holdable(players[0].weights, players[1].weights)) {\n\t\tthrow new Error('No hand of one range can be held against a hand of the other: every pair shares a card');\n\t}\n\tfor (const player of players) {\n\t\tif (config.maxCombos !== undefined && player.count > config.maxCombos) {\n\t\t\tthrow new Error(`A range and its reserve hold ${player.count} combinations, over the ${config.maxCombos} limit`);\n\t\t}\n\t}\n\n\t// Symmetry needs the ranges, so the runouts come after them. It must keep\n\t// the stored hands in place too, so each reserve counts as a range here.\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, ...reserves.filter((mask) => mask !== null)]);\n\tconst merge =\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\tconst runouts = runoutsFor(board, symmetries, merge);\n\t// Kept for `setRange`, which must not break a symmetry the runouts fold by.\n\tconst symmetryCombos = (symmetries ?? []).map((map) => {\n\t\tconst image = new Uint16Array(COMBOS);\n\t\tfor (let combo = 0; combo < COMBOS; combo++) image[combo] = comboIndex(map[COMBO_CARDS[combo * 2]], map[COMBO_CARDS[combo * 2 + 1]]);\n\t\treturn image;\n\t}).filter((image) => image.some((combo, at) => combo !== at));\n\tconst tree = buildTree(treeConfig(config, rows), runouts);\n\n\tconst historyAlias = config.shareHistories ? shareHistories(tree, runouts, config, chipScale) : undefined;\n\tconst layout = buildLayout(tree, runouts, players, 4, historyAlias);\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, historyAlias).bytes + showdownBytes;\n\t// Shared storage is walked once per history all the same.\n\tconst walkedSlots = layout.walkedSlots;\n\tconst compact = config.compactStorage ? compactPlan(config.compactStorage, runouts.rounds) : null;\n\tconst compactBytes = compact\n\t\t? buildLayout(tree, runouts, players, 4, historyAlias, compact).bytes + showdownBytes\n\t\t: null;\n\tconst needed = compactBytes ?? compressedBytes;\n\n\tconst suggestions: string[] = [];\n\tif (needed > maxBytes) {\n\t\tconst widest = Math.max(...[0, 1].flatMap((p) => forPlayer(rows, p).map((r) => r.length)));\n\t\tif (widest > 1) suggestions.push(`use fewer bet sizes (currently up to ${widest} per round)`);\n\t\tconst raises = [0, 1].flatMap((p) => [forPlayer(config.maxRaises ?? 1, p)].flat());\n\t\tif (Math.max(...raises) > 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\tcompactBytes,\n\t\tsecondsPerThousandIterations: (walkedSlots * 4 * 1000) / OPS_PER_SECOND,\n\t\tfits: needed <= maxBytes,\n\t\tsuggestions,\n\t};\n\tif (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);\n\n\tconst spot: Spot = {\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\t...(historyAlias ? { historyAlias } : {}),\n\t\tresolveBoard(cards) {\n\t\t\treturn resolveBoard(runouts, typeof cards === 'string' ? parseCards(cards) : cards);\n\t\t},\n\t};\n\tspotSymmetries.set(spot, symmetryCombos);\n\treturn spot;\n}\n\n/**\n * The iteration count a run resumes from after `SolveRun.setRange`, unless it\n * was lower. Early enough that DCFR discounts the old range's average away\n * within a few iterations, late enough that it does not flatten the regrets:\n * from 0 a changed range took as long as from cold, from 5 it varied, and 10\n * to 20 were alike.\n */\nexport const RANGE_RESUME = 10;\n\n/**\n * The configuration a spot was defined with, once `setRange` has replaced its\n * `source`. Defining that again gives the spot's own runouts and hand lists;\n * its changed ranges may have symmetries the spot was not built to fold.\n */\nconst builtFrom = new WeakMap<Spot, SpotConfig>();\n\n/** The runouts last enumerated, and what they were enumerated from. */\nlet keptRunouts: { key: string; runouts: Runouts } | null = null;\n\n/**\n * `enumerateRunouts`, kept for the next spot on the same board with the same\n * symmetries and buckets: a spot defined again with another pot, stack or\n * betting, or with ranges that fold the same runouts, deals the same cards.\n * One set is kept; `releaseSetupCache` lets it go.\n */\nfunction runoutsFor(board: readonly number[], symmetries: readonly Uint8Array[] | undefined, merge: RunoutMerge | undefined): Runouts {\n\tlet key = `${board.join(',')}|${(symmetries ?? []).map((map) => map.join(',')).join(';')}|`;\n\tif (merge) {\n\t\tkey += `${merge.maxGap}:`;\n\t\tfor (let a = 0; a < 13; a++) for (let b = 0; b < 13; b++) key += merge.ranks(a, b) ? '1' : '0';\n\t}\n\tif (keptRunouts?.key !== key) keptRunouts = { key, runouts: enumerateRunouts(board, symmetries, merge) };\n\treturn keptRunouts.runouts;\n}\n\n/** What a run looks up for every hand on every board, none of it depending on the tree. */\ninterface SetupTables {\n\treadonly showdown: ShowdownTable;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n}\n\n/** The tables last built, and the runouts and hands they were built for. */\nlet keptTables: { runouts: Runouts; combos: readonly [Uint16Array, Uint16Array]; tables: SetupTables } | null = null;\n\n/**\n * The showdown ranking, hand lists and hand-space maps of a spot. They\n * depend on its runouts and on which hands each player stores, not on the\n * tree, the weights or the storage, and building them is most of what a run\n * costs before its first iteration; so the last set is kept, and a run on\n * the same spot, or on one defined again with other betting or reweighted\n * ranges, takes it as it is. Nothing writes to them. `releaseSetupCache`\n * lets them go.\n */\nfunction setupTables(spot: Spot, relevant: Uint8Array): SetupTables {\n\tconst [first, second] = [spot.players[0].combos, spot.players[1].combos];\n\tconst same = (a: Uint16Array, b: Uint16Array): boolean => a.length === b.length && a.every((combo, i) => combo === b[i]);\n\tif (keptTables && keptTables.runouts === spot.runouts && same(keptTables.combos[0], first) && same(keptTables.combos[1], second)) {\n\t\treturn keptTables.tables;\n\t}\n\t// Let the old set go before the new one is built, so both are never held.\n\tkeptTables = null;\n\tconst showdown = buildShowdownTable(spot.runouts, relevant);\n\tconst active = buildActiveLists(spot.runouts, spot.players, showdown);\n\tconst hands = buildHandSpace(spot.runouts, spot.players, active);\n\tkeptTables = { runouts: spot.runouts, combos: [first, second], tables: { showdown, active, hands } };\n\treturn keptTables.tables;\n}\n\n/**\n * Let go of what the last spot and run left for the next: the runouts, and\n * the per-hand tables a run builds before its first iteration (a few MiB on\n * narrow ranges, tens on wide ones). A spot defined or a run created\n * afterwards builds its own again, which is all it costs. For a page that\n * has finished solving and wants the memory back.\n */\nexport function releaseSetupCache(): void {\n\tkeptRunouts = null;\n\tkeptTables = null;\n}\n\n/** Whether some hand of `a` and some hand of `b` share no card. */\nfunction holdable(a: Float64Array, b: Float64Array): boolean {\n\tfor (let i = 0; i < COMBOS; i++) {\n\t\tif (!(a[i] > 0)) continue;\n\t\tconst [c, d] = [COMBO_CARDS[i * 2], COMBO_CARDS[i * 2 + 1]];\n\t\tfor (let j = 0; j < COMBOS; j++) {\n\t\t\tif (!(b[j] > 0)) continue;\n\t\t\tconst [e, f] = [COMBO_CARDS[j * 2], COMBO_CARDS[j * 2 + 1]];\n\t\t\tif (c !== e && c !== f && d !== e && d !== f) return true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Each suit symmetry a spot's runouts fold by, the identity aside, as the hand each hand maps to. */\nconst spotSymmetries = new WeakMap<Spot, readonly Uint16Array[]>();\n\n/** `SpotConfig.shareHistories` resolved into each node's storage owner. */\nfunction shareHistories(tree: Tree, runouts: Runouts, config: SpotConfig, chipScale: number): Int32Array {\n\tconst asked: ShareHistories = config.shareHistories === true ? {} : config.shareHistories || {};\n\tconst keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : undefined;\n\treturn aliasHistories(tree, runouts, { keep }).alias;\n}\n\n/**\n * `ShareHistories.keepLines` as node marks: each listed node, everything\n * below it, and everything above it, so that no round root containing it\n * is shared either.\n */\nfunction keptNodes(tree: Tree, chipScale: number, lines: readonly string[]): Uint8Array {\n\tconst parent = new Int32Array(tree.nodeCount).fill(-1);\n\tconst paths: string[] = new Array(tree.nodeCount);\n\tpaths[0] = '(root)';\n\t// Children come after their parents, so a parent's path is always ready.\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\tconst child = tree.edgeChild[edge];\n\t\t\tparent[child] = node;\n\t\t\tconst step = tree.kind[node] === NodeKind.Decision ? actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], chipScale) : '/';\n\t\t\tpaths[child] = node === 0 ? step : `${paths[node]} ${step}`;\n\t\t}\n\t}\n\tconst listed = new Set(lines);\n\tconst missing = new Set(lines);\n\tconst marks = new Uint8Array(tree.nodeCount);\n\t// At or below a listed node: parents come first, so one sweep does.\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tif (listed.has(paths[node])) {\n\t\t\tmissing.delete(paths[node]);\n\t\t\tmarks[node] = 1;\n\t\t} else if (parent[node] >= 0 && marks[parent[node]]) {\n\t\t\tmarks[node] = 1;\n\t\t}\n\t}\n\tif (missing.size > 0) {\n\t\tthrow new Error(`shareHistories.keepLines: no node of this tree has the path ${[...missing].map((l) => `\"${l}\"`).join(', ')}`);\n\t}\n\t// Above one: every ancestor of a marked node.\n\tfor (let node = tree.nodeCount - 1; node > 0; node--) if (marks[node]) marks[parent[node]] = 1;\n\treturn marks;\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\t/**\n\t * Stop once the root play stops moving (issue #100): every `every`\n\t * iterations (default 20) read the average strategy at the root and at in\n\t * position's decision after a check, and stop once it has moved less than\n\t * `tolerance` (default 0.01: 1% of the range's mass, total variation\n\t * weighted by range) at `patience` checks in a row (default 2).\n\t * `stoppedAt` is then 'settled'. `rootPlayMovement` defines the measure.\n\t *\n\t * For solves that never reach an exploitability target, such as a\n\t * blueprint with `shareHistories`, which plateaus several percent of the\n\t * pot out while its first decisions go on settling (issue #85). A check\n\t * reads two nodes' strategies and no best-response pass, so it costs\n\t * almost nothing; with it, `Progress.exploitability` is NaN unless\n\t * `targetPercent` is set too, which then measures at every check and\n\t * stops on whichever comes first. `exploitEvery` is ignored. Measured\n\t * costs are in `solveLite`'s notes. Unset, off.\n\t */\n\treadonly settle?: SettleOptions;\n\treadonly onProgress?: (info: Progress) => void;\n\t/**\n\t * Accumulator storage. Unset, 'f32' — what the WebAssembly engine runs —\n\t * or 'i16' for a spot too big for it under `maxBytes` (beside chance\n\t * sampling's baselines, when `approximations.chanceSampling` is on). 'f64' is there on\n\t * request and runs the JavaScript engine; measured, it buys no accuracy\n\t * an exploitability target can see.\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 unless `enableThreads` from\n\t * `poker-flopsolve/threads` has started its workers; any count above what\n\t * is available resolves to what is, with one warning.\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 * For a `warmStart` from a solve of a different board: each card of this\n\t * spot's deck to the card of the old spot's it plays as, a permutation of\n\t * the 52 cards taking this board onto the old one. A rank swap (`6` and\n\t * `7` in every suit, say) carries a solve of AsKh6d onto AsKh7d with every\n\t * hand keeping its role: 66 there is 77 here (`rankSwap` builds that map).\n\t * Hands and runouts relabel through it; whatever the old ranges lacked\n\t * starts cold. Unset, a warm start must come from the same board. The\n\t * average strategy never carries over through it, even for a relabelling\n\t * that leaves the game unchanged: only regrets do.\n\t *\n\t * Measured on the bench flop (AsKh7d, single-threaded, to 0.5% of pot):\n\t * 52 iterations cold, 8 warm from a 0.1% solve of AsKh6d, 20 from AsQh7d.\n\t * It pays only when the whole old solve is at hand: seeding the flop's\n\t * decisions alone, as a downloadable library could, saved at most 15%\n\t * (see `Approximations`).\n\t */\n\treadonly warmCards?: Uint8Array;\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\t/**\n\t * Which traversal runs. Unset, the WebAssembly engine wherever it applies\n\t * — 32-bit storage (or 16-bit and compact with `wasmStorage`), WebAssembly\n\t * SIMD available — and the JavaScript one otherwise. 'js' forces\n\t * JavaScript, to compare the two.\n\t */\n\treadonly engine?: 'js';\n\t/**\n\t * 16-bit and compact storage on the WebAssembly engine (issue #84): pass\n\t * `wasmStorage` from `poker-flopsolve/wasm-storage`. With it, a solve at\n\t * `precision: 'i16'` or of a `compactStorage` spot runs on the engine,\n\t * threads included, rather than on JavaScript. Its updates are the\n\t * JavaScript ones, step for step, worked in 32-bit floats rather than\n\t * 64-bit ones, so a stored value differs only where it lies within float32\n\t * precision of a rounding boundary; the random rounding hashes the same\n\t * slot and iteration, read to 24 bits rather than 32. Compact scales\n\t * below 2^-126 (regrets under 10^-35) are taken as 0. Unset, those solves run on\n\t * JavaScript as before; 32-bit solves run on the default engine either\n\t * way, and `precision: 'f64'` on JavaScript.\n\t */\n\treadonly wasmStorage?: WasmStorage;\n}\n\n/** See `SolveOptions.approximations`. */\nexport interface Approximations {\n\t/**\n\t * Solve a coarser copy of the spot first and start the real one from its\n\t * regrets — coarse to fine, as multigrid methods do. The copy buckets\n\t * turn and river cards like `runoutBuckets`, so each of its iterations\n\t * is cheaper (a flop stores ~40% fewer runouts at a gap of 3), and its\n\t * equilibrium is close enough to the real one's that the real solve picks\n\t * up roughly where it left off. The answer is still the real spot's: the\n\t * coarse game only chooses where it starts, and exploitability and\n\t * `targetPercent` measure the real game. Unset, off.\n\t *\n\t * Measured on three flop spots in Chromium, one thread, stopped at 15 s,\n\t * with 40 coarse iterations (issue #24): root-EV error per combination\n\t * against a 0.1%-of-pot reference fell from 1.51% to 0.19% of pot on\n\t * AsKh7d (exploitability 0.94% to 0.40%), and 0.26% to 0.06% on the\n\t * wider bench flop. A monotone flop, which a cold solve already settles\n\t * within 15 s, reached 0.5% error in half the time but ended a little\n\t * looser, 0.11% against 0.04%. To an exploitability target in Node it\n\t * was faster on all three: 0.1% on the monotone flop in 14.5 s instead of\n\t * 15.3, 0.2% on the wide one in 15.5 instead of 19.3, 0.3% on AsKh7d in\n\t * 23.8 instead of 31.5. Around 40 iterations suits a flop; far fewer\n\t * leave the coarse solve too rough to help, far more spend the time\n\t * where the real solve would have spent it better.\n\t *\n\t * Carrying the coarse average strategy, restarting DCFR's count (a\n\t * `warmIteration` of 0 or 10), a bucket gap of 1, or forbidding donk bets\n\t * in the coarse spot were measured too, and were all worse.\n\t *\n\t * The coarse iterations count toward `totalIterations`, not `completed`\n\t * or `Solution.iterations`; DCFR carries on counting from them unless\n\t * `warmIteration` says otherwise. Both solves are in memory at the\n\t * switch, the coarse one about 60% the size of the real one on a flop.\n\t * Where bucketing folds no runouts together — a river spot, ranges with no rank symmetry — it does\n\t * nothing. Not with `warmStart`, which it already is. The coarse solve\n\t * runs inside `createRun`, all at once and without progress reports, so\n\t * a caller stepping a run to stay responsive should keep it short; it\n\t * must fit in what `maxBytes` leaves beside the real spot, at 16 bits if\n\t * not 32, or `createRun` refuses. With `precision` unset, a real spot\n\t * whose 32-bit storage leaves no room for the coarse one is solved at 16\n\t * bits, the coarse one too (issue #148; on the JavaScript engine unless\n\t * the solve passes `wasmStorage`).\n\t */\n\treadonly coarseStart?: CoarseStart;\n\t/**\n\t * Report `Solution.ev` and `Solution.handEvs` under the current profile —\n\t * the regret-matched strategy the next iteration would play — instead of\n\t * the average strategy. Default off. Measured under DCFR, the default\n\t * update rule; it applies to CFR+ alike.\n\t *\n\t * Measured against a solve to 0.045% of pot, after a 15 s single-threaded\n\t * browser budget, the current profile's per-hand root EVs had a mean error\n\t * of 1.23% of pot where the average's had 2.18% (flop As Kh 7d), 0.11%\n\t * against 0.37% (monotone Ks 9s 4s) and 1.40% against 2.02% (wide Qs Jh\n\t * 2c). Across those three spots it was the closer one at 62 of 65\n\t * checkpoints from 15 s down to 0.1% exploitability, often by 2–4 times.\n\t * It costs the same one pass per player as reading the average's EVs.\n\t *\n\t * Those EVs then belong to a different profile from the strategy\n\t * `strategyAt` and `reachAt` show, which stays the average: the average is\n\t * what converges to equilibrium and what exploitability measures, while\n\t * the current profile's values happen to settle sooner. Read them as the\n\t * better estimate of the equilibrium's EVs, not as the EVs of the strategy\n\t * on screen. A run with `analysisOnly` has no regrets and cannot use this.\n\t */\n\treadonly currentProfileEv?: boolean;\n\t/*\n\t * Every other approximation measured and left out, or measured as a\n\t * combination and offered only as a preset, is recorded with its numbers\n\t * and issue in docs/APPROXIMATIONS.md.\n\t */\n\t/**\n\t * Chance sampling with baselines (VR-MCCFR; Schmid et al., 2019). Each\n\t * training iteration walks each turn and river deal with probability `p`\n\t * (default 0.35, both rounds). A deal left out adds the per-hand values it\n\t * returned when last walked, its baseline; a walked deal adds\n\t * `b + (v - b) / p` and its values become the new baseline. DCFR discounts\n\t * a skipped subtree missed are applied when it is next walked. This is\n\t * what made sampling pay where the plain 1/p weighting (docs/APPROXIMATIONS.md) did not:\n\t * the correction only carries how much a deal's values moved since its\n\t * last walk, which is small.\n\t *\n\t * Iterations get several times cheaper and take 2–5 times as many to a\n\t * target, so the net is about 1.2–1.5 times faster to 0.3% of pot, and\n\t * per-hand root EVs come out closer to the true ones at the same\n\t * exploitability. Measured single-threaded in Node against the exact\n\t * solve, time to 0.3% of pot (to 1%): AsKh7d 23.7 s → 15.9 s (13.3 → 9.0),\n\t * Ks9s4s 6.0 → 4.3 (3.4 → 2.3), the README's wide flop 13.4 → 9.3\n\t * (7.5 → 5.3), and pairs-and-broadway ranges on AsKh7d 16.7 → 12.9 and on\n\t * Ks9s4s 5.5 → 4.5. Exploitability is measured exactly, in the full game.\n\t *\n\t * Costs: one float per hand per stored deal per chance node, 6–31 MB on\n\t * those flops (about 12–20% beside their storage), counted against\n\t * `maxBytes`. Any storage: 32-, 64- or 16-bit, or `compactStorage`\n\t * over 32 or 16 bits (16-bit since issue #102, with the same DCFR\n\t * catch-up, in both engines).\n\t *\n\t * Threads (issue #99): it runs on `workers` threads, in the JavaScript\n\t * pool and on the WebAssembly engine's threads alike. Threads split the\n\t * runouts as for an exact solve, and the state sampling keeps (baselines,\n\t * when each deal was last walked, when each block was last updated for\n\t * the catch-up) lives in shared memory, each thread's runouts' entries\n\t * its own. There is no per-thread random stream: whether a deal is walked\n\t * on an iteration is a hash of its chance node, the deal and the\n\t * iteration, in both engines, so every thread count walks the same deals\n\t * on the same iterations. A fixed count is then bitwise repeatable, and\n\t * different counts differ only as unsampled ones do (see `workers`). A\n\t * spot sampling a round above the threads' split, which no flop or turn\n\t * spot has, runs on one thread. Measured in Chromium on issue #47's\n\t * blueprint, 4 threads ran 3.1–3.2 times faster than 1 on three flops,\n\t * and the shared AsKh7d blueprint's root play settled in 33 s against\n\t * 105 s (`bench/blueprint-share/README.md`). With `targetPercent`, a sampled solve runs more\n\t * iterations, so it makes a few more exploitability checks.\n\t * Off, nothing changes; at `p: 1` it is the exact solve, bit for bit.\n\t */\n\treadonly chanceSampling?: SamplingOptions;\n}\n\n/** See `Approximations.coarseStart`. */\nexport interface CoarseStart {\n\t/** Iterations of the coarse spot to run before the real one. */\n\treadonly iterations: number;\n\t/**\n\t * The coarse spot's `runoutBuckets`, at least the spot's own. Default 3;\n\t * a wider gap folds more runouts only where the ranges allow it.\n\t */\n\treadonly runoutBuckets?: number;\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\t/** In chips; NaN at a `settle` check made without `targetPercent`. */\n\treadonly exploitability: number;\n\treadonly elapsedMs: number;\n\t/** With `settle`: how far the root play moved since the last check (`rootPlayMovement`), NaN at the first. */\n\treadonly movement?: number;\n}\n\n/** Which stopping rule ended a solve: see `Solution.stoppedAt`. */\nexport type StopReason = 'target' | 'iterations' | 'settled';\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. 'settled' is\n\t * `SolveOptions.settle`'s: the root play stopped moving.\n\t */\n\treadonly stoppedAt: StopReason;\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/**\n\t * The pot, in chips, that `ev` and `handEvs` are percentages of:\n\t * `SpotConfig.evPot`, which defaults to the spot's own `pot` (rounded to\n\t * chip units, as the tree holds it). A subgame\n\t * from `subgameAt` carries the original spot's.\n\t */\n\treadonly evPot: number;\n\t/**\n\t * A player's share of the pot, in percent of `evPot`: what they win on\n\t * average per hand, `100 × (evChips + evPot / 2) / evPot`. Folding, or\n\t * losing every showdown, is 0; winning the pot uncontested is 100; the\n\t * two players' values add up to 100. In a subgame, whose own pot holds\n\t * chips both players put in earlier, folding at its root reads below 0:\n\t * the earlier chips given up, as a share of `evPot`. Under the average\n\t * strategy, or the current profile with `approximations.currentProfileEv`.\n\t */\n\tev(player: 0 | 1): number;\n\t/**\n\t * `ev` in chips per hand, against a baseline where each player already\n\t * owns half the pot: folding is worth −pot/2 and the players' values add\n\t * up to 0. The same baseline at every round, since a round opens with\n\t * both players level. `Solver.valuesAt` and the traversal use it.\n\t */\n\tevChips(player: 0 | 1): number;\n\t/** `handEvs` in chips on `evChips`'s half-pot baseline. Returns a fresh copy. */\n\thandEvsChips(player: 0 | 1): Float64Array;\n\t/**\n\t * Root EV for each combination a player can hold, in percent of `evPot`\n\t * as `ev` is, indexed like `COMBO_CARDS` (as `reachAt` is): what that hand\n\t * wins on average, over the opponent hands it can be dealt against. Zero\n\t * for combinations outside the range or blocked by the board, and for a\n\t * hand no opponent hand can be dealt against, which has no EV to give;\n\t * those carry no weight. Weighted by range weight times compatible\n\t * opponent mass, the mean is `ev(player)`, and the same pass serves both.\n\t * Under the average strategy, or the current profile with\n\t * `approximations.currentProfileEv`. Returns a fresh copy.\n\t */\n\thandEvs(player: 0 | 1): Float64Array;\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'\n\t\t| 'raiseSizes'\n\t\t| 'maxRaises'\n\t\t| 'allowAllIn'\n\t\t| 'allInThreshold'\n\t\t| 'noDonk'\n\t\t| 'mergeSizes'\n\t\t| 'removeActions'\n\t\t| 'thinSizes'\n\t\t| 'maxCombos'\n\t\t| 'maxBytes'\n\t>\n>;\n\n/** Subgame settings that shape the tree, which a carried-over cut would not fit. */\nconst TREE_SETTINGS = [\n\t'betSizes', 'raiseSizes', 'maxRaises', 'allowAllIn', 'allInThreshold', 'noDonk', 'mergeSizes', 'thinSizes',\n] as const satisfies readonly (keyof SubgameBetting)[];\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/**\n * `SolveRun.setRange` cannot take this range where the run stands, though\n * the range itself is good: it holds a hand the spot keeps no storage for,\n * or it breaks a suit symmetry the spot folds runouts by. A new run on a\n * spot defined with the range can, warm-started from this one\n * (`SolveOptions.warmStart`); `openLite`'s session does that by itself.\n */\nexport class RangeNotInPlaceError extends Error {}\n\n/** Settings for `SolveRun.setRange`. */\nexport interface SetRangeOptions {\n\t/**\n\t * The iteration count the run resumes from, unless it was lower; a CFR+\n\t * run keeps its count whatever this says. Default\n\t * `RANGE_RESUME`, 10, measured on exact solves. A chance-sampled solve\n\t * wants more: Lite's blueprint (p 0.35) swung 10 points of root play off\n\t * and back resuming from 10, and settled smoothly from 25 or 40; from 80\n\t * and 160 it was smooth and slower.\n\t */\n\treadonly resume?: number;\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/** Which traversal runs: the WebAssembly engine or the JavaScript one. */\n\treadonly engine: 'wasm' | 'js';\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/**\n\t * Change a player's range in place and keep solving: what a range slider\n\t * calls on every move. Nothing is built or copied — the run keeps its\n\t * tree, its storage and every regret, as a warm start would carry them,\n\t * and only reads other weights from the next iteration on — so it costs\n\t * microseconds where a new run costs as much as a few iterations.\n\t *\n\t * A hand can be reweighted or dropped freely. One the range did not hold\n\t * when the spot was defined can be added only if `oopReserve` or\n\t * `ipReserve` kept storage for it. Board cards are dropped and\n\t * `minWeight` applied, as `defineSpot` does. The range must keep every\n\t * suit symmetry the spot folds runouts by (none with `isomorphism:\n\t * false`). `runoutBuckets` stand as they are: they were chosen by which\n\t * hands the spot stores, and that does not change.\n\t *\n\t * The average strategy is not cleared, since that would cost a pass over\n\t * the whole storage. Instead the iteration count resumes from\n\t * `RANGE_RESUME` (or stays, if lower), where DCFR's discounting is still\n\t * steep enough to shrink what the old range left behind while the regrets\n\t * keep the strategy where it was. Measured on the bench river, turn and\n\t * flop, adding or dropping about a tenth of a range, that reached 0.3%\n\t * of pot (0.5% on the flop) in as few iterations as a `warmStart` into a\n\t * new run or fewer — 40–50 against 60–85 cold on river and turn, 16–24\n\t * against 44 on the flop — where resuming from 0 or keeping the count\n\t * did no better than cold. `totalIterations` resumes with it. A run\n\t * with `algorithm: 'cfr+'`, which discounts nothing, keeps its count\n\t * and has its average cleared instead, a pass over the storage. On the\n\t * bench river and turn that reached 0.3% of pot in 25–100 iterations\n\t * against 105–185 from cold, for two hand classes or a third of the\n\t * range dropped. A range cut to a few hands is slower than from cold\n\t * under CFR+, whose regrets are never discounted.\n\t *\n\t * The spot is reweighted with the run: `spot.players` and `spot.source`\n\t * show the new range, for this run and any other built on the same spot,\n\t * which then solves and measures the new range too, its own count and\n\t * average left as they were.\n\t * A snapshot taken before the change is stale; take a fresh one.\n\t *\n\t * @param player 0 out of position, 1 in position\n\t * @param range the whole new range, as `SpotConfig.oop` takes one; an\n\t * array of weights skips the parsing a string costs\n\t * @param options `resume`, the iteration count to resume from\n\t * @throws {RangeNotInPlaceError} if the range adds a hand without storage or breaks a\n\t * symmetry: the range is good, but needs a new run. Or, a plain error, if\n\t * it is empty or leaves no pair of hands the players can hold together.\n\t * Nothing has changed in either case\n\t */\n\tsetRange(player: 0 | 1, range: string | Float64Array, options?: SetRangeOptions): 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?: StopReason): 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\tif (options.analysisOnly && options.approximations?.currentProfileEv) {\n\t\tthrow new Error('approximations.currentProfileEv needs regrets, and an analysisOnly run has none');\n\t}\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 { bytes } = spot.estimate;\n\tconst compact = spot.source.compactStorage ? compactPlan(spot.source.compactStorage, spot.runouts.rounds) : null;\n\tif (compact) {\n\t\tconst clashes: [unknown, string][] = [\n\t\t\t// An analysis-only run loads float32 sums, which compact nodes do not have.\n\t\t\t[options.analysisOnly, 'analysisOnly'],\n\t\t];\n\t\tconst clash = clashes.find(([set]) => set)?.[1];\n\t\tif (clash) throw new Error(`compactStorage does not combine with ${clash}`);\n\t}\n\t// With compact storage, `precision` is that of the rounds before `compactStorage.from`.\n\tconst defaulted = !compact && !options.analysisOnly && options.precision === undefined;\n\tlet precision: Precision = compact\n\t\t? options.precision ?? 'f32'\n\t\t: options.analysisOnly\n\t\t? 'f32'\n\t\t: options.precision ??\n\t\t\t(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\t// Threads take as long to start as the tables below take to build, so\n\t// the ones this run will use start now, beside that work. Judged as the\n\t// engine and the split are below; where chance sampling's baselines then\n\t// push the storage to 16 bits, threads started for nothing wait for the\n\t// next run or end.\n\tif (!options.analysisOnly && options.engine !== 'js' && options.simd !== false && (options.workers ?? 1) !== 1) {\n\t\tconst engineLikely =\n\t\t\t(precision === 'f32' && !compact) ||\n\t\t\t(options.wasmStorage !== undefined && precision !== 'f64' && (precision === 'i16' || compact !== null));\n\t\tconst asked = engineLikely ? resolveWorkers(options, true) : 1;\n\t\tif (asked > 1 && planShards(spot.tree, spot.runouts, asked)) warmEngineThreads(asked - 1);\n\t}\n\tconst { showdown, active, hands } = setupTables(spot, relevant);\n\tconst layoutAt = (at: Precision): Layout => buildLayout(\n\t\tspot.tree, spot.runouts, spot.players, PRECISION_BYTES[at], spot.historyAlias, compact ?? undefined,\n\t);\n\tlet layout = layoutAt(precision);\n\tconst weights = runoutWeights(spot.runouts);\n\tconst samplingOptions = options.approximations?.chanceSampling;\n\t// The plan reads only the layout's blocks, which do not depend on precision.\n\tconst samplingPlan = samplingOptions ? planSampling(spot.tree, spot.runouts, active, layout, samplingOptions) : undefined;\n\t// Measured as the precision choice measures storage: by the estimate at\n\t// the precision chosen (16-bit storage by its own); with compact storage,\n\t// which that estimate does not know, by the layout.\n\tconst storageAt = (at: Precision, of: Layout): number => compact\n\t\t? of.bytes\n\t\t: Math.max(at === 'i16' ? spot.estimate.compressedBytes : bytes, of.bytes);\n\tconst baselineBytes = samplingPlan ? samplingBytes(samplingPlan) : 0;\n\t// A default 32-bit choice that fits alone but not beside the baselines\n\t// falls back to 16 bits, as a spot too big for 32 bits does.\n\tif (defaulted && precision === 'f32' && samplingPlan && storageAt('f32', layout) + baselineBytes > maxBytes) {\n\t\tprecision = 'i16';\n\t\tlayout = layoutAt(precision);\n\t}\n\tlet storageBytes = storageAt(precision, layout);\n\tif (samplingPlan && storageBytes + baselineBytes > maxBytes) {\n\t\tthrow new Error(\n\t\t\t`chanceSampling needs ${Math.ceil(baselineBytes / 2 ** 20)} MiB of baselines beside ` +\n\t\t\t\t`${Math.ceil(storageBytes / 2 ** 20)} MiB of storage, over maxBytes; sample fewer rounds or raise maxBytes`,\n\t\t);\n\t}\n\n\t// Planned once the precision is settled (beside the baselines) and before\n\t// the accumulators are allocated, so a bad option or a coarse spot that\n\t// does not fit fails here; solved only once the real run exists.\n\t// The real run's storage by the larger of the layout it allocates and the\n\t// estimate the coarse spot is measured by, so neither undercounts it.\n\tconst held = (at: Precision, of: Layout): number =>\n\t\tMath.max(storageAt(at, of), storageCost(spot, at)) + baselineBytes;\n\tlet coarsePlan: CoarsePlan | null;\n\ttry {\n\t\tcoarsePlan = planCoarseStart(spot, options, maxBytes, held(precision, layout));\n\t} catch (error) {\n\t\t// A default 32-bit real run that leaves no room for the coarse one\n\t\t// drops to 16 bits, as it does for the baselines, and the coarse run\n\t\t// with it: never wider than the real one. A bad option, or a coarse\n\t\t// run that does not fit beside 16 bits either, is still refused.\n\t\tif (!(error instanceof CoarseRefusal && defaulted && precision === 'f32')) throw error;\n\t\tprecision = 'i16';\n\t\tlayout = layoutAt(precision);\n\t\tstorageBytes = storageAt(precision, layout);\n\t\tcoarsePlan = planCoarseStart(spot, { ...options, precision }, maxBytes, held(precision, layout));\n\t}\n\n\t// The WebAssembly engine, where it applies: 32-bit storage, or 16-bit and\n\t// compact storage with `wasmStorage`, and a platform with WebAssembly\n\t// SIMD. Decided before the thread count, because the browser build can\n\t// only thread the engine.\n\tconst storageEngine = options.wasmStorage !== undefined && precision !== 'f64' && (precision === 'i16' || compact !== null);\n\tconst wantsEngine =\n\t\toptions.engine !== 'js' && !options.analysisOnly && options.simd !== false &&\n\t\t((precision === 'f32' && !compact) || storageEngine);\n\tconst requested = resolveWorkers(options, wantsEngine);\n\tconst shards = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;\n\t// Threads sample the deals of their own runouts, below the split. A\n\t// sampled round above it would be sampled by the main thread after the\n\t// threads had walked it, so such a spot stays on one thread; the split\n\t// sits at the first round with more than one board, so no flop or turn\n\t// spot has one: this is a guard, not a case a real spot reaches.\n\tconst plan = shards && samplingOptions && sampledRounds(samplingOptions, spot.runouts.rounds).some((r) => r < shards.round)\n\t\t? null\n\t\t: shards;\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\t// The engine owns the storage; the context sees it through views.\n\tconst engine = wantsEngine\n\t\t? createEngine(\n\t\t\t\t{\n\t\t\t\t\ttree: spot.tree, runouts: spot.runouts, players: spot.players, layout, active, hands,\n\t\t\t\t\trunoutWeight: weights, chipScale: spot.chipScale, sampling: samplingPlan,\n\t\t\t\t\t...(storageEngine ? { storage: { source: options.wasmStorage!, quantised, compact } } : {}),\n\t\t\t\t},\n\t\t\t\tplan ? { plan, threads: requested, spawn: spawnEngineWorker } : undefined,\n\t\t\t)\n\t\t: null;\n\tconst engineCompact = engine?.compact ?? null;\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: engine\n\t\t\t? engine.regret\n\t\t\t: options.analysisOnly\n\t\t\t\t? new Float32Array(0)\n\t\t\t\t: makeRegretStore(precision, allocate(layout.totalSlots * width)),\n\t\tstrategySum: engine ? engine.strategySum : makeSumStore(precision, allocate(layout.totalSlots * width)),\n\t\tregretScale: !quantised ? null : engine ? engine.regretScale : new Float64Array(allocate(layout.blocks * 8)),\n\t\tsumScale: !quantised ? null : engine ? engine.sumScale : new Float64Array(allocate(layout.blocks * 8)),\n\t\tcompact,\n\t\tcompactRegret: !compact\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.regret\n\t\t\t\t: layout.chunkSlots.map((slots) =>\n\t\t\t\t\t\tcompact.float ? new Float32Array(allocate(slots * 4)) : new Int8Array(allocate(slots)),\n\t\t\t\t\t),\n\t\thandShift: !compact?.perHand\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.handShift\n\t\t\t\t: layout.chunkHands.map((hands) => new Uint8Array(allocate(hands))),\n\t\tcompactSum: !compact?.sums\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.sum\n\t\t\t\t: layout.chunkSlots.map((slots) => new Uint8Array(allocate(slots))),\n\t\tsumShift: !compact?.sums\n\t\t\t? null\n\t\t\t: engineCompact\n\t\t\t\t? engineCompact.sumShift\n\t\t\t\t: layout.chunkHands.map((hands) => new Uint8Array(allocate(hands))),\n\t\tcompactScale:\n\t\t\t!compact || compact.perHand || compact.float\n\t\t\t\t? null\n\t\t\t\t: engineCompact\n\t\t\t\t\t? engineCompact.scale\n\t\t\t\t\t: new Float64Array(allocate(layout.blocks * 8)),\n\t\tscratch: makeTerminalScratch(),\n\t\tchipScale: spot.chipScale,\n\t\tactive,\n\t\thands,\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\tif (samplingPlan) ctx.sampling = makeSampling(samplingPlan, engine?.sampling ?? undefined, allocate);\n\tif (layout.shared) ctx.discounted = engine?.discounted ?? new Int32Array(layout.blocks);\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\tlet solver: Solver;\n\tlet pool: Pool | null;\n\ttry {\n\t\tif (options.warmCards && !options.warmStart) {\n\t\t\tthrow new Error('`warmCards` relabels a warm start, so it needs `warmStart` too');\n\t\t}\n\t\tif (options.warmStart) {\n\t\t\tconst source = options.warmStart;\n\t\t\twarm = options.warmCards\n\t\t\t\t? warmStart(ctx, source.solver.ctx, false, options.warmCards)\n\t\t\t\t: warmStart(ctx, source.solver.ctx, sameSpot(spot.source, source.spot.source));\n\t\t\toffset = options.warmIteration ?? source.totalIterations;\n\t\t} else if (coarsePlan && coarsePlan.iterations > 0) {\n\t\t\t// Regrets only: the bucketed game's average would have to be outweighed.\n\t\t\tconst coarse = solveCoarse(coarsePlan, options);\n\t\t\ttry {\n\t\t\t\twarm = warmStart(ctx, coarse.solver.ctx, false);\n\t\t\t} finally {\n\t\t\t\tcoarse.close();\n\t\t\t}\n\t\t\toffset = options.warmIteration ?? coarse.totalIterations;\n\t\t}\n\t\t// Inherited accumulators are discounted up to where the count resumes.\n\t\tif (warm) ctx.sampling?.lastUpdate.fill(offset);\n\n\t\tsolver = makeSolver(ctx);\n\t\tif (engine?.profile) threadProfiles.set(solver, engine.profile);\n\t\tif (warm && coarsePlan) coarseMs.set(solver, coarsePlan.elapsed);\n\t\t// The engine runs its own threads; the JavaScript pool is for the rest.\n\t\tpool = plan && !engine\n\t\t\t? startPool(ctx, solver, plan, { config: builtFrom.get(spot) ?? spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd, compact }, requested)\n\t\t\t: null;\n\t} catch (error) {\n\t\t// The engine's threads would otherwise stay parked on this run for good.\n\t\tengine?.close();\n\t\tthrow error;\n\t}\n\tif (pool) solver.useRoot(pool.traverse);\n\tif (engine) solver.useRoot(engine.root(ctx.dcfr));\n\tconst threadCount = pool ? pool.workers : engine ? engine.threads : 1;\n\tlet completed = 0;\n\tconst nextRange = new Float64Array(COMBOS);\n\n\treturn {\n\t\tspot,\n\t\tsolver,\n\t\tworkers: threadCount,\n\t\tget completed() {\n\t\t\treturn completed;\n\t\t},\n\t\twarmStart: warm,\n\t\tengine: engine ? 'wasm' : 'js',\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\tsetRange(player, range, options = {}) {\n\t\t\tif (options.resume !== undefined && !(Number.isInteger(options.resume) && options.resume >= 0)) {\n\t\t\t\tthrow new Error(`setRange: resume must be a whole number of iterations; got ${options.resume}`);\n\t\t\t}\n\t\t\tconst given = typeof range === 'string' ? parseRange(range) : range;\n\t\t\tif (given.length !== COMBOS) {\n\t\t\t\tthrow new Error(`setRange: the range has ${given.length} weights; one per combination is ${COMBOS}`);\n\t\t\t}\n\t\t\tconst index = spot.players[player];\n\t\t\tconst floor = spot.source.minWeight ?? 0;\n\t\t\tconst [first, second, third] = spot.board;\n\t\t\tconst fourth = spot.board[3] ?? -1;\n\t\t\tconst fifth = spot.board[4] ?? -1;\n\t\t\tconst blocked = (card: number): boolean =>\n\t\t\t\tcard === first || card === second || card === third || card === fourth || card === fifth;\n\t\t\t// The range is judged whole before it is said to need a new run:\n\t\t\t// one that is no range at all must not be sent to get one.\n\t\t\tlet live = 0;\n\t\t\tlet unstored = -1;\n\t\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\t\tlet weight = given[combo];\n\t\t\t\tif (!(weight >= 0)) throw new Error(`setRange: a weight is ${weight}; weights are zero or more`);\n\t\t\t\t// The floor first, as `defineSpot` applies it: a hand under it was never stored.\n\t\t\t\tif (weight < floor) weight = 0;\n\t\t\t\tif (weight > 0 && index.slot[combo] < 0) {\n\t\t\t\t\tif (blocked(COMBO_CARDS[combo * 2]) || blocked(COMBO_CARDS[combo * 2 + 1])) weight = 0;\n\t\t\t\t\telse if (unstored < 0) unstored = combo;\n\t\t\t\t}\n\t\t\t\tif (weight > 0) live++;\n\t\t\t\tnextRange[combo] = weight;\n\t\t\t}\n\t\t\tif (live === 0) throw new Error('setRange: the range is empty once the board is removed');\n\t\t\t// Counted pair by pair: the mass, summed by inclusion-exclusion, leaves a rounding residue for none.\n\t\t\tif (!holdable(nextRange, spot.players[1 - player].weights)) {\n\t\t\t\tthrow new Error('setRange: no hand of this range can be held against the other range');\n\t\t\t}\n\t\t\tif (unstored >= 0) {\n\t\t\t\tthrow new RangeNotInPlaceError(\n\t\t\t\t\t`setRange: ${formatCards([COMBO_CARDS[unstored * 2], COMBO_CARDS[unstored * 2 + 1]])} has no storage; ` +\n\t\t\t\t\t\t`a hand can be added only if the range or \\`${player === 0 ? 'oopReserve' : 'ipReserve'}\\` held it when the spot was defined`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const image of spotSymmetries.get(spot) ?? []) {\n\t\t\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\t\t\tif (nextRange[combo] !== nextRange[image[combo]]) {\n\t\t\t\t\t\tthrow new RangeNotInPlaceError(\n\t\t\t\t\t\t\t'setRange: the range breaks a suit symmetry the spot folds runouts by; ' +\n\t\t\t\t\t\t\t\t'keep mirrored hands at one weight, or define the spot with `isomorphism: false`',\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tindex.weights.set(nextRange);\n\t\t\t// The source names every stored hand as reserved, so a spot defined\n\t\t\t// from it stores the hands this one does whatever the range dropped.\n\t\t\t// The spot's own structure stays that of the configuration it was\n\t\t\t// defined with, which is what a worker must rebuild.\n\t\t\tif (!builtFrom.has(spot)) builtFrom.set(spot, spot.source);\n\t\t\tconst stored = Float64Array.from(index.slot, (slot) => (slot >= 0 ? 1 : 0));\n\t\t\t(spot as { source: SpotConfig }).source = player === 0\n\t\t\t\t? { ...spot.source, oop: nextRange.slice(), oopReserve: stored }\n\t\t\t\t: { ...spot.source, ip: nextRange.slice(), ipReserve: stored };\n\t\t\t// The count resumes early, so the discounting forgets the old range's average.\n\t\t\tlet resumed = offset + completed;\n\t\t\tif (ctx.dcfr) {\n\t\t\t\tresumed = Math.min(resumed, options.resume ?? RANGE_RESUME);\n\t\t\t\toffset = resumed - completed;\n\t\t\t} else if (ctx.regret.length > 0 || ctx.compactRegret) {\n\t\t\t\t// CFR+ never discounts its average, so the old range's is\n\t\t\t\t// cleared, a pass over the storage, and the count kept: its\n\t\t\t\t// regrets carry the strategy, and scaled down or counted from\n\t\t\t\t// an earlier iteration they did worse than from cold. Not on\n\t\t\t\t// an analysis-only run, whose loaded average is all it has.\n\t\t\t\tctx.strategySum.fill(0);\n\t\t\t\tctx.sumScale?.fill(0);\n\t\t\t\tctx.compactSum?.forEach((sums) => sums.fill(0));\n\t\t\t\tctx.sumShift?.forEach((shifts) => shifts.fill(0));\n\t\t\t}\n\t\t\t// A shared block's last discount is an iteration the count will pass again.\n\t\t\tctx.discounted?.fill(0);\n\t\t\t// Baselines were the old range's values; discounts are owed from the resumed count.\n\t\t\tctx.sampling?.lastWalk.fill(0);\n\t\t\tctx.sampling?.lastUpdate.fill(resumed);\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\tengine?.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: threadCount,\n\t\t\t\tprecision,\n\t\t\t\twasmStorage: options.wasmStorage,\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(\n\t\t\t\tspot, solver, completed, offset + completed, [...history], stoppedAt, threadCount,\n\t\t\t\toptions.approximations?.currentProfileEv === true,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/** Validate `SpotConfig.compactStorage` into the solver's plan. */\nfunction compactPlan(settings: CompactStorage, rounds: number): CompactPlan {\n\tconst from = settings.from ?? 0;\n\tif (!Number.isInteger(from) || from < 0 || from >= rounds) {\n\t\tthrow new Error(`compactStorage.from must be a round of this spot, 0 to ${rounds - 1}; got ${from}`);\n\t}\n\tconst chunkBytes = settings.chunkBytes ?? 2 ** 30;\n\tif (!Number.isInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new Error(`compactStorage.chunkBytes must be a positive whole number of bytes; got ${chunkBytes}`);\n\t}\n\tconst steps = settings.steps ?? 127;\n\tif (!Number.isInteger(steps) || steps < 1 || steps > 127) {\n\t\tthrow new Error(`compactStorage.steps must be an integer from 1 to 127; got ${steps}`);\n\t}\n\tif (settings.sums !== false && (settings.blockScale || settings.float)) {\n\t\tthrow new Error('compactStorage.sums keeps a scale per hand, so blockScale and float need sums: false');\n\t}\n\treturn {\n\t\tfrom, steps, perHand: !settings.blockScale && !settings.float, stochastic: !settings.nearest,\n\t\tfloat: settings.float === true, chunkBytes, sums: settings.sums ?? true,\n\t};\n}\n\n/** Bucket gap of the coarse spot when `CoarseStart.runoutBuckets` is unset. */\nconst DEFAULT_COARSE_GAP = 3;\n\n/** A coarse start to run: its spot and settings, and once solved, how long it took. */\ninterface CoarsePlan {\n\treadonly spot: Spot;\n\treadonly iterations: number;\n\treadonly precision: Precision;\n\telapsed: number;\n}\n\n/** `planCoarseStart`'s refusal of a coarse spot that does not fit, as against a bad option. */\nclass CoarseRefusal extends Error {}\n\n/** Milliseconds a run's coarse start took, by the real run's solver, for `solve()`'s clock. */\nconst coarseMs = new WeakMap<Solver, number>();\n\n/**\n * Validate `approximations.coarseStart` and define its spot, or null when\n * there is nothing to solve: the option unset, no iterations, or bucketing\n * folds no more runouts than the spot itself does.\n *\n * The coarse spot must fit in what `maxBytes` leaves beside the real one,\n * since both are in memory at the switch; at 32 bits if it can, else 16.\n * `used` is what the real run holds: its storage and, with chance\n * sampling, its baselines. The coarse run's own baselines count too.\n */\nfunction planCoarseStart(spot: Spot, options: SolveOptions, maxBytes: number, used: number): CoarsePlan | null {\n\tconst settings = options.approximations?.coarseStart;\n\tif (!settings) return null;\n\tconst { iterations, runoutBuckets = DEFAULT_COARSE_GAP } = settings;\n\tif (!(Number.isInteger(iterations) && iterations >= 0)) {\n\t\tthrow new Error(`coarseStart.iterations must be a whole number of iterations; got ${iterations}`);\n\t}\n\tif (!(Number.isInteger(runoutBuckets) && runoutBuckets >= 1)) {\n\t\tthrow new Error(`coarseStart.runoutBuckets must be a rank gap of 1 or more; got ${runoutBuckets}`);\n\t}\n\tif (options.warmStart) throw new Error('coarseStart is a warm start of its own; give one or the other, not both');\n\tif (options.analysisOnly) throw new Error('coarseStart solves; an analysis-only run must never be stepped');\n\n\t// Never a narrower gap than the spot already uses, and only a wider one helps.\n\tconst own = spot.source.runoutBuckets;\n\tconst ownGap = own === true ? DEFAULT_BUCKET_GAP : own || 0;\n\tif (iterations === 0 || spot.board.length === 5 || runoutBuckets <= ownGap) return null;\n\tconst coarseSpot = defineSpot({ ...spot.source, runoutBuckets });\n\tif (coarseSpot.runouts.counts.at(-1)! >= spot.runouts.counts.at(-1)!) return null;\n\n\t// A compact spot's coarse spot is compact too: its storage is its layout at\n\t// that precision, beside the rest `estimate.compactBytes` counts at 32 bits.\n\tconst left = maxBytes - used;\n\tconst sampling = options.approximations?.chanceSampling;\n\tconst refuse = (needs: number): Error => new CoarseRefusal(\n\t\t`coarseStart needs ~${formatBytes(needs)} beside this spot's ~${formatBytes(used)}` +\n\t\t\t`${sampling ? ' (storage and chanceSampling baselines, for each)' : ''}, ` +\n\t\t\t`over the ${formatBytes(maxBytes)} limit; raise maxBytes or leave coarseStart off`,\n\t);\n\t// Storage first: where even the smallest storage does not fit, the\n\t// baselines need not be laid out to know it.\n\tconst narrowest = storageCost(coarseSpot, options.precision ?? 'i16');\n\tif (narrowest > left) throw refuse(narrowest);\n\tconst coarseBaselines = sampling ? baselineCost(coarseSpot, sampling) : 0;\n\tconst coarsePrecision: Precision = options.precision ?? (storageCost(coarseSpot, 'f32') + coarseBaselines <= left ? 'f32' : 'i16');\n\tconst needs = storageCost(coarseSpot, coarsePrecision) + coarseBaselines;\n\tif (needs > left) throw refuse(needs);\n\treturn { spot: coarseSpot, iterations, precision: coarsePrecision, elapsed: 0 };\n}\n\n/** Solve a planned coarse start, returning the run to warm-start from. */\nfunction solveCoarse(plan: CoarsePlan, options: SolveOptions): SolveRun {\n\tconst started = Date.now();\n\tconst { coarseStart: _, ...rest } = options.approximations!;\n\tconst run = createRun(plan.spot, {\n\t\tworkers: options.workers,\n\t\tprecision: plan.precision,\n\t\talgorithm: options.algorithm,\n\t\tsimd: options.simd,\n\t\tengine: options.engine,\n\t\twasmStorage: options.wasmStorage,\n\t\tapproximations: rest,\n\t});\n\ttry {\n\t\trun.step(plan.iterations);\n\t} catch (error) {\n\t\trun.close();\n\t\tthrow error;\n\t}\n\tplan.elapsed = Date.now() - started;\n\treturn run;\n}\n\n/**\n * Bytes chance sampling's baselines take for `of`, as `createRun` lays them\n * out. They depend on the layout's blocks, not on its precision.\n */\nfunction baselineCost(of: Spot, sampling: SamplingOptions): number {\n\tconst relevant = new Uint8Array(COMBOS);\n\tfor (const combo of of.players[0].combos) relevant[combo] = 1;\n\tfor (const combo of of.players[1].combos) relevant[combo] = 1;\n\tconst active = buildActiveLists(of.runouts, of.players, buildShowdownTable(of.runouts, relevant));\n\tconst compact = of.source.compactStorage ? compactPlan(of.source.compactStorage, of.runouts.rounds) : undefined;\n\tconst layout = buildLayout(of.tree, of.runouts, of.players, 4, of.historyAlias, compact);\n\treturn samplingBytes(planSampling(of.tree, of.runouts, active, layout, sampling));\n}\n\n/** Bytes `of` takes stored at `at`, compact storage included. */\nexport function storageCost(of: Spot, at: Precision): number {\n\tif (of.estimate.compactBytes === null) {\n\t\treturn at === 'i16' ? of.estimate.compressedBytes : of.estimate.bytes * (at === 'f64' ? 2 : 1);\n\t}\n\tconst plan = compactPlan(of.source.compactStorage!, of.runouts.rounds);\n\tconst bytesAt = (width: number): number =>\n\t\tbuildLayout(of.tree, of.runouts, of.players, width, of.historyAlias, plan).bytes;\n\treturn of.estimate.compactBytes + bytesAt(PRECISION_BYTES[at]) - bytesAt(4);\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\t// `evPot` only says how EV is reported, not what game is played.\n\tconst plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, evPot: _evPot, ...game }: SpotConfig): string =>\n\t\tJSON.stringify(game, (_, value: unknown) => (value instanceof Float64Array ? Array.from(value) : value));\n\tconst kept = (config: SpotConfig): readonly string[] | undefined =>\n\t\ttypeof config.shareHistories === 'object' ? config.shareHistories.keepLines : undefined;\n\tif (kept(a) === undefined && kept(b) === undefined) return plain(a) === plain(b);\n\t// `keepLines` only gives nodes their shared block's own copy, so a warm\n\t// start into a spot keeping every line its source keeps copies each node\n\t// exactly, average included; into one keeping fewer, several histories\n\t// would write one block.\n\tconst mine = new Set(kept(a) ?? []);\n\tif (!(kept(b) ?? []).every((line) => mine.has(line))) return false;\n\treturn plain(withoutKeptLines(a)) === plain(withoutKeptLines(b));\n}\n\n/** `config` with `keepLines` dropped and its sharing in one form: `true` and `{}` alike, unset keys gone. */\nfunction withoutKeptLines(config: SpotConfig): SpotConfig {\n\tconst asked = config.shareHistories;\n\tif (!asked) return config;\n\tconst { keepLines: _kept, ...rest } = asked === true ? {} : asked;\n\tconst set = Object.entries(rest).filter(([, value]) => value !== undefined);\n\treturn { ...config, shareHistories: set.length > 0 ? Object.fromEntries(set) : true };\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\nconst threadWarnings = new Set<string>();\n\n/**\n * Threads a run will use. Anything above what the platform can run now falls\n * back to what it can, with one warning per reason: the browser build threads\n * only the WebAssembly engine, and only after `enableThreads` from\n * `poker-flopsolve/threads` has started its workers.\n * @param options solver tuning\n * @param engine whether the WebAssembly engine is to run\n */\nfunction resolveWorkers(options: SolveOptions, engine: boolean): number {\n\tif (options.analysisOnly) return 1;\n\tconst asked = options.workers === 'auto' ? defaultWorkerCount() : (options.workers ?? 1);\n\tconst limit = threadLimit(engine);\n\tif (asked > limit) {\n\t\tconst advice = threadAdvice(engine);\n\t\tif (!threadWarnings.has(advice)) {\n\t\t\tthreadWarnings.add(advice);\n\t\t\tconsole.warn(`poker-flopsolve: ${asked} threads asked for, solving on ${limit} (${PLATFORM} build): ${advice}`);\n\t\t}\n\t\treturn limit;\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\t// Validated before any storage is taken.\n\tif (options.settle) settlePlan(options.settle);\n\tconst run = createRun(spot, options);\n\ttry {\n\t\treturn runToStop(run, options);\n\t} finally {\n\t\trun.close();\n\t}\n}\n\n/**\n * Run a live run as `solve` runs its own: `iterations` more, or until\n * `targetPercent` or the `settle` rule stops it, reporting to `onProgress`.\n * The run stays open. On a run that has iterations behind it (after\n * `setRange`, say) the settle rule takes the play as it stands as its first\n * reading, so its first check already measures a movement.\n *\n * @param run from {@link createRun}\n * @param options `iterations`, `targetPercent`, `exploitEvery`, `settle` and `onProgress`; the rest set the run up and are not read here\n * @returns a snapshot at the stop\n */\nexport function runToStop(run: SolveRun, options: SolveOptions = {}): Solution {\n\tconst { spot } = run;\n\tconst iterations = options.iterations ?? 500;\n\tconst target = options.targetPercent ?? 0;\n\tconst fixed = options.exploitEvery ?? 0;\n\tconst settle = options.settle ? settlePlan(options.settle) : null;\n\tconst history: Progress[] = [];\n\t// A coarse start solves inside createRun, and that is solving time too.\n\tconst coarse = run.completed === 0 ? coarseMs.get(run.solver) : undefined;\n\tconst started = Date.now() - (coarse ?? 0);\n\t// Where DCFR's count stands before this call's first iteration, for\n\t// predicting the target; only a coarse start shifts it, as a warm start's\n\t// checks were always scheduled from zero.\n\tconst before = coarse !== undefined ? run.totalIterations : 0;\n\treturn runAll();\n\n\tfunction runAll(): Solution {\n\t\tif (settle) return runSettled(settle);\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: StopReason = '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\tbefore + prevIteration,\n\t\t\t\t\tprevExploitability,\n\t\t\t\t\tbefore + done,\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 - before : 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\t/** `settle`'s loop: a cheap root-play check every `every` iterations. */\n\tfunction runSettled(plan: Required<SettleOptions>): Solution {\n\t\tconst tracker = trackSettle(plan);\n\t\tif (run.completed > 0) tracker.check(run.snapshot(), 0);\n\t\tlet stoppedAt: StopReason = 'iterations';\n\t\tlet done = 0;\n\t\twhile (done < iterations) {\n\t\t\tconst until = Math.min(done + plan.every, iterations);\n\t\t\t// A short last step moves the play less; it is not a check.\n\t\t\tconst full = until - done === plan.every;\n\t\t\trun.step(until - done);\n\t\t\tdone = until;\n\t\t\tconst measured = run.snapshot();\n\t\t\tconst settled = full && tracker.check(measured, done);\n\t\t\tconst info: Progress = {\n\t\t\t\titeration: done,\n\t\t\t\texploitability: target > 0 ? measured.exploitability() : Number.NaN,\n\t\t\t\telapsedMs: Date.now() - started,\n\t\t\t\tmovement: full ? tracker.movement : Number.NaN,\n\t\t\t};\n\t\t\thistory.push(info);\n\t\t\toptions.onProgress?.(info);\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\t\t\tif (settled) {\n\t\t\t\tstoppedAt = 'settled';\n\t\t\t\tbreak;\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\tsolver: Solver,\n\titerations: number,\n\ttotalIterations: number,\n\thistory: Progress[],\n\tstoppedAt: StopReason,\n\tworkers: number,\n\tcurrentProfileEv: boolean,\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 => actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], spot.chipScale);\n\n\tconst path = (node: number): string => {\n\t\tconst steps: string[] = [];\n\t\tlet current = node;\n\t\twhile (parent[current] >= 0) {\n\t\t\tconst owner = parent[current];\n\t\t\tsteps.push(tree.kind[owner] === NodeKind.Decision ? label(viaEdge[current]) : '/');\n\t\t\tcurrent = owner;\n\t\t}\n\t\treturn steps.reverse().join(' ') || '(root)';\n\t};\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\t// One pass per player serves `ev` and `handEvs` alike.\n\tlet cachedEv: RootValues | null = null;\n\tconst rootValues = (): RootValues =>\n\t\t(cachedEv ??= solver.rootValues(currentProfileEv ? Mode.Current : Mode.Average));\n\tconst cachedHands: [Float64Array | null, Float64Array | null] = [null, null];\n\tconst cachedChips: [Float64Array | null, Float64Array | null] = [null, null];\n\tlet cachedExploit: number | null = null;\n\t// The pot as the tree holds it, rounded to chip units, so the half-pot\n\t// baseline cancels exactly and a fold reads 0.\n\tconst evPot = spot.source.evPot ?? spot.potUnits / spot.chipScale;\n\t// Chips on the half-pot baseline to a share of `evPot`.\n\tconst share = (chips: number): number => (100 * (chips + evPot / 2)) / evPot;\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\tevPot,\n\t\tev(player) {\n\t\t\treturn share(rootValues().totals[player]);\n\t\t},\n\t\tevChips(player) {\n\t\t\treturn rootValues().totals[player];\n\t\t},\n\t\thandEvs(player) {\n\t\t\tcachedHands[player] ??= solver.handEvs(player, rootValues().values[player], share);\n\t\t\treturn cachedHands[player].slice();\n\t\t},\n\t\thandEvsChips(player) {\n\t\t\tcachedChips[player] ??= solver.handEvs(player, rootValues().values[player]);\n\t\t\treturn cachedChips[player].slice();\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,\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\t// Each player's side of a setting loses the played rounds alike.\n\t\t\tconst laterEach = <T>(value: PerPlayer<T> | undefined, listed: (side: T) => boolean): PerPlayer<T> | undefined =>\n\t\t\t\tvalue === undefined ? undefined : (mapPlayers(value, (side) => later(side, listed(side)) as T) as PerPlayer<T>);\n\t\t\tconst rows = laterEach(source.betSizes, () => true) as SpotConfig['betSizes'];\n\t\t\tconst raiseRows = laterEach(source.raiseSizes, (side) => side !== undefined && raisesPerRound(side));\n\t\t\t// Cuts below the node carry over, re-rooted at it, while the tree\n\t\t\t// keeps the old betting; new betting builds a tree they need not fit.\n\t\t\t// Settings read with `??` fall back when given as undefined, and an\n\t\t\t// unset thinSizes is the full tree the cuts were made on.\n\t\t\tconst keeps = (key: keyof SubgameBetting): boolean =>\n\t\t\t\tkey === 'thinSizes' ? !betting.thinSizes : betting[key] === undefined && ['betSizes', 'maxRaises', 'allowAllIn'].includes(key);\n\t\t\tconst reshaped = TREE_SETTINGS.some((key) => key in betting && !keeps(key));\n\t\t\tconst prefix = node === 0 ? '' : `${path(node)} `;\n\t\t\t// Chips in a path are the actor's total investment, which a subgame\n\t\t\t// counts from its own start: each amount drops by what is already in.\n\t\t\tconst rebase = (step: string): string => {\n\t\t\t\tconst [label, chips] = step.split(' ');\n\t\t\t\treturn chips === undefined ? step : `${label} ${(Math.round(Number(chips) * spot.chipScale) - invested) / spot.chipScale}`;\n\t\t\t};\n\t\t\tconst cuts = source.removeActions\n\t\t\t\t?.filter((line) => line.startsWith(prefix))\n\t\t\t\t.map((line) => line.slice(prefix.length).split(' ').reduce<string[]>((steps, word, i, words) => {\n\t\t\t\t\t// Words come as single actions (\"check\", \"/\") or a label and its chips.\n\t\t\t\t\tif (/^-?[\\d.]+$/.test(word)) steps[steps.length - 1] = rebase(`${words[i - 1]} ${word}`);\n\t\t\t\t\telse steps.push(word);\n\t\t\t\t\treturn steps;\n\t\t\t\t}, []).join(' '));\n\t\t\tconst removeActions =\n\t\t\t\t'removeActions' in betting ? betting.removeActions : reshaped || !cuts || cuts.length === 0 ? undefined : cuts;\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\t// EV stays a share of the original spot's pot down a hand.\n\t\t\t\tevPot,\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 ?? laterEach(source.maxRaises, Array.isArray),\n\t\t\t\tallowAllIn: betting.allowAllIn ?? laterEach(source.allowAllIn, Array.isArray),\n\t\t\t\tallInThreshold: 'allInThreshold' in betting ? betting.allInThreshold : laterEach(source.allInThreshold, Array.isArray),\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\t...(removeActions ? { removeActions } : {}),\n\t\t\t\t// The thinned shape is the whole tree's, so a subgame starts full.\n\t\t\t\t...(betting.thinSizes ? { thinSizes: true } : {}),\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\tcompactStorage: source.compactStorage,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport { formatCards, parseCards };\nexport { compressRanges } from './compress.ts';\nexport type { CompressedRanges, CompressRangesOptions, RangeCompression } from './compress.ts';\nexport { bettingFrom, checkedDown, exploitabilityInExact, keepWithin, liteConfig, litePreset, openLite, solveLite } from './lite.ts';\nexport type { LiteOptions, LitePreset, LiteResolveOptions, LiteSession, LiteSolution, OpenLiteOptions, SolveLiteOptions } from './lite.ts';\nexport type { PresetChanges, SettingChange, SizesCut, Street } from './presets.ts';\n"],"mappings":";AAeA,IAAM,aAAa;AAGnB,IAAM,aAAa;AAEZ,IAAM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AAQ,aAAa,UAAU,OAAO,WAAW,MAAM,OAAO;AAAA,QACzE,YAAY,QAAQ,cAAc,UAAU,OAAO,YAAY,MAAM,OAAO;AAAA,QAC5E,gBAAgB,oBAAoB,UAAU,QAAQ,iBAAiB,UAAU,OAAO,gBAAgB,MAAM,OAAO;AAAA,QACrH,QAAQ,YAAY,UAAU,QAAQ,SAAS,OAAO,WAAW,SAAY,SAAY,MAAM,OAAO,QAAQ,MAAM,QAAQ,OAAO,MAAM,CAAC;AAAA,QAC1I,YAAY,gBAAgB,UAAU,QAAQ,aAAa,OAAO;AAAA,QAClE,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;AAAA;AAAA,QAEzC,GAAI,QAAQ,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;AAAA,QAC/C,WAAW,OAAO;AAAA,QAClB,aAAa,OAAO;AAAA,QACpB,WAAW,eAAe,UAAU,QAAQ,YAAY,OAAO;AAAA,QAC/D,UAAU,cAAc,UAAU,QAAQ,WAAW,OAAO;AAAA,QAC5D,WAAW,KAAK;AAAA,QAChB,gBAAgB,OAAO;AAAA,MACxB;AAAA,IACD;AAAA,EACD;AACD;","names":["fraction","nearest","walk","RANK_CHARS","high","span","i","factory","childCols","regretMatch","p","makeBuffers","treeDepth","factory","stochastic","high","wasm","wasm","treeDepth","bytes","plan","count","REGRET_STEPS","SUM_STEPS","walk","shifts","base","walk","makeBuffers","high","RANKS","SUITS","parseRange","wasm","st","rivers","present","mk","walk","shareHistories","bytes","hands","options","needs","raiseRows","label"]}