poker-flopsolve 0.4.1 → 0.5.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/README.md +936 -86
- package/dist/browser-threads.js +238 -0
- package/dist/browser-threads.js.map +1 -0
- package/dist/browser.js +2195 -396
- package/dist/browser.js.map +1 -1
- package/dist/engine-worker.js +81 -50
- package/dist/engine-worker.js.map +1 -1
- package/dist/index.d.ts +1251 -30
- package/dist/index.js +2178 -392
- package/dist/index.js.map +1 -1
- package/dist/threads.d.ts +41 -0
- package/dist/threads.js +28 -0
- package/dist/threads.js.map +1 -0
- package/dist/wasm-storage.d.ts +84 -0
- package/dist/wasm-storage.js +532 -0
- package/dist/wasm-storage.js.map +1 -0
- package/dist/worker.js +1037 -240
- package/dist/worker.js.map +1 -1
- package/docs/APPROXIMATIONS.md +588 -0
- package/package.json +19 -4
package/dist/worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/worker.ts","../src/cards.ts","../src/eval7.ts","../src/showdown.ts","../src/hands.ts","../src/tree.ts","../src/pairs.ts","../src/wasm/kernels.ts","../src/kernels.ts","../src/cfr.ts","../src/abstraction.ts","../src/runouts.ts","../src/range.ts","../src/platform/node.ts","../src/parallel.ts","../src/index.ts"],"sourcesContent":["/**\n * Solver worker.\n *\n * Purpose: traverse one shard of the runout space.\n *\n * A worker owns a contiguous range of runouts at the split round; the main\n * thread owns the first, so worker `n` takes shard `n + 1`. Because\n * storage is indexed runout-outermost, everything it writes below that round is\n * its own; nothing is shared and nothing is locked. It never visits a node above\n * the split, so the non-linear CFR+ clamp there stays the main thread's job.\n *\n * The spot is rebuilt from its config rather than shipped across as typed\n * arrays: `defineSpot` is deterministic, so both sides derive byte-identical\n * structures, and only the two accumulators are actually shared.\n */\n\nimport { parentPort, workerData } from 'node:worker_threads';\nimport { COMBOS } from './cards.ts';\nimport type { Context, Mode } from './cfr.ts';\nimport {\n\tbuildActiveLists,\n\tbuildLayout,\n\tmakeSolver,\n\tmakeTerminalScratch,\n\tmatchupMass,\n\trunoutWeights,\n} from './cfr.ts';\nimport { defineSpot, makeRegretStore, makeSumStore, PRECISION_BYTES } from './index.ts';\nimport type { Precision, SpotConfig } from './index.ts';\nimport { buildShowdownTable } from './showdown.ts';\nimport { buildHandSpace } from './hands.ts';\nimport type { WorkerSetup } from './parallel.ts';\nimport { COMMAND, CONTROL } from './parallel.ts';\n\nconst setup = workerData as WorkerSetup;\nconst { config, dcfr, precision, simd } = setup.payload as {\n\tconfig: SpotConfig;\n\tdcfr: boolean;\n\tprecision: Precision;\n\tsimd: boolean;\n};\n\nconst spot = defineSpot(config);\nconst relevant = new Uint8Array(COMBOS);\nfor (const combo of spot.players[0].combos) relevant[combo] = 1;\nfor (const combo of spot.players[1].combos) relevant[combo] = 1;\n\nconst weights = runoutWeights(spot.runouts);\nconst layout = buildLayout(spot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision]);\n\nconst showdown = buildShowdownTable(spot.runouts, relevant);\nconst active = buildActiveLists(spot.runouts, spot.players, showdown);\nconst ctx: Context = {\n\ttree: spot.tree,\n\trunouts: spot.runouts,\n\tplayers: spot.players,\n\tlayout,\n\tshowdown,\n\tregret: makeRegretStore(precision, setup.regret),\n\tstrategySum: makeSumStore(precision, setup.strategySum),\n\tregretScale: setup.regretScale ? new Float64Array(setup.regretScale) : null,\n\tsumScale: setup.sumScale ? new Float64Array(setup.sumScale) : null,\n\tscratch: makeTerminalScratch(),\n\tchipScale: spot.chipScale,\n\tactive,\n\thands: buildHandSpace(spot.runouts, spot.players, active),\n\trunoutWeight: weights,\n\ttotalMass: matchupMass(spot.players[0].weights, spot.players[1].weights) * weights[0],\n\tdcfr,\n\tshardStart: setup.shardStart,\n\tshardEnd: setup.shardEnd,\n\tshardRound: setup.plan.round,\n\tapplyUpdates: true,\n\tchanceCollect: null,\n\tchanceOverride: null,\n\tentryIndexOf: null,\n\texpandOrbits: false,\n\tsimd,\n};\n\nconst solver = makeSolver(ctx);\nconst control = new Int32Array(setup.control);\nconst exchange = new Float64Array(setup.exchange);\nconst reachFloats = setup.entryCount * 2 * COMBOS;\nconst partialBase = reachFloats + setup.workerId * setup.entryCount * COMBOS;\n\nconst reachMe = new Float64Array(COMBOS);\nconst reachOpp = new Float64Array(COMBOS);\n\n// Latch the generation BEFORE announcing readiness, so no dispatch that happens\n// after this point can be missed.\nlet generation = Atomics.load(control, CONTROL.generation);\nAtomics.add(control, CONTROL.ready, 1);\nAtomics.notify(control, CONTROL.ready);\n\nfor (;;) {\n\tAtomics.wait(control, CONTROL.generation, generation);\n\tgeneration = Atomics.load(control, CONTROL.generation);\n\tif (Atomics.load(control, CONTROL.command) === COMMAND.exit) break;\n\n\tconst mode = Atomics.load(control, CONTROL.mode) as Mode;\n\tconst traverser = Atomics.load(control, CONTROL.traverser) as 0 | 1;\n\tconst iterWeight = Atomics.load(control, CONTROL.iterWeight);\n\n\tfor (let entry = 0; entry < setup.plan.entryNodes.length; entry++) {\n\t\tconst node = setup.plan.entryNodes[entry];\n\t\tfor (let i = 0; i < COMBOS; i++) {\n\t\t\treachMe[i] = exchange[entry * 2 * COMBOS + i];\n\t\t\treachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];\n\t\t}\n\t\tconst value = solver.traverseChance(mode, traverser, iterWeight, node, reachMe, reachOpp);\n\t\tfor (let i = 0; i < COMBOS; i++) exchange[partialBase + entry * COMBOS + i] = value[i];\n\t}\n\n\tAtomics.add(control, CONTROL.done, 1);\n\tAtomics.notify(control, CONTROL.done);\n}\n\nparentPort?.close();\n","/**\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 * 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}\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/** 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\tfor (let i = 0; i < parentCount; i++) indexOf[lists.list[parentFrom + i]] = i;\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\tfor (let i = 0; i < parentCount; i++) indexOf[lists.list[parentFrom + i]] = -1;\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\tfor (let j = 0; j < otherCount; j++) indexOf[lists.list[otherFrom + j]] = j;\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\tfor (let j = 0; j < otherCount; j++) indexOf[lists.list[otherFrom + j]] = -1;\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 * 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}\n\n/**\n * Collapse pot-fraction sizes closer together than `distance` into their mean.\n * Other kinds of size pass through untouched, after the merged ones.\n */\nexport function mergeBetSizes(sizes: readonly BetSize[], distance: number): BetSize[] {\n\tif (!(distance > 0)) return [...sizes];\n\tconst fractions = sizes.filter((size): size is number => typeof size === 'number').sort((a, b) => a - b);\n\tconst others = sizes.filter((size) => typeof size !== 'number');\n\tconst merged: number[] = [];\n\tlet cluster: number[] = [];\n\tconst flush = (): void => {\n\t\tif (cluster.length === 0) return;\n\t\tmerged.push(Math.round((cluster.reduce((a, b) => a + b, 0) / cluster.length) * 1000) / 1000);\n\t\tcluster = [];\n\t};\n\tfor (const size of fractions) {\n\t\tif (cluster.length > 0 && size - cluster[0] >= distance) flush();\n\t\tcluster.push(size);\n\t}\n\tflush();\n\treturn [...merged, ...others];\n}\n\n/** Structure-of-arrays betting tree. */\nexport interface Tree {\n\treadonly nodeCount: number;\n\treadonly edgeCount: number;\n\treadonly kind: Uint8Array;\n\t/** Player to act at a decision node, else -1. 0 is out of position. */\n\treadonly player: Int8Array;\n\treadonly round: Uint8Array;\n\treadonly firstEdge: Int32Array;\n\treadonly numEdges: Uint8Array;\n\t/** Total in the middle at this node, in units, including the dead pot. */\n\treadonly pot: Int32Array;\n\t/**\n\t * TerminalFold: value to player 0, signed, in units.\n\t * TerminalShowdown: what the winner gains, in units.\n\t */\n\treadonly payoff: Int32Array;\n\treadonly edgeAction: Uint8Array;\n\t/** The actor's total investment after acting, in units. */\n\treadonly edgeTarget: Int32Array;\n\treadonly edgeChild: Int32Array;\n\treadonly decisionNodes: Int32Array;\n}\n\ninterface BetState {\n\treadonly round: number;\n\treadonly invested: readonly [number, number];\n\treadonly toAct: 0 | 1;\n\treadonly aggressions: number;\n\treadonly lastRaise: number;\n\treadonly acted: number;\n\t/** What each player had in when this round opened; equal for both. */\n\treadonly base: number;\n\t/** Who last bet or raised this round, or -1. */\n\treadonly aggressor: number;\n\t/** Who last bet or raised the round before, or -1. */\n\treadonly previousAggressor: number;\n}\n\n/**\n * Build the betting tree for a spot.\n *\n * @param config betting structure, in units\n * @param runouts board completions, which fix the number of rounds\n */\nexport function buildTree(config: TreeConfig, runouts: Runouts): Tree {\n\tconst kind: number[] = [];\n\tconst player: number[] = [];\n\tconst round: number[] = [];\n\tconst firstEdge: number[] = [];\n\tconst numEdges: number[] = [];\n\tconst pot: number[] = [];\n\tconst payoff: number[] = [];\n\tconst edgeAction: number[] = [];\n\tconst edgeTarget: number[] = [];\n\tconst edgeChild: number[] = [];\n\n\tconst { potUnits, stackUnits, chipScale, minRaiseUnits } = config;\n\tconst rounds = runouts.rounds;\n\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\n\tconst addNode = (\n\t\tnodeKind: number,\n\t\tnodePlayer: number,\n\t\tnodeRound: number,\n\t\tnodePot: number,\n\t\tnodePayoff: number,\n\t): number => {\n\t\tkind.push(nodeKind);\n\t\tplayer.push(nodePlayer);\n\t\tround.push(nodeRound);\n\t\tfirstEdge.push(-1);\n\t\tnumEdges.push(0);\n\t\tpot.push(nodePot);\n\t\tpayoff.push(nodePayoff);\n\t\treturn kind.length - 1;\n\t};\n\n\t/** What follows once a round's betting has closed. */\n\tconst closeRound = (state: BetState): number => {\n\t\tconst total = potUnits + state.invested[0] + state.invested[1];\n\t\tconst allIn = state.invested[0] >= stackUnits || state.invested[1] >= stackUnits;\n\n\t\tif (state.round + 1 >= runouts.rounds) {\n\t\t\t// Both invested the same, so the winner gains half the dead pot plus\n\t\t\t// the opponent's investment.\n\t\t\treturn addNode(NodeKind.TerminalShowdown, -1, state.round, total, half + state.invested[0]);\n\t\t}\n\n\t\tconst node = addNode(NodeKind.Chance, -1, state.round, total, 0);\n\t\tconst next: BetState = {\n\t\t\tround: state.round + 1,\n\t\t\tinvested: state.invested,\n\t\t\ttoAct: 0,\n\t\t\taggressions: 0,\n\t\t\tlastRaise: minRaiseUnits,\n\t\t\tacted: 0,\n\t\t\tbase: state.invested[0],\n\t\t\taggressor: -1,\n\t\t\tpreviousAggressor: state.aggressor,\n\t\t};\n\t\t// With someone already all in there is nothing left to decide, so the\n\t\t// remaining streets run out straight to showdown.\n\t\tconst child = allIn ? closeRound(next) : buildDecision(next);\n\n\t\tfirstEdge[node] = edgeChild.length;\n\t\tnumEdges[node] = 1;\n\t\tedgeAction.push(ActionKind.Check);\n\t\tedgeTarget.push(0);\n\t\tedgeChild.push(child);\n\t\treturn node;\n\t};\n\n\t/** Resolve one bet size to a total-investment target, or null if illegal. */\n\tconst resolveTarget = (size: BetSize, state: BetState, cap: number): number | null => {\n\t\tconst me = state.toAct;\n\t\tconst opp = (1 - me) as 0 | 1;\n\t\tconst mine = state.invested[me];\n\t\tconst theirs = state.invested[opp];\n\t\tconst owed = Math.max(0, theirs - mine);\n\t\tconst potAfterCall = potUnits + state.invested[0] + state.invested[1] + owed;\n\n\t\tlet target: number;\n\t\tif (size === 'allin') target = cap;\n\t\telse if (typeof size === 'number') target = mine + owed + Math.round(size * potAfterCall);\n\t\telse if ('times' in size) target = state.base + Math.round(size.times * (theirs - state.base));\n\t\telse target = mine + owed + Math.round(size.chips * chipScale);\n\n\t\ttarget = Math.min(target, cap);\n\t\tif (target <= theirs) return null;\n\n\t\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): 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 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\tactions.push({\n\t\t\t\t\taction: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet,\n\t\t\t\t\ttarget,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst base = edgeChild.length;\n\t\tfirstEdge[node] = base;\n\t\tnumEdges[node] = actions.length;\n\t\tfor (const entry of actions) {\n\t\t\tedgeAction.push(entry.action);\n\t\t\tedgeTarget.push(entry.target);\n\t\t\tedgeChild.push(-1);\n\t\t}\n\n\t\tactions.forEach((entry, i) => {\n\t\t\tconst invested: [number, number] =\n\t\t\t\tme === 0 ? [entry.target, theirs] : [theirs, entry.target];\n\t\t\tlet child: number;\n\n\t\t\tif (entry.action === ActionKind.Fold) {\n\t\t\t\t// The folder forfeits what they put in, and the dead pot goes\n\t\t\t\t// to the other player.\n\t\t\t\tconst value = me === 0 ? -(half + mine) : half + mine;\n\t\t\t\tchild = addNode(NodeKind.TerminalFold, -1, state.round, total, value);\n\t\t\t} else if (entry.action === ActionKind.Check || entry.action === ActionKind.Call) {\n\t\t\t\tconst closed = invested[0] === invested[1] && state.acted + 1 >= 2;\n\t\t\t\tchild = closed\n\t\t\t\t\t? closeRound({ ...state, invested, acted: state.acted + 1 })\n\t\t\t\t\t: buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 });\n\t\t\t} else {\n\t\t\t\tchild = buildDecision({\n\t\t\t\t\tround: state.round,\n\t\t\t\t\tinvested,\n\t\t\t\t\ttoAct: opp,\n\t\t\t\t\taggressions: state.aggressions + 1,\n\t\t\t\t\tlastRaise: entry.target - theirs,\n\t\t\t\t\tacted: state.acted + 1,\n\t\t\t\t\tbase: state.base,\n\t\t\t\t\taggressor: me,\n\t\t\t\t\tpreviousAggressor: state.previousAggressor,\n\t\t\t\t});\n\t\t\t}\n\t\t\tedgeChild[base + i] = child;\n\t\t});\n\n\t\treturn node;\n\t};\n\n\tbuildDecision({\n\t\tround: 0,\n\t\tinvested: [0, 0],\n\t\ttoAct: 0,\n\t\taggressions: 0,\n\t\tlastRaise: minRaiseUnits,\n\t\tacted: 0,\n\t\tbase: 0,\n\t\taggressor: -1,\n\t\tpreviousAggressor: -1,\n\t});\n\n\tconst decisionNodes: number[] = [];\n\tfor (let i = 0; i < kind.length; i++) if (kind[i] === NodeKind.Decision) decisionNodes.push(i);\n\n\treturn {\n\t\tnodeCount: kind.length,\n\t\tedgeCount: edgeChild.length,\n\t\tkind: Uint8Array.from(kind),\n\t\tplayer: Int8Array.from(player),\n\t\tround: Uint8Array.from(round),\n\t\tfirstEdge: Int32Array.from(firstEdge),\n\t\tnumEdges: Uint8Array.from(numEdges),\n\t\tpot: Int32Array.from(pot),\n\t\tpayoff: Int32Array.from(payoff),\n\t\tedgeAction: Uint8Array.from(edgeAction),\n\t\tedgeTarget: Int32Array.from(edgeTarget),\n\t\tedgeChild: Int32Array.from(edgeChild),\n\t\tdecisionNodes: Int32Array.from(decisionNodes),\n\t};\n}\n","/**\n * Values against single opposing hands, many at once.\n *\n * Purpose: answer \"what is each of my hands worth against that one hand of\n * theirs, from here on\" for a whole list of their hands in one walk of the\n * tree. `valuesAt` with a one-hot opponent reach gives the same numbers, one\n * opposing hand per walk; this shares everything that does not depend on the\n * opposing hand:\n *\n * - the tree walk itself, and every average-strategy lookup on the way;\n * - the traverser's reach, which never depends on the opposing hand;\n * - terminals, where a single opposing hand needs no card-removal kernel:\n * at a fold every hand not sharing a card wins or loses the same amount,\n * and at a showdown it is a comparison of two strengths.\n *\n * An opposing hand drops out of the walk as soon as its own strategy stops\n * reaching a line, or a dealt card hits it, so lines a hand never takes cost\n * nothing for it.\n *\n * Reads the average strategy only. Results match `valuesAt` with a one-hot\n * reach to floating-point accuracy.\n */\n\nimport { COMBO_CARDS, COMBOS } from './cards.ts';\nimport type { Context } from './cfr.ts';\nimport { averageStrategy } from './cfr.ts';\nimport { NodeKind } from './tree.ts';\n\n/** Opposing hands per walk; more share the walk better but need more memory. */\nconst CHUNK = 64;\n\ninterface PairBuffers {\n\treadonly value: Float64Array[];\n\treadonly cols: Int32Array[];\n\treadonly colReach: Float64Array[];\n\treadonly live: Uint16Array[];\n\t/** Opposing hands relabelled onto a stored board, per depth. */\n\treadonly hands: Uint16Array[];\n\treadonly strategy: Float64Array[];\n\treadonly rank: Int32Array;\n\t/** A combination's position in the current decision's hand list. */\n\treadonly position: 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),\n\t};\n}\n\n/**\n * Counterfactual values for `traverser` from `node` on `board`, against each\n * opposing hand alone.\n *\n * @param hands the opposing hands, one per result row\n * @param handReach each opposing hand's reach at `node`\n * @returns `hands.length * COMBOS` values; row `k` is what `valuesAt` returns\n * for an opponent reach holding only `hands[k]` at `handReach[k]`\n */\nexport function pairValues(\n\tctx: Context,\n\tnode: number,\n\tboard: number,\n\ttraverser: 0 | 1,\n\thands: Uint16Array,\n\thandReach: Float64Array,\n\tlive: Uint16Array,\n\tliveCount: number,\n): Float64Array {\n\tconst result = new Float64Array(hands.length * COMBOS);\n\tif (hands.length === 0) return result;\n\tconst width = Math.min(CHUNK, hands.length);\n\tconst buffers = makeBuffers(ctx, width);\n\t// Only the traverser's own hands get a value, so only they are carried.\n\tconst mine = new Uint16Array(liveCount);\n\tlet mineCount = 0;\n\tfor (let i = 0; i < liveCount; i++) if (ctx.players[traverser].slot[live[i]] >= 0) mine[mineCount++] = live[i];\n\tfor (let start = 0; start < hands.length; start += width) {\n\t\tconst chunk = hands.subarray(start, Math.min(hands.length, start + width));\n\t\tconst colReach = buffers.colReach[0];\n\t\tconst cols = buffers.cols[0];\n\t\tlet count = 0;\n\t\tfor (let k = 0; k < chunk.length; k++) {\n\t\t\tcolReach[k] = handReach[start + k];\n\t\t\tif (colReach[k] !== 0) cols[count++] = k;\n\t\t}\n\t\tconst value = walk(ctx, buffers, traverser, chunk, node, board, colReach, cols, count, mine, mineCount, 0);\n\t\tfor (let c = 0; c < count; c++) {\n\t\t\tconst k = cols[c];\n\t\t\tconst row = value.subarray(k * COMBOS, (k + 1) * COMBOS);\n\t\t\tfor (let i = 0; i < mineCount; i++) result[(start + k) * COMBOS + mine[i]] = row[mine[i]];\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction walk(\n\tctx: Context,\n\tbuffers: PairBuffers,\n\ttraverser: 0 | 1,\n\thands: Uint16Array,\n\tnode: number,\n\tboard: number,\n\tcolReach: Float64Array,\n\tcols: Int32Array,\n\tcolCount: number,\n\tlive: Uint16Array,\n\tliveCount: number,\n\tdepth: number,\n): Float64Array {\n\tconst { tree, runouts } = ctx;\n\tconst out = buffers.value[depth];\n\tconst kind = tree.kind[node];\n\tconst cards = COMBO_CARDS;\n\n\tfor (let c = 0; c < colCount; c++) {\n\t\tconst row = cols[c] * COMBOS;\n\t\tfor (let i = 0; i < liveCount; i++) out[row + live[i]] = 0;\n\t}\n\tif (colCount === 0) return out;\n\n\tif (kind === NodeKind.TerminalFold) {\n\t\tconst signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];\n\t\tconst weight = (signed * ctx.runoutWeight[tree.round[node]]) / ctx.chipScale;\n\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\tconst k = cols[c];\n\t\t\tconst a = cards[hands[k] * 2];\n\t\t\tconst b = cards[hands[k] * 2 + 1];\n\t\t\tconst v = weight * colReach[k];\n\t\t\tconst row = k * COMBOS;\n\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\tconst combo = live[i];\n\t\t\t\tconst x = cards[combo * 2];\n\t\t\t\tconst y = cards[combo * 2 + 1];\n\t\t\t\tif (x !== a && x !== b && y !== a && y !== b) out[row + combo] = v;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.TerminalShowdown) {\n\t\tconst weight = (tree.payoff[node] * ctx.runoutWeight[tree.round[node]]) / ctx.chipScale;\n\t\t// Strength on this final board as a tie-group index.\n\t\tconst table = ctx.showdown;\n\t\tconst rank = buffers.rank;\n\t\tconst orderBase = board * table.stride;\n\t\tconst groupBase = board * (table.stride + 1);\n\t\tfor (let g = 0; g < table.groupCount[board]; g++) {\n\t\t\tfor (let i = table.groupStart[groupBase + g]; i < table.groupStart[groupBase + g + 1]; i++) {\n\t\t\t\trank[table.order[orderBase + i]] = g;\n\t\t\t}\n\t\t}\n\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\tconst k = cols[c];\n\t\t\tconst theirs = hands[k];\n\t\t\tconst a = cards[theirs * 2];\n\t\t\tconst b = cards[theirs * 2 + 1];\n\t\t\tconst strength = rank[theirs];\n\t\t\tconst v = weight * colReach[k];\n\t\t\tconst row = k * COMBOS;\n\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\tconst combo = live[i];\n\t\t\t\tconst x = cards[combo * 2];\n\t\t\t\tconst y = cards[combo * 2 + 1];\n\t\t\t\tif (x === a || x === b || y === a || y === b) continue;\n\t\t\t\tconst mine = rank[combo];\n\t\t\t\tif (mine > strength) out[row + combo] = v;\n\t\t\t\telse if (mine < strength) out[row + combo] = -v;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tif (kind === NodeKind.Chance) {\n\t\tconst nextRound = tree.round[node] + 1;\n\t\tconst child = tree.edgeChild[tree.firstEdge[node]];\n\t\tconst width = runouts.width[nextRound];\n\t\tconst dealtCards = runouts.cards[nextRound];\n\t\tconst orbitStart = runouts.orbitStart[nextRound];\n\t\tconst childLive = buffers.live[depth];\n\t\tconst childCols = buffers.cols[depth + 1];\n\t\tconst mappedHands = buffers.hands[depth];\n\n\t\tfor (let childBoard = runouts.childStart[nextRound][board]; childBoard < runouts.childStart[nextRound][board + 1]; childBoard++) {\n\t\t\t// Every deal this board stands for, the stored one first. The\n\t\t\t// opposing hands are an arbitrary list, not a symmetric range, so a\n\t\t\t// mirrored deal is walked with every hand relabelled onto the\n\t\t\t// stored board rather than assumed equal to it.\n\t\t\tfor (let m = orbitStart[childBoard]; m < orbitStart[childBoard + 1]; m++) {\n\t\t\t\tconst dealt = m === orbitStart[childBoard] ? dealtCards[childBoard * width + width - 1] : runouts.orbitCard[nextRound][m];\n\t\t\t\tconst map = runouts.maps.combo[runouts.orbitMap[nextRound][m]];\n\n\t\t\t\tlet childCount = 0;\n\t\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\t\tconst combo = live[i];\n\t\t\t\t\tif (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;\n\t\t\t\t\tchildLive[childCount++] = map[combo];\n\t\t\t\t}\n\t\t\t\tlet childColCount = 0;\n\t\t\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\t\t\tconst k = cols[c];\n\t\t\t\t\tif (cards[hands[k] * 2] !== dealt && cards[hands[k] * 2 + 1] !== dealt) childCols[childColCount++] = k;\n\t\t\t\t}\n\t\t\t\tif (childColCount === 0) continue;\n\t\t\t\tfor (let k = 0; k < hands.length; k++) mappedHands[k] = map[hands[k]];\n\n\t\t\t\tconst value = walk(\n\t\t\t\t\tctx, buffers, traverser, mappedHands.subarray(0, hands.length), child, childBoard, colReach,\n\t\t\t\t\tchildCols, childColCount, childLive, childCount, depth + 1,\n\t\t\t\t);\n\t\t\t\tfor (let c = 0; c < childColCount; c++) {\n\t\t\t\t\tconst row = childCols[c] * COMBOS;\n\t\t\t\t\tfor (let i = 0; i < liveCount; i++) {\n\t\t\t\t\t\tconst combo = live[i];\n\t\t\t\t\t\tif (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;\n\t\t\t\t\t\tout[row + combo] += value[row + map[combo]];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t// --- decision ---\n\tconst actions = tree.numEdges[node];\n\tconst edgeBase = tree.firstEdge[node];\n\tconst owner = tree.player[node] as 0 | 1;\n\tconst lists = ctx.active;\n\tconst listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;\n\tconst active = lists.list;\n\tconst activeFrom = lists.start[listSlot];\n\tconst activeCount = lists.count[listSlot];\n\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\taverageStrategy(ctx.strategySum, slotBase, actions, stride, strategy, ctx.regret);\n\n\t// The traverser's values are counterfactual: its own reach never enters.\n\tif (owner === traverser) {\n\t\tfor (let a = 0; a < actions; a++) {\n\t\t\tconst offset = a * COMBOS;\n\t\t\tconst value = walk(\n\t\t\t\tctx, buffers, traverser, hands, tree.edgeChild[edgeBase + a], board, colReach,\n\t\t\t\tcols, colCount, live, liveCount, depth + 1,\n\t\t\t);\n\t\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\t\tconst row = cols[c] * COMBOS;\n\t\t\t\tfor (let i = 0; i < activeCount; i++) {\n\t\t\t\t\tconst combo = active[activeFrom + i];\n\t\t\t\t\tout[row + combo] += strategy[a * stride + i] * value[row + combo];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t// The opposing hands act: each column follows its own hand's strategy.\n\tconst childReach = buffers.colReach[depth + 1];\n\tconst childCols = buffers.cols[depth + 1];\n\t// Each opposing hand's position in the acting player's list here.\n\tconst position = buffers.position;\n\tfor (let i = 0; i < activeCount; i++) position[active[activeFrom + i]] = i;\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst offset = a * COMBOS;\n\t\tlet childCount = 0;\n\t\tfor (let c = 0; c < colCount; c++) {\n\t\t\tconst k = cols[c];\n\t\t\tconst r = colReach[k] * strategy[a * stride + position[hands[k]]];\n\t\t\tchildReach[k] = r;\n\t\t\tif (r !== 0) childCols[childCount++] = k;\n\t\t}\n\t\tif (childCount === 0) continue;\n\t\tconst value = walk(\n\t\t\tctx, buffers, traverser, hands, tree.edgeChild[edgeBase + a], board, childReach,\n\t\t\tchildCols, childCount, live, liveCount, depth + 1,\n\t\t);\n\t\tfor (let c = 0; c < childCount; c++) {\n\t\t\tconst row = childCols[c] * COMBOS;\n\t\t\tfor (let i = 0; i < liveCount; i++) out[row + live[i]] += value[row + live[i]];\n\t\t}\n\t}\n\treturn out;\n}\n","// Generated by scripts/build-wasm.ts from assembly/kernels.ts. Do not edit.\n/** The SIMD kernels, 1327 bytes of WebAssembly. */\nexport const KERNELS_WASM = 'AGFzbQEAAAABEwJgBX9/f39/AGAHf39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBycDC3JlZ3JldE1hdGNoAAAMYXZlcmFnZU1hdGNoAAEGbWVtb3J5AgAK0AkC8AMDB38BfAJ7IARBfnEhCANAIAQgBUoEQCACIAVBA3RqRAAAAAAAAAAAOQMAIAVBAWohBQwBCwsDQCADIAZKBEAgBCAGbEEDdCEJQQAhBQNAIAUgCEgEQCAFQQN0IgogCWoiCyAAav0ABAD9DAAAAAAAAAAAAAAAAAAAAAD99QEhDSABIAtqIA39CwQAIAIgCmoiCiAK/QAEACAN/fAB/QsEACAFQQJqIQUMAQsLA0AgBCAFSgRAIAVBA3QiCiAAIAlqaisDACIMRAAAAAAAAAAAIAxEAAAAAAAAAABkGyEMIAEgCWogCmogDDkDACACIApqIgogCisDACAMoDkDACAFQQFqIQUMAQsLIAZBAWohBgwBCwtEAAAAAAAA8D8gA7ej/RQhDgNAIAMgB0oEQCAEIAdsQQN0IQVBACEAA0AgACAISARAIABBA3QiBiABIAVqaiIJIAn9AAQAIAIgBmr9AAQAIg398wEgDiAN/QwAAAAAAAAAAAAAAAAAAAAA/Ur9Uv0LBAAgAEECaiEADAELCwNAIAAgBEgEQCAA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oMAQsLCw==';\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, showdownValuesHands } 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/** 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`.\n\t */\n\treadonly offset: Int32Array;\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\treadonly maxActions: number;\n\treadonly bytes: number;\n}\n\n/**\n * Size storage. A node's block is `boards * actions * combosOfItsOwner`.\n * @param bytesPerElement 8 for float64, 4 for float32, 2 for 16-bit, which\n * also keeps one float64 scale per block for each accumulator\n */\nexport function buildLayout(\n\ttree: Tree,\n\trunouts: Runouts,\n\tplayers: readonly [PlayerIndex, PlayerIndex],\n\tbytesPerElement: number,\n): Layout {\n\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]]) live++;\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 Int32Array(tree.nodeCount).fill(-1);\n\tconst blockOffset = new Int32Array(tree.nodeCount).fill(-1);\n\tlet total = 0;\n\tlet blocks = 0;\n\tlet maxActions = 0;\n\tfor (let i = 0; i < tree.decisionNodes.length; i++) {\n\t\tconst node = tree.decisionNodes[i];\n\t\tconst actions = tree.numEdges[node];\n\t\tif (actions > maxActions) maxActions = actions;\n\t\toffset[node] = total;\n\t\tblockOffset[node] = blocks;\n\t\ttotal += actions * totals[tree.round[node] * 2 + tree.player[node]];\n\t\tblocks += runouts.counts[tree.round[node]];\n\t}\n\tconst scales = bytesPerElement === 2 ? blocks * 8 * 2 : 0;\n\treturn {\n\t\toffset, blockOffset, blocks, totalSlots: total, maxActions, rowStart, roundBase,\n\t\tbytes: total * bytesPerElement * 2 + scales,\n\t};\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\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/** Accumulated strategy sums: float, or 16-bit integers scaled per block. */\nexport type SumStore = Float64Array | Float32Array | Uint16Array;\n\n/** Largest magnitudes 16-bit storage encodes. */\nconst REGRET_STEPS = 32767;\nconst SUM_STEPS = 65535;\n\n/** Everything a traversal needs. */\nexport interface Context {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly showdown: ShowdownTable;\n\treadonly regret: RegretStore;\n\treadonly strategySum: SumStore;\n\t/**\n\t * Per-block scales when the accumulators are 16-bit, else null: a stored\n\t * integer `q` in block `b` means `q * scale[b]`. Only updates need them.\n\t * Everything that reads a strategy divides each hand's values by their own\n\t * total within one block, so the scale cancels and the integers are read\n\t * as they are.\n\t */\n\treadonly regretScale: Float64Array | null;\n\treadonly sumScale: Float64Array | null;\n\treadonly scratch: TerminalScratch;\n\treadonly chipScale: number;\n\t/** Which combinations each player can hold on each board. */\n\treadonly active: ActiveLists;\n\t/** 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}\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/**\n\t * Hands that mirror each other on a board with symmetry left, whose\n\t * accumulators are kept equal, indexed by the same slot as `start`:\n\t * `ties[tieStart[slot]..tieStart[slot + 1]]` is a run of classes, each its\n\t * size then that many positions in the board's hand list. Empty almost\n\t * everywhere.\n\t */\n\treadonly tieStart: Int32Array;\n\treadonly ties: 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}\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 entries: number[] = [];\n\tconst entrySlots: number[] = [];\n\tconst onBoard = new Uint8Array(DECK);\n\n\tfor (let round = 0; round < runouts.rounds; round++) {\n\t\tconst width = runouts.width[round];\n\t\tconst cards = runouts.cards[round];\n\t\tfor (let board = 0; board < runouts.counts[round]; board++) {\n\t\t\tonBoard.fill(0);\n\t\t\tfor (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst index = players[player];\n\t\t\t\tconst slot = (roundBase[round] + board) * 2 + player;\n\t\t\t\tstart[slot] = entries.length;\n\t\t\t\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\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\tentries.push(index.combos[i]);\n\t\t\t\t\tentrySlots.push(i);\n\t\t\t\t}\n\t\t\t\tcount[slot] = entries.length - start[slot];\n\t\t\t}\n\t\t}\n\t}\n\t// Tie classes. A board's stabiliser fixes it, so it permutes the hands\n\t// live on it; a player's range is unchanged by it, so the image of one of\n\t// their hands is theirs too.\n\tconst tieStart = new Int32Array(slots + 1);\n\tconst ties: number[] = [];\n\tfor (let round = 0; round < runouts.rounds; round++) {\n\t\tconst stabStart = runouts.stabiliserStart[round];\n\t\tconst stabMap = runouts.stabiliserMap[round];\n\t\tfor (let board = 0; board < runouts.counts[round]; board++) {\n\t\t\tfor (let player = 0; player < 2; player++) {\n\t\t\t\tconst slot = (roundBase[round] + board) * 2 + player;\n\t\t\t\ttieStart[slot] = ties.length;\n\t\t\t\tif (stabStart[board + 1] - stabStart[board] < 2) continue;\n\t\t\t\t// Members are positions in this board's hand list, which is\n\t\t\t\t// how storage is laid out.\n\t\t\t\tconst position = new Map<number, number>();\n\t\t\t\tfor (let e = start[slot]; e < start[slot] + count[slot]; e++) position.set(entries[e], e - start[slot]);\n\t\t\t\tconst seen = new Uint8Array(count[slot]);\n\t\t\t\tfor (let e = start[slot]; e < start[slot] + count[slot]; e++) {\n\t\t\t\t\tif (seen[e - start[slot]]) continue;\n\t\t\t\t\tconst members: number[] = [];\n\t\t\t\t\tfor (let k = stabStart[board]; k < stabStart[board + 1]; k++) {\n\t\t\t\t\t\tconst image = position.get(runouts.maps.combo[stabMap[k]][entries[e]]);\n\t\t\t\t\t\tif (image === undefined || seen[image]) continue;\n\t\t\t\t\t\tseen[image] = 1;\n\t\t\t\t\t\tmembers.push(image);\n\t\t\t\t\t}\n\t\t\t\t\tif (members.length > 1) ties.push(members.length, ...members);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ttieStart[slots] = ties.length;\n\n\tconst list = Uint16Array.from(entries);\n\tconst cardA = new Uint8Array(list.length);\n\tconst cardB = new Uint8Array(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}\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\ttieStart, ties: Int32Array.from(ties), cardA, cardB, strength,\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/**\n * Make mirrored hands' accumulators equal, by averaging each tie class.\n *\n * Their updates are equal in exact arithmetic but not in floating point, and\n * regret matching is discontinuous at zero, so left alone the copies drift to\n * genuinely different strategies — and the reach that flows from them stops\n * being symmetric, which is what lets a stored board stand for its mirror\n * images. Averaging restores exact equality after every update. It is CFR on\n * the folded game, where the mirrored hands are one information set.\n */\nexport function tieMirrors(\n\tstore: RegretStore | SumStore,\n\tslotBase: number,\n\tactions: number,\n\tstride: number,\n\tties: Int32Array,\n\tfrom: number,\n\tto: number,\n\tinteger: boolean,\n): void {\n\tfor (let a = 0; a < actions; a++) {\n\t\tconst row = slotBase + a * stride;\n\t\tfor (let k = from; k < to; ) {\n\t\t\tconst size = ties[k];\n\t\t\tlet sum = 0;\n\t\t\tfor (let j = 1; j <= size; j++) sum += store[row + ties[k + j]];\n\t\t\tlet mean = sum / size;\n\t\t\tif (integer) mean = Math.round(mean);\n\t\t\tfor (let j = 1; j <= size; j++) store[row + ties[k + j]] = mean;\n\t\t\tk += size + 1;\n\t\t}\n\t}\n}\n\n/**\n * Tie mirrored hands on one node and board, as every update does; for code\n * that writes accumulators outside a traversal, such as a warm start.\n */\nexport function tieBlock(ctx: Context, node: number, board: number): void {\n\tconst { tree } = ctx;\n\tconst owner = tree.player[node];\n\tconst lists = ctx.active;\n\tconst listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;\n\tconst from = lists.tieStart[listSlot];\n\tconst to = lists.tieStart[listSlot + 1];\n\tif (from === to) return;\n\tconst actions = tree.numEdges[node];\n\tconst count = lists.count[listSlot];\n\tconst base = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];\n\tconst integer = ctx.regretScale !== null;\n\tif (ctx.regret.length > 0) tieMirrors(ctx.regret, base, actions, count, lists.ties, from, to, integer);\n\ttieMirrors(ctx.strategySum, base, actions, count, lists.ties, from, to, integer);\n}\n\n/** Per-depth buffers, so the hot loop never allocates. */\ninterface Buffers {\n\treadonly value: Float64Array[];\n\t/**\n\t * Reach buffers per player. Only ever written at that player's own\n\t * combinations, so entries belonging to the other player stay zero from\n\t * allocation and never need clearing.\n\t */\n\treadonly reachFor: readonly [Float64Array[], Float64Array[]];\n\treadonly strategy: Float64Array[];\n\treadonly actionValues: Float64Array[];\n\treadonly live: Uint16Array[];\n\t/** Reach and live hands relabelled onto a stored board, for `expandOrbits`. */\n\treadonly mappedMe: Float64Array[];\n\treadonly mappedOpp: Float64Array[];\n\treadonly mappedLive: Uint16Array[];\n\t/** This thread's SIMD kernels, whose memory holds `strategy`; null for JavaScript. */\n\treadonly kernels: Kernels | null;\n\t/** 52 doubles for the terminal kernels' per-card sums, kept zero between uses. */\n\treadonly cardSums: Float64Array;\n}\n\nfunction makeBuffers(tree: Tree, maxActions: number, simd: boolean): Buffers {\n\tconst depth = treeDepth(tree) + 2;\n\tconst make = <T>(factory: () => T): T[] => Array.from({ length: depth }, factory);\n\tconst kernels = simd ? loadKernels(depth, maxActions * COMBOS) : null;\n\treturn {\n\t\tkernels,\n\t\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 */\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\nexport const Mode = { Train: 0, BestResponse: 1, Average: 2 } as const;\nexport type Mode = (typeof Mode)[keyof typeof Mode];\n\n/**\n * Normalise accumulated values into a strategy: each action's share of the\n * positive values, uniform where there are none. One hand at a time, so its\n * few actions stay in registers rather than round-tripping through a sum array.\n *\n * 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: RegretStore | 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/** Current strategy from positive regrets; uniform where there is none. */\nfunction regretMatch(regret: RegretStore, 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 never reached this node on its own, so the\n * average says nothing about it. Its regrets are still updated — weighted by\n * the opponent's reach — so it plays the current strategy: whatever goes on to\n * continue it from here (a best response, another player's rules, a user\n * browsing the line) then sees sensible play rather than every action at an\n * equal share. Uniform only where the regrets are all non-positive too, or\n * where there are none (an `analysisOnly` run).\n *\n * @param regret the regrets beside `strategySum`, or omitted for none\n */\nexport function averageStrategy(\n\tstrategySum: SumStore,\n\tbase: number,\n\tactions: number,\n\tcount: number,\n\tstrategy: Float64Array,\n\tregret?: RegretStore,\n): void {\n\tconst fallback = regret !== undefined && regret.length > 0 ? regret : null;\n\tconst uniform = 1 / actions;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst 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 */\nfunction traverse(\n\tctx: Context,\n\tbuffers: Buffers,\n\tmode: Mode,\n\ttraverser: 0 | 1,\n\titerWeight: number,\n\tnode: number,\n\tboard: number,\n\treachMe: Float64Array,\n\treachOpp: Float64Array,\n\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\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\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 first = runouts.childStart[nextRound][board];\n\t\tconst last = runouts.childStart[nextRound][board + 1];\n\t\tconst from = sharded && ctx.shardStart > first ? ctx.shardStart : first;\n\t\tconst to = sharded && ctx.shardEnd < last ? ctx.shardEnd : last;\n\n\t\tfor (let childBoard = from; childBoard < to; childBoard++) {\n\t\t\tconst 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 | 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 (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\tfor (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k];\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 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\tif (mode === Mode.Train && buffers.kernels !== null) {\n\t\tconst kernels = buffers.kernels;\n\t\tkernels.input.set(ctx.regret.subarray(slotBase, slotBase + length));\n\t\tkernels.regretMatch(strategy, actions, stride);\n\t} else if (mode === Mode.Train) {\n\t\tregretMatch(ctx.regret, slotBase, actions, stride, strategy);\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 && ctx.regretScale !== null) {\n\t\tupdateQuantised(\n\t\t\tctx, 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 } = dcfrFactors(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 + reachMe[i] * 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\tif (isTraverser && mode === Mode.Train && ctx.applyUpdates) {\n\t\tconst tieFrom = lists.tieStart[listSlot];\n\t\tconst tieTo = lists.tieStart[listSlot + 1];\n\t\tif (tieFrom < tieTo) {\n\t\t\tconst integer = ctx.regretScale !== null;\n\t\t\ttieMirrors(ctx.regret, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);\n\t\t\ttieMirrors(ctx.strategySum, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * The regret and strategy-sum update for 16-bit storage, under either rule.\n *\n * A block is rescaled whole on every update: decode, update in float, find the\n * block's largest magnitude, re-encode against it.\n *\n * Regrets round to nearest. Strategy sums round up or down at random, with\n * odds set by the remainder, so each is right on average: rounded to nearest,\n * a hand whose sum is small beside its block's largest loses most of every\n * iteration's contribution, and measured, exploitability stalls near 0.04%\n * of pot where float32 keeps falling. The randomness is a hash of the slot and\n * the iteration, so a solve stays deterministic at any thread count.\n *\n * `actionValues` and `strategy` are not needed once their values are used, so\n * the new regrets and sums are staged in them rather than in buffers of their\n * own.\n */\nfunction updateQuantised(\n\tctx: Context,\n\tblock: number,\n\tslotBase: number,\n\tactions: number,\n\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 } = dcfrFactors(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\tconst sum = strategySum[at] * oldSum * keepSum + weight * reachMe[i] * strategy[a * count + i];\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\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);\n\t\t\tstrategySum[at] = s < SUM_STEPS ? s : SUM_STEPS;\n\t\t}\n\t}\n\tregretScale[block] = largestRegret / REGRET_STEPS;\n\tsumScale[block] = largestSum / SUM_STEPS;\n}\n\n/** A deterministic uniform value in [0, 1) for a slot on an iteration. */\nfunction dither(slot: number, iteration: number): number {\n\tlet h = Math.imul(slot ^ Math.imul(iteration, 0x9e3779b1), 0x85ebca6b);\n\th ^= h >>> 13;\n\th = Math.imul(h, 0xc2b2ae35);\n\th ^= h >>> 16;\n\treturn (h >>> 0) / 4294967296;\n}\n\n/** A whole-tree traversal, returning the root value vector. */\nexport type RootTraversal = (mode: Mode, traverser: 0 | 1, iterWeight: number) => Float64Array;\n\n/** A prepared solver. */\nexport interface Solver {\n\treadonly ctx: Context;\n\t/**\n\t * One traversal for `traverser` on this thread alone, returning the root\n\t * value vector.\n\t */\n\ttraverseRoot(mode: Mode, traverser: 0 | 1, iterWeight: number): Float64Array;\n\t/**\n\t * Route the whole-tree traversals behind `iterate`, `expectedValue` and\n\t * `exploitability` elsewhere — a worker pool — or back to `traverseRoot`\n\t * with null.\n\t */\n\tuseRoot(root: RootTraversal | null): void;\n\t/** One chance node's subtree, honouring the context shard. */\n\ttraverseChance(\n\t\tmode: Mode,\n\t\ttraverser: 0 | 1,\n\t\titerWeight: number,\n\t\tnode: number,\n\t\treachMe: Float64Array,\n\t\treachOpp: Float64Array,\n\t): Float64Array;\n\t/** Combinations live on the given board, shared by root and workers. */\n\treadonly rootLive: Uint16Array;\n\treadonly rootCount: number;\n\titerate(count: number, from: number): void;\n\texpectedValue(): [number, number];\n\texploitability(): number;\n\taverageStrategyAt(node: number, board: number): { actions: number; probs: Float64Array };\n\t/**\n\t * Counterfactual values under the average strategy from any node, for\n\t * reach vectors the caller supplies. Returns a fresh copy.\n\t */\n\tvaluesAt(\n\t\tnode: number,\n\t\tboard: number,\n\t\ttraverser: 0 | 1,\n\t\treachMe: Float64Array,\n\t\treachOpp: Float64Array,\n\t\tlive: Uint16Array,\n\t\tliveCount: number,\n\t): Float64Array;\n\t/**\n\t * Counterfactual values under the average strategy from any node against\n\t * each of `hands` alone, at the reach given for it: the same as `valuesAt`\n\t * with a one-hot opponent reach, for many opposing hands in one walk.\n\t * Returns `hands.length * COMBOS` values, one row per opposing hand.\n\t */\n\tpairValuesAt(\n\t\tnode: number,\n\t\tboard: number,\n\t\ttraverser: 0 | 1,\n\t\thands: Uint16Array,\n\t\thandReach: Float64Array,\n\t\tlive: Uint16Array,\n\t\tliveCount: number,\n\t): Float64Array;\n}\n\n/** Create a solver over prepared structures. */\nexport function makeSolver(ctx: Context): Solver {\n\tconst buffers = makeBuffers(ctx.tree, ctx.layout.maxActions, ctx.simd);\n\tconst reach0 = new Float64Array(COMBOS);\n\tconst reach1 = new Float64Array(COMBOS);\n\tconst rootLive = new Uint16Array(COMBOS);\n\n\t// Only hands one of the players can actually hold, minus whatever the given\n\t// board blocks. Carrying the other thousand-odd combinations through every\n\t// traversal would cost far more than the solve itself.\n\tlet rootCount = 0;\n\t{\n\t\tconst onBoard = new Uint8Array(DECK);\n\t\tfor (const card of ctx.runouts.initial) onBoard[card] = 1;\n\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\tif (ctx.players[0].slot[combo] < 0 && ctx.players[1].slot[combo] < 0) continue;\n\t\t\tif (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;\n\t\t\trootLive[rootCount++] = combo;\n\t\t}\n\t}\n\n\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]] * 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\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\texploitability() {\n\t\t\tconst br0 = total(root(Mode.BestResponse, 0, 0), 0);\n\t\t\tconst br1 = total(root(Mode.BestResponse, 1, 0), 1);\n\t\t\treturn (br0 + br1) / 2;\n\t\t},\n\t\tvaluesAt(node, board, traverser, reachMe, reachOpp, live, liveCount) {\n\t\t\t// The caller's reach need not be symmetric, so mirrored deals are\n\t\t\t// walked rather than assumed.\n\t\t\tconst expanded = ctx.expandOrbits;\n\t\t\tctx.expandOrbits = true;\n\t\t\ttry {\n\t\t\t\tconst round = ctx.tree.round[node];\n\t\t\t\tconst opponent = (1 - traverser) as 0 | 1;\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++) result[lists.list[from + i]] = value[i];\n\t\t\t\tvoid live;\n\t\t\t\tvoid liveCount;\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\taverageStrategy(ctx.strategySum, base, actions, count, strategy, ctx.regret);\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\tconst at = lists.slot[from + i];\n\t\t\t\tfor (let a = 0; a < actions; a++) probs[at * actions + a] = strategy[a * count + i];\n\t\t\t}\n\t\t\treturn { actions, probs };\n\t\t},\n\t};\n}\n\nexport { buildActiveLists, makeTerminalScratch };\n","/**\n * Card relabellings, and the symmetries of a spot.\n *\n * Purpose: the one place a runout is identified with another.\n *\n * A map relabels cards — and with them every combination — so that a subgame\n * after one card can stand for the subgame after another. For a suit\n * permutation that fixes the board and both ranges this is exact: the two\n * subgames are mirror images, so solving one solves both. Later abstractions\n * (rank relabellings) reuse the same table and accept an approximation.\n *\n * Map 0 is always the identity.\n */\n\nimport { COMBO_CARDS, COMBOS, comboIndex, DECK } from './cards.ts';\n\n/** Every relabelling in use, each as a card map and the combination map it induces. */\nexport class CardMaps {\n\t/** `card[m][x]`: what map `m` sends card `x` to. */\n\treadonly card: Uint8Array[] = [];\n\t/** `combo[m][h]`: what map `m` sends combination `h` to. */\n\treadonly combo: Uint16Array[] = [];\n\tprivate readonly known = new Map<string, number>();\n\n\tconstructor() {\n\t\tconst identity = new Uint8Array(DECK);\n\t\tfor (let card = 0; card < DECK; card++) identity[card] = card;\n\t\tthis.add(identity);\n\t}\n\n\t/** Register a card map, returning its id; the same map always gets the same id. */\n\tadd(cardMap: Uint8Array): number {\n\t\tconst key = cardMap.join(',');\n\t\tconst existing = this.known.get(key);\n\t\tif (existing !== undefined) return existing;\n\t\tconst combo = new Uint16Array(COMBOS);\n\t\tfor (let h = 0; h < COMBOS; h++) {\n\t\t\tcombo[h] = comboIndex(cardMap[COMBO_CARDS[h * 2]], cardMap[COMBO_CARDS[h * 2 + 1]]);\n\t\t}\n\t\tconst id = this.card.length;\n\t\tthis.card.push(Uint8Array.from(cardMap));\n\t\tthis.combo.push(combo);\n\t\tthis.known.set(key, id);\n\t\treturn id;\n\t}\n\n\t/** The map that applies `first`, then `second`. */\n\tthen(first: number, second: number): number {\n\t\tconst a = this.card[first];\n\t\tconst b = this.card[second];\n\t\tconst out = new Uint8Array(DECK);\n\t\tfor (let card = 0; card < DECK; card++) out[card] = b[a[card]];\n\t\treturn this.add(out);\n\t}\n\n\t/** The inverse of a map, which must be a bijection. */\n\tinverse(id: number): number {\n\t\tconst a = this.card[id];\n\t\tconst out = new Uint8Array(DECK);\n\t\tfor (let card = 0; card < DECK; card++) out[a[card]] = card;\n\t\treturn this.add(out);\n\t}\n}\n\n/** All 24 orderings of the four suits, identity first. */\nfunction suitPermutations(): number[][] {\n\tconst out: number[][] = [];\n\tconst walk = (prefix: number[]): void => {\n\t\tif (prefix.length === 4) {\n\t\t\tout.push(prefix);\n\t\t\treturn;\n\t\t}\n\t\tfor (let s = 0; s < 4; s++) if (!prefix.includes(s)) walk([...prefix, s]);\n\t};\n\twalk([]);\n\treturn out;\n}\n\n/** The card map of a suit permutation; cards are `rank * 4 + suit`. */\nfunction suitMap(perm: readonly number[]): Uint8Array {\n\tconst out = new Uint8Array(DECK);\n\tfor (let card = 0; card < DECK; card++) out[card] = (card & ~3) | perm[card & 3];\n\treturn out;\n}\n\n/**\n * The suit permutations that leave a spot unchanged: they fix the board as a\n * set and map each range onto itself, weight for weight.\n *\n * Returned as card maps, identity first. Ranges are compared exactly, so a\n * range that differs between suits anywhere — an exact combination such as\n * `AsKh`, or a fractional weight on one suit — breaks that symmetry, and the\n * spot is solved as it would be without any.\n *\n * @param board the board as given\n * @param ranges each player's weights, board cards already removed\n */\nexport function suitSymmetries(board: readonly number[], ranges: readonly Float64Array[]): Uint8Array[] {\n\tconst onBoard = new Uint8Array(DECK);\n\tfor (const card of board) onBoard[card] = 1;\n\tconst out: Uint8Array[] = [];\n\tfor (const perm of suitPermutations()) {\n\t\tconst map = suitMap(perm);\n\t\tlet ok = true;\n\t\tfor (const card of board) if (!onBoard[map[card]]) ok = false;\n\t\tfor (let h = 0; ok && h < COMBOS; h++) {\n\t\t\tconst image = comboIndex(map[COMBO_CARDS[h * 2]], map[COMBO_CARDS[h * 2 + 1]]);\n\t\t\tfor (const weights of ranges) {\n\t\t\t\tif (weights[h] !== weights[image]) {\n\t\t\t\t\tok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (ok) out.push(map);\n\t}\n\treturn out;\n}\n","/**\n * Board completions.\n *\n * Purpose: the one place the cards still to come are enumerated and indexed.\n *\n * The board is given, so unlike a from-scratch solver there is nothing to deal\n * before the first betting round. What remains is the turn, the river, or\n * neither. Completions are ORDERED — the turn is known when turn betting\n * happens, so `Kh` then `2c` is a different line from `2c` then `Kh`, even\n * though the final board is the same.\n *\n * Boards at a round are stored densely and grouped by parent, so the children\n * of one board are a contiguous range and a worker can own a contiguous slice.\n *\n * Suit symmetry folds mirror-image deals together: on a two-tone flop a club\n * turn is a diamond turn with the suits swapped, so only one is stored, and it\n * stands for both. `orbitStart` and friends record which real deals each\n * stored board stands for and how to relabel hands onto it.\n */\n\nimport { CardMaps } from './abstraction.ts';\nimport { DECK, formatCards } from './cards.ts';\n\n/** Boards visible at each betting round. */\nexport interface Runouts {\n\t/** Betting rounds: 3 from a flop, 2 from a turn, 1 from a river. */\n\treadonly rounds: number;\n\t/** Cards on the board at each round: 3, 4, 5. */\n\treadonly width: readonly number[];\n\t/** Distinct boards stored at each round; always 1 at round 0. */\n\treadonly counts: readonly number[];\n\t/** Flat board cards per round, `counts[r] * width[r]` entries. */\n\treadonly cards: readonly Uint8Array[];\n\t/**\n\t * Children of each board, as a prefix: the boards at round `r` dealt from\n\t * board `p` of round `r - 1` are `childStart[r][p]` to\n\t * `childStart[r][p + 1]`. Empty at round 0.\n\t */\n\treadonly childStart: readonly Int32Array[];\n\t/** Each board's parent at the round before; -1 at round 0. */\n\treadonly parent: readonly Int32Array[];\n\t/**\n\t * The real deals each stored board stands for, as a prefix into\n\t * `orbitMap`/`orbitCard`: board `b` of round `r` stands for members\n\t * `orbitStart[r][b]` to `orbitStart[r][b + 1]`. Member 0 is the board\n\t * itself under the identity. Another member is a card that could have been\n\t * dealt instead, with the map that sends it — and every combination with\n\t * it — onto this board; the map fixes the parent board. Without symmetry\n\t * every board stands only for itself.\n\t */\n\treadonly orbitStart: readonly Int32Array[];\n\treadonly orbitMap: readonly Int32Array[];\n\treadonly orbitCard: readonly Uint8Array[];\n\t/**\n\t * The symmetries each stored board still has, as a prefix into\n\t * `stabiliserMap`: map ids, identity first. A board with more than the\n\t * identity holds hands that mirror each other on it, whose strategies the\n\t * solver keeps tied together.\n\t */\n\treadonly stabiliserStart: readonly Int32Array[];\n\treadonly stabiliserMap: readonly Int32Array[];\n\t/** The relabellings `orbitMap` refers to. */\n\treadonly maps: CardMaps;\n\t/** Whether any board stands for more than itself. */\n\treadonly symmetric: boolean;\n\t/**\n\t * Whether some board stands for deals that are not its exact mirror\n\t * images — runout buckets — so the stored game approximates the real one.\n\t */\n\treadonly approximate: boolean;\n\t/** The board as given. */\n\treadonly initial: readonly number[];\n}\n\n/**\n * Enumerate every way the given board can complete, one board per orbit.\n *\n * With no symmetry beyond the identity every completion is stored, in\n * ascending order of the dealt card. With a symmetry group, a dealt card is\n * stored only if it is the lowest of the cards the board's own symmetries\n * send it to; the others become members of its orbit. A child's symmetries are\n * its parent's that also fix the card just dealt, so they shrink as cards\n * fall.\n *\n * @param board 3, 4 or 5 distinct cards\n * @param symmetries card maps that fix the board and both ranges, identity\n * first; see `suitSymmetries`. Omitted, none.\n * @throws if the board is not a legal postflop board\n */\nexport function enumerateRunouts(\n\tboard: readonly number[],\n\tsymmetries?: readonly Uint8Array[],\n\tmerge?: RunoutMerge,\n): Runouts {\n\tif (board.length < 3 || board.length > 5) {\n\t\tthrow new Error(`A postflop board has 3, 4 or 5 cards; got ${board.length} (${formatCards(board)})`);\n\t}\n\tif (new Set(board).size !== board.length) {\n\t\tthrow new Error(`Board repeats a card: ${formatCards(board)}`);\n\t}\n\n\tconst maps = new CardMaps();\n\tconst group = (symmetries ?? []).map((map) => maps.add(map));\n\tif (group.length === 0 || group[0] !== 0) group.unshift(0);\n\n\tconst rounds = 5 - board.length + 1;\n\tconst width: number[] = [board.length];\n\tconst counts: number[] = [1];\n\tconst cards: Uint8Array[] = [Uint8Array.from(board)];\n\tconst childStart: Int32Array[] = [new Int32Array(0)];\n\tconst parent: Int32Array[] = [Int32Array.of(-1)];\n\tconst orbitStart: Int32Array[] = [Int32Array.of(0, 1)];\n\tconst orbitMap: Int32Array[] = [Int32Array.of(0)];\n\tconst orbitCard: Uint8Array[] = [new Uint8Array(1)];\n\tlet stabilisers: number[][] = [group];\n\tlet symmetric = false;\n\tlet approximate = false;\n\tconst stabiliserStart: Int32Array[] = [];\n\tconst stabiliserMap: Int32Array[] = [];\n\tconst recordStabilisers = (list: number[][]): void => {\n\t\tconst starts = new Int32Array(list.length + 1);\n\t\tconst flat: number[] = [];\n\t\tfor (let b = 0; b < list.length; b++) {\n\t\t\tstarts[b] = flat.length;\n\t\t\tflat.push(...list[b]);\n\t\t}\n\t\tstarts[list.length] = flat.length;\n\t\tstabiliserStart.push(starts);\n\t\tstabiliserMap.push(Int32Array.from(flat));\n\t};\n\trecordStabilisers(stabilisers);\n\n\tconst used = new Uint8Array(DECK);\n\tconst seen = new Uint8Array(DECK);\n\tfor (let round = 1; round < rounds; round++) {\n\t\tconst previousWidth = width[round - 1];\n\t\tconst previousCount = counts[round - 1];\n\t\tconst previousCards = cards[round - 1];\n\t\tconst thisWidth = previousWidth + 1;\n\n\t\tconst level: number[] = [];\n\t\tconst parents: number[] = [];\n\t\tconst starts = new Int32Array(previousCount + 1);\n\t\tconst memberStart: number[] = [0];\n\t\tconst memberMap: number[] = [];\n\t\tconst memberCard: number[] = [];\n\t\tconst nextStabilisers: number[][] = [];\n\n\t\tfor (let p = 0; p < previousCount; p++) {\n\t\t\tstarts[p] = parents.length;\n\t\t\tused.fill(0);\n\t\t\tseen.fill(0);\n\t\t\tconst base = p * previousWidth;\n\t\t\tfor (let i = 0; i < previousWidth; i++) used[previousCards[base + i]] = 1;\n\t\t\tconst stabiliser = stabilisers[p];\n\n\t\t\t// One stored child per orbit of the board's symmetries.\n\t\t\tconst children: { card: number; maps: number[]; cards: number[]; fixing: number[]; merged: boolean }[] = [];\n\t\t\tfor (let card = 0; card < DECK; card++) {\n\t\t\t\tif (used[card] || seen[card]) continue;\n\t\t\t\t// Ascending, so the first unseen card of an orbit is its lowest.\n\t\t\t\tconst child = { card, maps: [] as number[], cards: [] as number[], fixing: [] as number[], merged: false };\n\t\t\t\tfor (const sigma of stabiliser) {\n\t\t\t\t\tconst image = maps.card[sigma][card];\n\t\t\t\t\tif (image === card) child.fixing.push(sigma);\n\t\t\t\t\tif (seen[image]) continue;\n\t\t\t\t\tseen[image] = 1;\n\t\t\t\t\t// `sigma` sends `card` to `image`, so its inverse sends the\n\t\t\t\t\t// deal of `image` back onto this board.\n\t\t\t\t\tchild.maps.push(image === card ? 0 : maps.inverse(sigma));\n\t\t\t\t\tchild.cards.push(image);\n\t\t\t\t}\n\t\t\t\tchildren.push(child);\n\t\t\t}\n\n\t\t\t// Runout buckets: a child that plays like an earlier one is folded\n\t\t\t// into it, relabelled by swapping the two cards' ranks.\n\t\t\tif (merge) {\n\t\t\t\tconst boardRanks = new Set<number>();\n\t\t\t\tfor (let i = 0; i < previousWidth; i++) boardRanks.add(previousCards[base + i] >> 2);\n\t\t\t\tfor (let j = 0; j < children.length; j++) {\n\t\t\t\t\tconst later = children[j];\n\t\t\t\t\tconst rankJ = later.card >> 2;\n\t\t\t\t\tif (boardRanks.has(rankJ)) continue;\n\t\t\t\t\tfor (let i = 0; i < j; i++) {\n\t\t\t\t\t\tconst earlier = children[i];\n\t\t\t\t\t\tif (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;\n\t\t\t\t\t\tconst rankI = earlier.card >> 2;\n\t\t\t\t\t\tif (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;\n\t\t\t\t\t\tif (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;\n\t\t\t\t\t\tconst swap = maps.add(rankSwap(rankI, rankJ));\n\t\t\t\t\t\tfor (let m = 0; m < later.maps.length; m++) {\n\t\t\t\t\t\t\tearlier.maps.push(maps.then(later.maps[m], swap));\n\t\t\t\t\t\t\tearlier.cards.push(later.cards[m]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlater.merged = true;\n\t\t\t\t\t\tapproximate = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const child of children) {\n\t\t\t\tif (child.merged) continue;\n\t\t\t\tfor (let i = 0; i < previousWidth; i++) level.push(previousCards[base + i]);\n\t\t\t\tlevel.push(child.card);\n\t\t\t\tparents.push(p);\n\t\t\t\tmemberMap.push(...child.maps);\n\t\t\t\tmemberCard.push(...child.cards);\n\t\t\t\tmemberStart.push(memberMap.length);\n\t\t\t\tnextStabilisers.push(child.fixing);\n\t\t\t\tif (child.maps.length > 1) symmetric = true;\n\t\t\t}\n\t\t}\n\t\tstarts[previousCount] = parents.length;\n\n\t\twidth.push(thisWidth);\n\t\tcounts.push(parents.length);\n\t\tcards.push(Uint8Array.from(level));\n\t\tchildStart.push(starts);\n\t\tparent.push(Int32Array.from(parents));\n\t\torbitStart.push(Int32Array.from(memberStart));\n\t\torbitMap.push(Int32Array.from(memberMap));\n\t\torbitCard.push(Uint8Array.from(memberCard));\n\t\tstabilisers = nextStabilisers;\n\t\trecordStabilisers(stabilisers);\n\t}\n\n\treturn {\n\t\trounds, width, counts, cards, childStart, parent, orbitStart, orbitMap, orbitCard,\n\t\tstabiliserStart, stabiliserMap, maps, symmetric, approximate,\n\t\tinitial: [...board],\n\t};\n}\n\n/** Which runouts may be bucketed together; see `enumerateRunouts`. */\nexport interface RunoutMerge {\n\t/**\n\t * Whether swapping these two ranks leaves the game close enough to itself:\n\t * at the least, every hand in either range still maps to a hand in it.\n\t */\n\tranks(a: number, b: number): boolean;\n\t/** Largest distance between two ranks in one bucket, counted from the stored card. */\n\treadonly maxGap: number;\n}\n\n/** The card map swapping two ranks in every suit. */\nexport function rankSwap(a: number, b: number): Uint8Array {\n\tconst out = new Uint8Array(DECK);\n\tfor (let card = 0; card < DECK; card++) {\n\t\tconst rank = card >> 2;\n\t\tout[card] = ((rank === a ? b : rank === b ? a : rank) << 2) | (card & 3);\n\t}\n\treturn out;\n}\n\n/**\n * How far a rank goes toward a straight with the board: the most board ranks\n * sharing one five-rank window with it, the ace counting low as well.\n */\nexport function connectivity(boardRanks: ReadonlySet<number>, rank: number): number {\n\tlet best = 0;\n\t// Windows by their lowest rank; -1 is the wheel, A-2-3-4-5.\n\tfor (let low = -1; low <= 8; low++) {\n\t\tif (rank < low || rank > low + 4) {\n\t\t\tif (!(low === -1 && rank === 12)) continue;\n\t\t}\n\t\tlet count = 0;\n\t\tfor (let r = low; r <= low + 4; r++) {\n\t\t\tconst actual = r === -1 ? 12 : r;\n\t\t\tif (actual !== rank && boardRanks.has(actual)) count++;\n\t\t}\n\t\tif (count > best) best = count;\n\t}\n\treturn best;\n}\n\n/**\n * Map a board index back to its ancestor at an earlier round.\n *\n * @param runouts the enumeration\n * @param board board index at `round`\n * @param round that board's round\n * @param target the earlier round wanted\n */\nexport function boardAtRound(runouts: Runouts, board: number, round: number, target: number): number {\n\tlet index = board;\n\tfor (let r = round; r > target; r--) index = runouts.parent[r][index];\n\treturn index;\n}\n\n/** A real board, as the solver stores it. */\nexport interface ResolvedBoard {\n\treadonly round: number;\n\t/** The stored board standing for it. */\n\treadonly board: number;\n\t/**\n\t * Real combination to stored combination: a hand `h` on the real board\n\t * plays as `combos[h]` on the stored one. The identity without symmetry.\n\t */\n\treadonly combos: Uint16Array;\n}\n\n/**\n * Find the stored board that stands for a real one.\n *\n * @param runouts the enumeration\n * @param board every card, the given board first and then the cards dealt in order\n * @throws if the cards do not extend the given board legally\n */\nexport function resolveBoard(runouts: Runouts, board: readonly number[]): ResolvedBoard {\n\tconst start = runouts.initial.length;\n\tfor (let i = 0; i < start; i++) {\n\t\tif (board[i] !== runouts.initial[i]) {\n\t\t\tthrow new Error(`${formatCards(board)} does not start with the spot's board ${formatCards(runouts.initial)}`);\n\t\t}\n\t}\n\tif (board.length > 5) throw new Error(`A board has at most 5 cards; got ${board.length}`);\n\tlet index = 0;\n\tlet map = 0;\n\tfor (let i = start; i < board.length; i++) {\n\t\tconst round = i - start + 1;\n\t\tconst dealt = runouts.maps.card[map][board[i]];\n\t\tlet found = -1;\n\t\tfor (let child = runouts.childStart[round][index]; child < runouts.childStart[round][index + 1] && found < 0; child++) {\n\t\t\tfor (let m = runouts.orbitStart[round][child]; m < runouts.orbitStart[round][child + 1]; m++) {\n\t\t\t\tif (runouts.orbitCard[round][m] !== dealt) continue;\n\t\t\t\tfound = child;\n\t\t\t\tmap = runouts.maps.then(map, runouts.orbitMap[round][m]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (found < 0) throw new Error(`${formatCards(board)} deals a card already on the board`);\n\t\tindex = found;\n\t}\n\treturn { round: board.length - start, board: index, combos: runouts.maps.combo[map] };\n}\n","/**\n * Weighted range parsing.\n *\n * Purpose: the one place range notation becomes solver input.\n *\n * A range is a dense `Float64Array` of 1326 weights, one per two-card\n * combination, in the same colex order the solver indexes by. Weights rather\n * than membership: a solver range is routinely partial (\"call 40% of these\"),\n * and every downstream reach vector is a weight anyway.\n *\n * The notation follows common usage:\n *\n * AA KK-99 22+ pairs, ranges and \"and better\"\n * AKs A2s+ A5s-A2s suited\n * AKo KTo+ offsuit\n * AK both suited and offsuit\n * AsKh one exact combination\n * Ax AXs AXo any second card, optionally constrained\n * random everything\n * AKo:0.5 any of the above at a partial weight\n *\n * `Xo` forms include the pair, because a pair is not suited; `Xs` forms do not.\n */\n\nimport { cardOf, comboIndex, COMBOS, parseCard, SUITS } from './cards.ts';\n\n/** Rank characters, highest first, as written in notation. */\nconst RANK_CHARS = 'AKQJT98765432';\n\n/** Rank index from its character, 12 = ace down to 0 = deuce. */\nfunction rankOfChar(char: string): number {\n\tconst index = RANK_CHARS.indexOf(char.toUpperCase());\n\tif (index < 0) throw new Error(`Invalid rank \"${char}\"`);\n\treturn 12 - index;\n}\n\n/** Every combination of a pocket pair: `C(4,2)` = 6. */\nfunction pairCombos(rank: number, out: number[]): void {\n\tfor (let a = 0; a < SUITS; a++) {\n\t\tfor (let b = a + 1; b < SUITS; b++) out.push(comboIndex(cardOf(rank, a), cardOf(rank, b)));\n\t}\n}\n\n/** Every suited combination of two ranks: 4. */\nfunction suitedCombos(high: number, low: number, out: number[]): void {\n\tfor (let suit = 0; suit < SUITS; suit++) out.push(comboIndex(cardOf(high, suit), cardOf(low, suit)));\n}\n\n/** Every offsuit combination of two ranks: 12. */\nfunction offsuitCombos(high: number, low: number, out: number[]): void {\n\tfor (let a = 0; a < SUITS; a++) {\n\t\tfor (let b = 0; b < SUITS; b++) {\n\t\t\tif (a !== b) out.push(comboIndex(cardOf(high, a), cardOf(low, b)));\n\t\t}\n\t}\n}\n\n/** Inclusive rank span, in either written order. */\nfunction ranksBetween(a: number, b: number): number[] {\n\tconst lo = Math.min(a, b);\n\tconst hi = Math.max(a, b);\n\tconst ranks: number[] = [];\n\tfor (let r = lo; r <= hi; r++) ranks.push(r);\n\treturn ranks;\n}\n\n/** Expand one notation segment, without its weight, to combination indices. */\nfunction expand(segment: string): number[] {\n\tconst out: number[] = [];\n\tconst text = segment.trim();\n\tif (!text) return out;\n\n\tif (/^(random|any|100%)$/i.test(text)) {\n\t\tfor (let combo = 0; combo < COMBOS; combo++) out.push(combo);\n\t\treturn out;\n\t}\n\n\t// An exact combination, e.g. AsKh.\n\tif (/^([AKQJT2-9][shdc]){2}$/i.test(text)) {\n\t\tconst a = parseCard(text.slice(0, 2));\n\t\tconst b = parseCard(text.slice(2, 4));\n\t\tif (a === b) throw new Error(`\"${text}\" uses the same card twice`);\n\t\tout.push(comboIndex(a, b));\n\t\treturn out;\n\t}\n\n\t// Any second card: Ax, AXs, AXo.\n\tconst wildcard = /^([AKQJT2-9])[xX]([so])?$/.exec(text);\n\tif (wildcard) {\n\t\tconst rank = rankOfChar(wildcard[1]);\n\t\tconst kind = wildcard[2]?.toLowerCase();\n\t\tfor (let other = 0; other < 13; other++) {\n\t\t\tif (other === rank) {\n\t\t\t\t// A pair is not suited, so it belongs to the offsuit and\n\t\t\t\t// unqualified forms only.\n\t\t\t\tif (kind !== 's') pairCombos(rank, out);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst high = Math.max(rank, other);\n\t\t\tconst low = Math.min(rank, other);\n\t\t\tif (kind !== 'o') suitedCombos(high, low, out);\n\t\t\tif (kind !== 's') offsuitCombos(high, low, out);\n\t\t}\n\t\treturn out;\n\t}\n\n\tconst emit = (high: number, low: number, kind: string | undefined): void => {\n\t\tif (high === low) {\n\t\t\tpairCombos(high, out);\n\t\t\treturn;\n\t\t}\n\t\tif (kind !== 'o') suitedCombos(high, low, out);\n\t\tif (kind !== 's') offsuitCombos(high, low, out);\n\t};\n\n\t// A span, e.g. KK-99 or A5s-A2s.\n\tconst span = /^([AKQJT2-9])([AKQJT2-9])([so])?-([AKQJT2-9])([AKQJT2-9])([so])?$/.exec(text);\n\tif (span) {\n\t\tconst [, a1, a2, k1, b1, b2, k2] = span;\n\t\tconst kind = k1 ?? k2;\n\t\tif (k1 && k2 && k1 !== k2) throw new Error(`\"${text}\" mixes suited and offsuit`);\n\n\t\tconst from1 = rankOfChar(a1);\n\t\tconst from2 = rankOfChar(a2);\n\t\tconst to1 = rankOfChar(b1);\n\t\tconst to2 = rankOfChar(b2);\n\n\t\tif (from1 === from2 && to1 === to2) {\n\t\t\tfor (const rank of ranksBetween(from1, to1)) pairCombos(rank, out);\n\t\t\treturn out;\n\t\t}\n\t\tif (from1 !== to1) throw new Error(`\"${text}\" must hold its higher rank fixed, e.g. A5s-A2s`);\n\t\tfor (const low of ranksBetween(from2, to2)) {\n\t\t\tif (low === from1) continue;\n\t\t\temit(Math.max(from1, low), Math.min(from1, low), kind);\n\t\t}\n\t\treturn out;\n\t}\n\n\t// \"And better\", e.g. 22+, A2s+, KTo+.\n\tconst plus = /^([AKQJT2-9])([AKQJT2-9])([so])?\\+$/.exec(text);\n\tif (plus) {\n\t\tconst first = rankOfChar(plus[1]);\n\t\tconst second = rankOfChar(plus[2]);\n\t\tconst kind = plus[3]?.toLowerCase();\n\n\t\tif (first === second) {\n\t\t\t// Pairs climb to aces.\n\t\t\tfor (let rank = first; rank <= 12; rank++) pairCombos(rank, out);\n\t\t\treturn out;\n\t\t}\n\t\t// Non-pairs climb the lower card to just under the higher one.\n\t\tconst high = Math.max(first, second);\n\t\tconst from = Math.min(first, second);\n\t\tfor (let low = from; low < high; low++) emit(high, low, kind);\n\t\treturn out;\n\t}\n\n\t// A single class, e.g. AA, AKs, AKo, AK.\n\tconst single = /^([AKQJT2-9])([AKQJT2-9])([so])?$/.exec(text);\n\tif (single) {\n\t\tconst first = rankOfChar(single[1]);\n\t\tconst second = rankOfChar(single[2]);\n\t\tconst kind = single[3]?.toLowerCase();\n\t\tif (first === second && kind === 's') throw new Error(`\"${text}\" is impossible: a pair cannot be suited`);\n\t\temit(Math.max(first, second), Math.min(first, second), kind);\n\t\treturn out;\n\t}\n\n\tthrow new Error(`Unrecognised range notation: \"${segment.trim()}\"`);\n}\n\n/**\n * Parse range notation into per-combination weights.\n *\n * Repeating a combination keeps the LAST weight given, so a narrowing segment\n * can follow a broad one: `random:0.1, AA:1` is a light range with pure aces.\n *\n * @param notation comma-separated segments, each optionally `:weight`\n * @returns weights indexed by combination, length 1326\n */\nexport function parseRange(notation: string): Float64Array {\n\tconst weights = new Float64Array(COMBOS);\n\tif (!notation || !notation.trim()) return weights;\n\n\tfor (const segment of notation.split(',')) {\n\t\tif (!segment.trim()) continue;\n\t\tconst [body, weightText] = segment.split(':');\n\t\tlet weight = 1;\n\t\tif (weightText !== undefined) {\n\t\t\tweight = Number(weightText.trim().replace('%', '')) / (weightText.includes('%') ? 100 : 1);\n\t\t\tif (!Number.isFinite(weight) || weight < 0 || weight > 1) {\n\t\t\t\tthrow new Error(`Weight in \"${segment.trim()}\" must be between 0 and 1`);\n\t\t\t}\n\t\t}\n\t\tfor (const combo of expand(body)) weights[combo] = weight;\n\t}\n\treturn weights;\n}\n\n/** Combinations carrying any weight. */\nexport function activeCombos(weights: Float64Array): number[] {\n\tconst combos: number[] = [];\n\tfor (let combo = 0; combo < COMBOS; combo++) if (weights[combo] > 0) combos.push(combo);\n\treturn combos;\n}\n\n/** Total weight, i.e. combinations counted with their weight. */\nexport function rangeWeight(weights: Float64Array): number {\n\tlet total = 0;\n\tfor (let combo = 0; combo < COMBOS; combo++) total += weights[combo];\n\treturn total;\n}\n","/**\n * Node platform.\n *\n * Purpose: the one place the solver touches Node-only APIs. A browser build\n * swaps this module for `browser.ts`, which has the same exports; see\n * `scripts/browser-platform.ts`.\n */\n\nimport { availableParallelism } from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport type { WorkerSetup } from '../parallel.ts';\nimport type { EngineWorkerSetup } from '../engine.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'node';\n\n/** Whether `workers > 1` can be honoured here. */\nexport const THREADS_AVAILABLE = true;\n\n/** Default ceiling on solver storage. */\nexport const DEFAULT_MAX_BYTES = 6 * 1024 * 1024 * 1024;\n\n/**\n * The parent's Node flags, minus any a worker started from a file rejects:\n * `--input-type` is for code given as a string (`node -e`), and a worker\n * inheriting it fails to start.\n */\nfunction workerFlags(): string[] {\n\treturn process.execArgv.filter((flag) => !flag.startsWith('--input-type'));\n}\n\n/** A spawned solver thread. */\nexport interface WorkerHandle {\n\tterminate(): void;\n}\n\n/**\n * Suggested worker count for this machine, the calling thread included.\n *\n * One less than the available parallelism, but never under two. Scaling stays\n * monotone right up to the core count — a flop solve measured 3.3x on 4\n * workers, 3.9x on 6 and 4.3x on 8 across 8 cores — so the only reason to hold\n * one back is leaving the machine responsive, and on two cores that would mean\n * not splitting at all.\n */\nexport function defaultWorkerCount(): number {\n\tconst cores = availableParallelism();\n\treturn cores < 2 ? 1 : Math.max(2, cores - 1);\n}\n\n/**\n * Start one solver thread on `worker.ts`.\n *\n * @param setup everything the worker needs to rebuild the solver\n * @param onError called if the thread dies, so the pool can stop waiting on it\n */\nexport function spawnWorker(setup: WorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\t// From source the worker is TypeScript; from a build it sits beside this\n\t// bundle as JavaScript.\n\tconst url = new URL(import.meta.url.endsWith('.ts') ? '../worker.ts' : './worker.js', import.meta.url);\n\tconst thread = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });\n\tthread.on('error', onError);\n\tthread.unref();\n\treturn {\n\t\tterminate() {\n\t\t\tvoid thread.terminate();\n\t\t},\n\t};\n}\n\n/** Start one WebAssembly engine thread on `engine-worker.ts`. */\nexport function spawnEngineWorker(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst url = new URL(import.meta.url.endsWith('.ts') ? '../engine-worker.ts' : './engine-worker.js', import.meta.url);\n\tconst thread = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });\n\tthread.on('error', onError);\n\tthread.unref();\n\treturn {\n\t\tterminate() {\n\t\t\tvoid thread.terminate();\n\t\t},\n\t};\n}\n","/**\n * Worker-thread parallelism.\n *\n * Purpose: the one place solving is split across cores.\n *\n * The split is by RUNOUT, at the first round with more than one board. Storage\n * is indexed runout-outermost, so each worker owns a disjoint slice of the\n * shared regret and strategy arrays and never needs a lock for anything below\n * that round.\n *\n * The round ABOVE the split is the exception: its regret update needs the value\n * summed over every runout, and CFR+ clamps at zero, which is not linear, so\n * partial updates cannot simply be added. That round stays on the main thread,\n * which walks it twice per traversal — once to collect the reach vectors the\n * workers need, once to apply updates from the totals they returned. It carries\n * a single board, so this costs almost nothing.\n *\n * The main thread takes the first shard itself rather than sleeping while the\n * workers run, so `workers` counts every thread doing the work: two means the\n * main thread and one worker.\n *\n * Every traversal goes through here, not just training: an exploitability\n * check is a full best-response pass, and left single-threaded it would cost\n * as many iterations as there are threads.\n *\n * Coordination is through Atomics rather than messages, so the public solve API\n * stays synchronous.\n *\n * Agreement with a single-threaded solve is to floating point, not bit-for-bit:\n * each worker sums its own slice of runouts before the totals are summed across\n * workers, which is a different association of the same addition.\n */\n\nimport { COMBOS } from './cards.ts';\nimport type { Context, RootTraversal, Solver } from './cfr.ts';\nimport { Mode } from './cfr.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { NodeKind } from './tree.ts';\nimport type { WorkerHandle } from './platform/node.ts';\nimport { spawnWorker } from './platform/node.ts';\n\nexport { defaultWorkerCount } from './platform/node.ts';\n\nexport const CONTROL = {\n\tgeneration: 0,\n\tdone: 1,\n\tcommand: 2,\n\ttraverser: 3,\n\titerWeight: 4,\n\tready: 5,\n\tmode: 6,\n\tsize: 8,\n} as const;\n\nexport const COMMAND = { work: 0, exit: 1 } as const;\n\n/** How 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\treadonly control: SharedArrayBuffer;\n\treadonly exchange: SharedArrayBuffer;\n\treadonly entryCount: number;\n}\n\n/** A running pool of solver workers. */\nexport interface Pool {\n\t/** One traversal for one traverser, returning the root value vector. */\n\treadonly traverse: RootTraversal;\n\tclose(): void;\n\t/** Threads doing the work, the main thread included. */\n\treadonly workers: number;\n}\n\n/**\n * Start a worker pool.\n *\n * @param ctx solver context, whose accumulators must be SharedArrayBuffer backed\n * @param solver single-threaded solver, used for the round above the split\n * @param plan how the runouts are split\n * @param payload everything the worker needs to rebuild the context\n * @param workers threads doing the work, the main thread included\n */\nexport function startPool(\n\tctx: Context,\n\tsolver: Solver,\n\tplan: ShardPlan,\n\tpayload: unknown,\n\tworkers: number,\n): Pool {\n\tconst entryCount = plan.entryNodes.length;\n\t// The main thread is one of the `workers`; only the rest are spawned.\n\tconst spawned = workers - 1;\n\tconst reachFloats = entryCount * 2 * COMBOS;\n\tconst partialFloats = spawned * entryCount * COMBOS;\n\tconst exchangeBuffer = new SharedArrayBuffer((reachFloats + partialFloats) * 8);\n\tconst exchange = new Float64Array(exchangeBuffer);\n\tconst controlBuffer = new SharedArrayBuffer(CONTROL.size * 4);\n\tconst control = new Int32Array(controlBuffer);\n\n\tconst threads: WorkerHandle[] = [];\n\tlet failure: Error | null = null;\n\n\tfor (let w = 0; w < spawned; w++) {\n\t\tconst setup: WorkerSetup = {\n\t\t\tworkerId: w,\n\t\t\tpayload,\n\t\t\tplan: { round: plan.round, entryNodes: plan.entryNodes, entryIndexOf: plan.entryIndexOf },\n\t\t\tshardStart: plan.bounds[w + 1],\n\t\t\tshardEnd: plan.bounds[w + 2],\n\t\t\tregret: ctx.regret.buffer as SharedArrayBuffer,\n\t\t\tstrategySum: ctx.strategySum.buffer as SharedArrayBuffer,\n\t\t\tregretScale: (ctx.regretScale?.buffer as SharedArrayBuffer | undefined) ?? null,\n\t\t\tsumScale: (ctx.sumScale?.buffer as SharedArrayBuffer | undefined) ?? null,\n\t\t\tcontrol: controlBuffer,\n\t\t\texchange: exchangeBuffer,\n\t\t\tentryCount,\n\t\t};\n\t\t// A worker that dies would otherwise leave the main thread waiting on a\n\t\t// counter that can never reach its target.\n\t\tconst thread = spawnWorker(setup, (error: Error) => {\n\t\t\tfailure ??= error;\n\t\t\tAtomics.store(control, CONTROL.ready, spawned);\n\t\t\tAtomics.add(control, CONTROL.done, spawned);\n\t\t\tAtomics.notify(control, CONTROL.done);\n\t\t\tAtomics.notify(control, CONTROL.ready);\n\t\t});\n\t\tthreads.push(thread);\n\t}\n\n\t// Barrier: a worker that started after the first dispatch would never see\n\t// the generation change, and the pool would deadlock.\n\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 dispatch = (mode: Mode, traverser: 0 | 1, iterWeight: number): void => {\n\t\tAtomics.store(control, CONTROL.done, 0);\n\t\tAtomics.store(control, CONTROL.mode, mode);\n\t\tAtomics.store(control, CONTROL.traverser, traverser);\n\t\tAtomics.store(control, CONTROL.iterWeight, iterWeight);\n\t\tAtomics.store(control, CONTROL.command, COMMAND.work);\n\t\tAtomics.add(control, CONTROL.generation, 1);\n\t\tAtomics.notify(control, CONTROL.generation);\n\n\t\t// Shard 0 is this thread's, done while the workers do theirs. With no\n\t\t// collect or override set the split-round chance nodes expand as usual,\n\t\t// over whatever slice the context names.\n\t\tconst fullStart = ctx.shardStart;\n\t\tconst fullEnd = ctx.shardEnd;\n\t\tctx.shardStart = plan.bounds[0];\n\t\tctx.shardEnd = plan.bounds[1];\n\t\t// Pass A left updates off; below the split they are this shard's own.\n\t\tctx.applyUpdates = true;\n\t\ttry {\n\t\t\tfor (let entry = 0; entry < entryCount; entry++) {\n\t\t\t\tfor (let i = 0; i < COMBOS; i++) {\n\t\t\t\t\tmainReachMe[i] = exchange[entry * 2 * COMBOS + i];\n\t\t\t\t\tmainReachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];\n\t\t\t\t}\n\t\t\t\tconst value = solver.traverseChance(\n\t\t\t\t\tmode, traverser, iterWeight, plan.entryNodes[entry], mainReachMe, mainReachOpp,\n\t\t\t\t);\n\t\t\t\tchanceValues.set(value.subarray(0, COMBOS), entry * COMBOS);\n\t\t\t}\n\t\t} finally {\n\t\t\tctx.shardStart = fullStart;\n\t\t\tctx.shardEnd = fullEnd;\n\t\t}\n\n\t\tfor (;;) {\n\t\t\tconst done = Atomics.load(control, CONTROL.done);\n\t\t\tif (done >= spawned) break;\n\t\t\tif (failure) throw failure;\n\t\t\tAtomics.wait(control, CONTROL.done, done, 50);\n\t\t}\n\t\tif (failure) throw failure;\n\t};\n\n\treturn {\n\t\tworkers,\n\t\ttraverse(mode, traverser, iterWeight) {\n\t\t\t// Pass A: walk the round above the split to capture what each worker\n\t\t\t// needs, applying nothing.\n\t\t\tctx.applyUpdates = false;\n\t\t\tctx.chanceOverride = null;\n\t\t\tctx.chanceCollect = (node, reachMe, reachOpp) => {\n\t\t\t\tconst entry = plan.entryIndexOf[node];\n\t\t\t\texchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);\n\t\t\t\texchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tsolver.traverseRoot(mode, traverser, iterWeight);\n\t\t\t} finally {\n\t\t\t\tctx.chanceCollect = null;\n\t\t\t}\n\n\t\t\t// Leaves this thread's own partial in `chanceValues`.\n\t\t\tdispatch(mode, traverser, iterWeight);\n\n\t\t\tfor (let w = 0; w < spawned; w++) {\n\t\t\t\tconst base = reachFloats + w * entryCount * COMBOS;\n\t\t\t\tfor (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];\n\t\t\t}\n\n\t\t\t// Pass B: finish that round from the totals, now applying updates.\n\t\t\tctx.chanceOverride = chanceValues;\n\t\t\tctx.applyUpdates = true;\n\t\t\ttry {\n\t\t\t\tconst value = solver.traverseRoot(mode, traverser, iterWeight);\n\t\t\t\ttotal.set(value.subarray(0, COMBOS));\n\t\t\t} finally {\n\t\t\t\tctx.chanceOverride = null;\n\t\t\t}\n\t\t\treturn total;\n\t\t},\n\t\tclose() {\n\t\t\tAtomics.store(control, CONTROL.command, COMMAND.exit);\n\t\t\tAtomics.add(control, CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, CONTROL.generation);\n\t\t\tfor (const thread of threads) thread.terminate();\n\t\t},\n\t};\n}\n","/**\n * Postflop Texas Hold'em solver.\n *\n * Purpose: the public surface. Give it a board, a pot, stacks, two ranges and a\n * betting scheme; it solves to showdown.\n *\n * There is no preflop round. The ranges you supply already encode whatever spot\n * you are in, so the solver starts from a dead pot with both players even.\n */\n\nimport { COMBO_CARDS, COMBOS, comboIndex, formatCards, parseCards } from './cards.ts';\nimport type { BetSize, RaiseSizes, Tree } from './tree.ts';\nimport type { PerPlayer } from './tree.ts';\nimport { ACTION_LABELS, ActionKind, buildTree, forPlayer, isPerPlayer, mapPlayers, NodeKind, raisesPerRound } from './tree.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { ResolvedBoard } from './runouts.ts';\nimport type { RunoutMerge } from './runouts.ts';\nimport { boardAtRound, enumerateRunouts, rankSwap, resolveBoard } from './runouts.ts';\nimport { suitSymmetries } from './abstraction.ts';\nimport { activeCombos, parseRange, rangeWeight } from './range.ts';\nimport { buildShowdownTable } from './showdown.ts';\nimport { buildHandSpace } from './hands.ts';\nimport { createEngine } from './engine.ts';\nimport type { WarmStartReport } from './warm.ts';\nimport { warmStart } from './warm.ts';\nimport type { Pool } from './parallel.ts';\nimport { defaultWorkerCount, planShards, startPool } from './parallel.ts';\nimport { DEFAULT_MAX_BYTES, PLATFORM, spawnEngineWorker, THREADS_AVAILABLE } from './platform/node.ts';\nimport type { Context, PlayerIndex, RegretStore, Solver, SumStore } from './cfr.ts';\nimport {\n\tbuildActiveLists,\n\tbuildLayout,\n\tbuildPlayerIndex,\n\tmakeSolver,\n\tmakeTerminalScratch,\n\tmatchupMass,\n\trunoutWeights,\n} from './cfr.ts';\n\nexport * from './cards.ts';\nexport * from './eval7.ts';\nexport { activeCombos, parseRange, rangeWeight } from './range.ts';\nexport type { ResolvedBoard } from './runouts.ts';\nexport type { WarmStartReport } from './warm.ts';\nexport { simdAvailable } from './kernels.ts';\nexport type { BetSize } from './tree.ts';\nexport type { Solver } from './cfr.ts';\nexport { ACTION_LABELS, ActionKind, NodeKind } from './tree.ts';\nexport type { PerPlayer, RaiseSizes } from './tree.ts';\n/** 'node' or 'browser': which build is running. */\nexport { PLATFORM } from './platform/node.ts';\n\n/** Sub-chip resolution, so pot-fraction sizing is exact. */\nconst DEFAULT_CHIP_SCALE = 100;\n\n/** Measured throughput on a warm run, used only to project solve time. */\nconst OPS_PER_SECOND = 2e8;\n\n/** A spot to solve. */\nexport interface SpotConfig {\n\t/** 3, 4 or 5 cards, e.g. \"AsKh7d\" or \"As Kh 7d 2c\". */\n\treadonly board: string;\n\t/** Dead money already in the middle, in chips. */\n\treadonly pot: number;\n\t/** Effective stack behind, per player, in chips. */\n\treadonly stack: number;\n\t/**\n\t * The out-of-position player's range, who acts first: range notation, or\n\t * a weight per combination indexed like `COMBO_CARDS`, as\n\t * `Solution.subgameAt` produces.\n\t */\n\treadonly oop: string | Float64Array;\n\t/** The in-position player's range, in either form. */\n\treadonly ip: string | Float64Array;\n\t/**\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/** Refuse a range wider than this many combinations. */\n\treadonly maxCombos?: number;\n\t/**\n\t * Drop combinations weighted below this from both ranges. Imported ranges\n\t * are often full of hands at a few percent that barely move the answer\n\t * but cost as much as any other; this removes them. It edits the ranges,\n\t * so it changes the game being solved. Default 0, keep everything.\n\t */\n\treadonly minWeight?: number;\n\t/**\n\t * Refuse a spot needing more than this much storage. Defaults to 6 GiB in\n\t * the Node build and 512 MiB in the browser build, where a tab has far less\n\t * to give.\n\t */\n\treadonly maxBytes?: number;\n\treadonly chipScale?: number;\n\t/**\n\t * Fold mirror-image runouts together. When the board and both ranges are\n\t * unchanged by swapping some suits — two suits absent from a two-tone flop,\n\t * three from a monotone one — a deal in one of those suits is the mirror\n\t * image of a deal in another, so only one is solved and it stands for both.\n\t * Exact, not an approximation: strategies on a mirrored runout are the\n\t * stored ones relabelled. Default true; ranges that differ between suits\n\t * anywhere simply have no symmetry to use.\n\t */\n\treadonly isomorphism?: boolean;\n\t/**\n\t * Solve one turn or river card for several that play alike — an\n\t * approximation. Two cards of one suit are bucketed together when neither\n\t * pairs the board, they connect equally to its straights, and swapping\n\t * their ranks maps each range onto itself (so `98s` in a range keeps an 8\n\t * and a 9 apart). The stored card stands for the others with hands\n\t * relabelled by that swap. How much it saves depends on the ranges: with\n\t * pairs and broadway hands most low cards bucket together; suited\n\t * connectors keep them apart. `trueExploitabilityPercent()` measures the\n\t * strategy in the real game, every card dealt. Default false.\n\t */\n\treadonly runoutBuckets?: boolean | number;\n}\n\n/** Projected cost of solving a spot. */\nexport interface Estimate {\n\treadonly rounds: number;\n\t/**\n\t * Final boards stored. With `isomorphism` a mirrored runout is not\n\t * stored, so this can be well under the number of real runouts.\n\t */\n\treadonly runouts: number;\n\treadonly combos: readonly [number, number];\n\treadonly decisionNodes: number;\n\treadonly totalSlots: number;\n\t/** Storage at 32-bit precision, the default for any sizeable spot. */\n\treadonly bytes: number;\n\t/**\n\t * Storage at 16-bit precision, a little over half of `bytes`; what a spot\n\t * that does not fit at 32 bits is solved with.\n\t */\n\treadonly compressedBytes: number;\n\treadonly secondsPerThousandIterations: number;\n\t/** Whether the spot fits `maxBytes` at 16 bits or better. */\n\treadonly fits: boolean;\n\treadonly suggestions: readonly string[];\n}\n\n/** Thrown when a spot would need more memory than allowed. */\nexport class SpotTooLargeError extends Error {\n\treadonly estimate: Estimate;\n\tconstructor(estimate: Estimate, maxBytes: number) {\n\t\tsuper(\n\t\t\t`This spot needs ~${formatBytes(estimate.compressedBytes)} even at 16-bit precision, ` +\n\t\t\t\t`but the limit is ${formatBytes(maxBytes)}.\\n` +\n\t\t\t\t` ${estimate.decisionNodes} decision nodes x up to ${estimate.runouts.toLocaleString()} runouts ` +\n\t\t\t\t`x ${Math.max(...estimate.combos)} combos.\\n` +\n\t\t\t\t(estimate.suggestions.length\n\t\t\t\t\t? `Try:\\n${estimate.suggestions.map((s) => ` - ${s}`).join('\\n')}\\n`\n\t\t\t\t\t: '') +\n\t\t\t\t'Raise the ceiling with `maxBytes` if you have the memory.',\n\t\t);\n\t\tthis.name = 'SpotTooLargeError';\n\t\tthis.estimate = estimate;\n\t}\n}\n\nfunction formatBytes(bytes: number): string {\n\tconst units = ['B', 'KB', 'MB', 'GB', 'TB'];\n\tlet value = bytes;\n\tlet unit = 0;\n\twhile (value >= 1024 && unit < units.length - 1) {\n\t\tvalue /= 1024;\n\t\tunit++;\n\t}\n\treturn `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;\n}\n\n/** A prepared spot, ready to solve. */\nexport interface Spot {\n\treadonly board: number[];\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly estimate: Estimate;\n\treadonly chipScale: number;\n\treadonly potUnits: number;\n\treadonly stackUnits: number;\n\t/** The configuration this was built from, so a worker can rebuild it. */\n\treadonly source: SpotConfig;\n\t/**\n\t * Find the stored board standing for a real one, and how hands relabel\n\t * onto it. Board indices everywhere else — `strategyAt`, `reachAt`,\n\t * `subgameAt` — index stored boards; with `isomorphism` a mirrored runout\n\t * is not stored, and this is how to read it.\n\t *\n\t * @param board the spot's board followed by the cards dealt, in order\n\t */\n\tresolveBoard(board: string | readonly number[]): ResolvedBoard;\n}\n\n/**\n * Validate a spot and build everything needed to solve it.\n * @throws {SpotTooLargeError} when it would exceed the memory ceiling\n */\nexport function defineSpot(config: SpotConfig): Spot {\n\tconst chipScale = config.chipScale ?? DEFAULT_CHIP_SCALE;\n\tconst maxBytes = config.maxBytes ?? DEFAULT_MAX_BYTES;\n\tconst board = parseCards(config.board);\n\tif (board.length < 3 || board.length > 5) {\n\t\tthrow new Error(`A postflop board has 3, 4 or 5 cards; got ${board.length} (${formatCards(board)})`);\n\t}\n\tconst rounds = 6 - board.length;\n\n\tif (config.pot <= 0) throw new Error('pot must be positive');\n\tif (config.stack <= 0) throw new Error('stack must be positive');\n\n\t// One row per round, for each player.\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\tconst rows = 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\t// Board cards cannot be in anyone's range.\n\tconst onBoard = new Set(board);\n\tconst trim = (range: string | Float64Array, who: string): Float64Array => {\n\t\tconst weights = typeof range === 'string' ? parseRange(range) : Float64Array.from(range);\n\t\tif (weights.length !== COMBOS) {\n\t\t\tthrow new Error(`The ${who} range has ${weights.length} weights; one per combination is ${COMBOS}`);\n\t\t}\n\t\tconst floor = config.minWeight ?? 0;\n\t\tfor (let combo = 0; combo < COMBOS; combo++) {\n\t\t\tif (weights[combo] === 0) continue;\n\t\t\tif (onBoard.has(COMBO_CARDS[combo * 2]) || onBoard.has(COMBO_CARDS[combo * 2 + 1])) {\n\t\t\t\tweights[combo] = 0;\n\t\t\t} else if (weights[combo] < floor) {\n\t\t\t\tweights[combo] = 0;\n\t\t\t}\n\t\t}\n\t\tconst live = activeCombos(weights).length;\n\t\tif (live === 0) throw new Error(`The ${who} range is empty once the board is removed`);\n\t\tif (config.maxCombos !== undefined && live > config.maxCombos) {\n\t\t\tthrow new Error(\n\t\t\t\t`The ${who} range has ${live} combinations, over the ${config.maxCombos} limit. ` +\n\t\t\t\t\t'Narrow the range or raise `maxCombos`.',\n\t\t\t);\n\t\t}\n\t\treturn weights;\n\t};\n\n\tconst players: [PlayerIndex, PlayerIndex] = [\n\t\tbuildPlayerIndex(trim(config.oop, 'out-of-position')),\n\t\tbuildPlayerIndex(trim(config.ip, 'in-position')),\n\t];\n\n\t// Symmetry needs the ranges, so the runouts come after them.\n\tconst symmetries =\n\t\tconfig.isomorphism === false || board.length === 5\n\t\t\t? undefined\n\t\t\t: suitSymmetries(board, [players[0].weights, players[1].weights]);\n\tconst runouts = enumerateRunouts(\n\t\tboard,\n\t\tsymmetries,\n\t\tconfig.runoutBuckets && board.length < 5\n\t\t\t? rangeRankMerge(players, config.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config.runoutBuckets)\n\t\t\t: undefined,\n\t);\n\n\tconst tree = buildTree(\n\t\t{\n\t\t\tpotUnits: Math.round(config.pot * chipScale),\n\t\t\tstackUnits: Math.round(config.stack * chipScale),\n\t\t\tbetSizes: rows,\n\t\t\traiseSizes: config.raiseSizes,\n\t\t\tmaxRaises: config.maxRaises ?? 1,\n\t\t\tallowAllIn: config.allowAllIn ?? false,\n\t\t\tallInThreshold: config.allInThreshold,\n\t\t\tnoDonk: config.noDonk,\n\t\t\tmergeSizes: config.mergeSizes,\n\t\t\tchipScale,\n\t\t\tminRaiseUnits: chipScale,\n\t\t},\n\t\trunouts,\n\t);\n\n\tconst layout = buildLayout(tree, runouts, players, 4);\n\tconst last = runouts.rounds - 1;\n\tconst showdownBytes = runouts.counts[last] * (2 * COMBOS + COMBOS + 1) * 2;\n\tconst bytes = layout.bytes + showdownBytes;\n\tconst compressedBytes = buildLayout(tree, runouts, players, 2).bytes + showdownBytes;\n\n\tconst suggestions: string[] = [];\n\tif (compressedBytes > maxBytes) {\n\t\tconst widest = Math.max(...[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\tsecondsPerThousandIterations: (layout.totalSlots * 4 * 1000) / OPS_PER_SECOND,\n\t\tfits: compressedBytes <= maxBytes,\n\t\tsuggestions,\n\t};\n\tif (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);\n\n\treturn {\n\t\tboard,\n\t\ttree,\n\t\trunouts,\n\t\tplayers,\n\t\testimate,\n\t\tchipScale,\n\t\tpotUnits: Math.round(config.pot * chipScale),\n\t\tstackUnits: Math.round(config.stack * chipScale),\n\t\tsource: config,\n\t\tresolveBoard(cards) {\n\t\t\treturn resolveBoard(runouts, typeof cards === 'string' ? parseCards(cards) : cards);\n\t\t},\n\t};\n}\n\n/** Solver tuning. */\nexport interface SolveOptions {\n\t/**\n\t * Iterations to run. With `targetPercent` set this is only a cap, and the\n\t * solve normally stops well before it; `stoppedAt` on the result says which\n\t * of the two ended it.\n\t */\n\treadonly iterations?: number;\n\t/**\n\t * Stop once exploitability falls to this percentage of the pot — the\n\t * accuracy knob, and the cheapest way to cut solve time.\n\t *\n\t * Solvers conventionally quote accuracy this way, and it is the only form\n\t * comparable between spots of different sizes. As a rough guide, 1% of pot\n\t * is a sketch, 0.5% is enough to read strategies off, 0.1% is publishable\n\t * and costs several times as long.\n\t *\n\t * Checking is not free — see `exploitEvery` — so the solve overshoots the\n\t * target slightly rather than stopping on the exact iteration it was met.\n\t */\n\treadonly targetPercent?: number;\n\t/**\n\t * Measure exploitability every N iterations. Each costs about one iteration,\n\t * because it is a full best-response pass for both players.\n\t *\n\t * Left unset with `targetPercent` given, checks are scheduled by predicting\n\t * when the target will be met rather than at any fixed cadence — see\n\t * `nextCheck`. Setting this forces a fixed cadence instead.\n\t */\n\treadonly exploitEvery?: number;\n\treadonly onProgress?: (info: Progress) => void;\n\t/**\n\t * Accumulator storage. Unset, '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: any count resolves to 1 there.\n\t */\n\treadonly workers?: number | 'auto';\n\t/**\n\t * The update rule. 'dcfr' (the default) is Discounted CFR, which discounts\n\t * old regrets and weights recent iterations more heavily; measured, it\n\t * reaches 0.3% of pot in 35–45% fewer iterations than 'cfr+' on river,\n\t * turn and flop spots alike. 'cfr+' clamps regrets at zero and weights\n\t * iteration `t` by `t` in the average.\n\t *\n\t * Predictive Discounted CFR+ (Xu et al., 2024) was implemented and measured\n\t * against 'dcfr' and is not offered: at the paper's parameters (α 2.3,\n\t * γ 5) it took 165 iterations to 0.3% of pot on the bench turn spot where\n\t * 'dcfr' takes 85, and 120 to 65 on the river; no α, γ tried (1 to 2.3, 2\n\t * to 5) came close, with or without the prediction.\n\t */\n\treadonly algorithm?: Algorithm;\n\t/**\n\t * Allocate only the strategy sums, for loading a saved strategy and\n\t * analysing it. Such a run must never be stepped.\n\t */\n\treadonly analysisOnly?: boolean;\n\t/**\n\t * Start from a previous solve of the same board instead of from nothing.\n\t *\n\t * For re-solving a tweaked spot — another pot or stack, a bet size nudged,\n\t * a range reweighted — whose equilibrium is close to the old one. The\n\t * answer is not approximate: CFR converges from any start, and this one is\n\t * near. Nodes match by the actions leading to them, bet sizes by the\n\t * nearest pot fraction; hands by combination; anything without a match\n\t * starts cold. `SolveRun.warmStart` says how much matched.\n\t *\n\t * Regrets carry over; the average strategy only when the spot is the\n\t * same, which resumes a solve exactly. Measured on a river spot re-solved\n\t * to 0.1% of pot, a nudged bet size took 15 iterations instead of 130 from\n\t * cold, a reweighted range 80 instead of 130, a 20% bigger pot 100\n\t * instead of 125.\n\t */\n\treadonly warmStart?: Solution | SolveRun;\n\t/**\n\t * The iteration to carry on counting from, which sets how heavily DCFR\n\t * discounts the inherited regrets and how CFR+ weights the averages. Unset,\n\t * the old solve's own count: the new solve continues it. Lower it to let\n\t * the new spot's own iterations outweigh the old ones sooner.\n\t */\n\treadonly warmIteration?: number;\n\t/**\n\t * Approximations that keep the game but solve it more cheaply. All off by\n\t * default. Each costs some accuracy, which the exploitability — measured\n\t * exactly, in the full game — shows.\n\t */\n\treadonly approximations?: Approximations;\n\t/**\n\t * Use the WebAssembly SIMD kernels where the platform supports them,\n\t * falling back to JavaScript where it does not. Results are identical\n\t * either way, to the bit; this exists to compare the two. Default true.\n\t */\n\treadonly simd?: boolean;\n\t/**\n\t * Which traversal runs. Unset, the WebAssembly engine wherever it applies\n\t * — one thread, 32-bit storage, WebAssembly SIMD available — and the\n\t * JavaScript one otherwise. 'js' forces JavaScript, to compare the two.\n\t */\n\treadonly engine?: 'js';\n}\n\n/** See `SolveOptions.approximations`. */\nexport interface Approximations {\n\t/*\n\t * Threshold pruning — skipping opponent actions taken with negligible\n\t * reach — was built and measured, and is deliberately not offered: a\n\t * threshold on reach mass also skips deep lines that are rare overall but\n\t * matter to the few hands that reach them, their strategy stops training,\n\t * and the best response walks straight into it. On a wide turn spot it\n\t * plateaued near 0.8% of pot where the unpruned solve reached 0.17%, for\n\t * at most 15% less time per iteration.\n\t *\n\t * River hand buckets — one strategy per set of hands of equal strength\n\t * and equal ranks, suits told apart only where a flush is possible — were\n\t * built and measured too, and also left out. The solver updates every hand\n\t * in one vector pass, so fewer separate strategies did not mean fewer\n\t * iterations, while the lost blocker detail put a floor under accuracy:\n\t * 105 iterations to 0.3% of pot on a turn spot instead of 85, and a\n\t * plateau near 0.15% where the exact solve went on to 0.1%.\n\t *\n\t * Chance sampling — walking each river deal in training with probability\n\t * p and weighting it by 1/p, with DCFR discounts caught up for deals left\n\t * out — was built and measured as well. Iterations got cheaper, but the\n\t * sampling noise, which DCFR's weighting of recent iterations amplifies,\n\t * cost more iterations than it saved: a flop spot on 4 threads reached\n\t * 0.3% of pot in 14.1 s exact, 23.1 s at p = 0.5, and not within 400\n\t * iterations at p = 0.25; at best it broke even to 1%.\n\t */\n}\n\nexport type Algorithm = 'cfr+' | 'dcfr';\n\nexport type Precision = 'f64' | 'f32' | 'i16';\n\n/** Bytes per stored value at each precision. */\nexport const PRECISION_BYTES = { f64: 8, f32: 4, i16: 2 } as const;\n\nexport interface Progress {\n\treadonly iteration: number;\n\treadonly exploitability: number;\n\treadonly elapsedMs: number;\n}\n\n/** A solved spot. */\nexport interface Solution {\n\treadonly spot: Spot;\n\t/** Iterations this solve ran. */\n\treadonly iterations: number;\n\t/** Iterations behind the strategy, counting any a warm start inherited. */\n\treadonly totalIterations: number;\n\t/**\n\t * Which stopping rule ended the solve. 'iterations' with a `targetPercent`\n\t * set means the target was NOT reached and the answer is looser than asked\n\t * for — worth surfacing rather than swallowing.\n\t */\n\treadonly stoppedAt: 'target' | 'iterations';\n\t/** Worker threads the solve actually used, which 'auto' does not tell you. */\n\treadonly workers: number;\n\t/** The solver behind this solution, for analysis and warm starts. */\n\treadonly solver: Solver;\n\t/** Chips per hand for a player, under the average strategy. */\n\tev(player: 0 | 1): number;\n\t/** Distance from equilibrium, in chips per hand. */\n\texploitability(): number;\n\t/**\n\t * Distance from equilibrium as a percentage of the pot, which is how\n\t * solvers conventionally report it and the only form comparable between\n\t * spots of different sizes.\n\t */\n\texploitabilityPercent(): number;\n\t/** Action probabilities for every combination this player holds. */\n\tstrategyAt(node: number, board: number): StrategyView;\n\t/** Readable action path to a node. */\n\tpath(node: number): string;\n\t/**\n\t * How likely each combination is to reach a node on a board, for one\n\t * player: their range weight times the probability of every action they\n\t * took on the way, under the average strategy. Indexed by combination.\n\t * The other player's actions do not enter: this is the player's own range\n\t * at the node, not the joint probability of getting there.\n\t */\n\treachAt(node: number, board: number, player: 0 | 1): Float64Array;\n\t/**\n\t * The spot that starts at a node: the board as dealt there, the pot and\n\t * stacks as they stand, and each player's range as `reachAt` gives it.\n\t * Defining and solving it re-solves that part of the game, typically with\n\t * more bet sizes than the whole spot could afford.\n\t *\n\t * This is unsafe re-solving: the subgame is solved for the ranges that\n\t * arrive, so its strategy can be exploited in ways the original solution\n\t * did not allow for. It answers \"how should these ranges play from here\"\n\t * well; it does not make the earlier streets any more accurate.\n\t *\n\t * @param node a decision that opens a betting round after the first, or the root\n\t * @param board the board index at that node's round\n\t * @param betting overrides; unset, the original spot's betting carries over\n\t */\n\tsubgameAt(node: number, board: number, betting?: SubgameBetting): SpotConfig;\n\treadonly history: readonly Progress[];\n}\n\n/** Betting for a subgame; anything unset keeps the original spot's. */\nexport type SubgameBetting = Partial<\n\tPick<\n\t\tSpotConfig,\n\t\t'betSizes' | 'raiseSizes' | 'maxRaises' | 'allowAllIn' | 'allInThreshold' | 'noDonk' | 'mergeSizes' | 'maxCombos' | 'maxBytes'\n\t>\n>;\n\nexport interface StrategyView {\n\treadonly node: number;\n\treadonly board: number;\n\treadonly player: 0 | 1;\n\treadonly actions: readonly string[];\n\treadonly combos: Uint16Array;\n\t/** Row-major `combos.length * actions.length`. */\n\treadonly probs: Float64Array;\n}\n\n/** An in-progress solve the caller drives. */\nexport interface SolveRun {\n\treadonly spot: Spot;\n\t/** Iterations completed so far, by this run; a warm start's are not counted. */\n\treadonly completed: number;\n\t/** Iterations behind the strategy, counting any a warm start inherited. */\n\treadonly totalIterations: number;\n\t/** 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?: 'target' | 'iterations'): Solution;\n\t/** Release worker threads. Snapshots taken before this stay usable. */\n\tclose(): void;\n\t/** Worker threads actually in use; 1 when single-threaded. */\n\treadonly workers: number;\n\t/** The underlying solver, for per-node analysis once solving is done. */\n\treadonly solver: Solver;\n}\n\n/**\n * Prepare a solve without running it.\n *\n * Stepping costs nothing over one long call — the work per iteration is\n * identical — and it is what lets a caller report progress or stop early while\n * keeping the partial answer.\n *\n * @param spot from {@link defineSpot}\n * @param options solver setup\n */\nexport function createRun(spot: Spot, options: SolveOptions = {}): SolveRun {\n\t// A saved strategy is loaded as float32 sums, so analysis stays there.\n\tconst maxBytes = spot.source.maxBytes ?? DEFAULT_MAX_BYTES;\n\tconst { totalSlots, bytes } = spot.estimate;\n\tconst precision: Precision = options.analysisOnly\n\t\t? 'f32'\n\t\t: options.precision ??\n\t\t\t(bytes <= maxBytes ? 'f32' : 'i16');\n\n\t// Hands neither player holds never carry reach, so they need no ranking.\n\tconst relevant = new Uint8Array(COMBOS);\n\tfor (const combo of spot.players[0].combos) relevant[combo] = 1;\n\tfor (const combo of spot.players[1].combos) relevant[combo] = 1;\n\n\tconst showdown = buildShowdownTable(spot.runouts, relevant);\n\tconst layout = buildLayout(spot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision]);\n\tconst weights = runoutWeights(spot.runouts);\n\n\tconst requested = resolveWorkers(options);\n\tconst plan = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;\n\n\t// Workers need the accumulators in shared memory. Allocating shared for a\n\t// single-threaded solve would cost nothing but buys nothing either.\n\tconst allocate = (bytes: number): ArrayBuffer | SharedArrayBuffer =>\n\t\tplan ? new SharedArrayBuffer(bytes) : new ArrayBuffer(bytes);\n\tconst width = PRECISION_BYTES[precision];\n\tconst quantised = precision === 'i16';\n\n\tconst active = buildActiveLists(spot.runouts, spot.players, showdown);\n\tconst hands = buildHandSpace(spot.runouts, spot.players, active);\n\t// The WebAssembly engine, where it applies: one thread, 32-bit storage,\n\t// a platform with WebAssembly SIMD. It owns the storage; the context sees\n\t// it through views.\n\tconst engine =\n\t\toptions.engine !== 'js' && precision === 'f32' && !options.analysisOnly && options.simd !== false\n\t\t\t? createEngine(\n\t\t\t\t\t{\n\t\t\t\t\t\ttree: spot.tree, runouts: spot.runouts, players: spot.players, layout, active, hands,\n\t\t\t\t\t\trunoutWeight: weights, chipScale: spot.chipScale,\n\t\t\t\t\t},\n\t\t\t\t\tplan ? { plan, threads: requested, spawn: spawnEngineWorker } : undefined,\n\t\t\t\t)\n\t\t\t: 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 ? new Float64Array(allocate(layout.blocks * 8)) : null,\n\t\tsumScale: quantised ? new Float64Array(allocate(layout.blocks * 8)) : null,\n\t\tscratch: makeTerminalScratch(),\n\t\tchipScale: spot.chipScale,\n\t\tactive,\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\n\t// Seeded before any worker starts, so they all see the inherited values.\n\tlet warm: WarmStartReport | null = null;\n\tlet offset = 0;\n\tif (options.warmStart) {\n\t\tconst source = options.warmStart;\n\t\twarm = warmStart(ctx, source.solver.ctx, sameSpot(spot.source, source.spot.source));\n\t\toffset = options.warmIteration ?? source.totalIterations;\n\t}\n\n\tconst solver = makeSolver(ctx);\n\t// The engine runs its own threads; the JavaScript pool is for the rest.\n\tconst pool: Pool | null = plan && !engine\n\t\t? startPool(ctx, solver, plan, { config: spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd }, requested)\n\t\t: null;\n\tif (pool) solver.useRoot(pool.traverse);\n\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});\n\t\t\ttry {\n\t\t\t\twarmStart(real.solver.ctx, ctx, true);\n\t\t\t\treturn real.exploitabilityPercent();\n\t\t\t} finally {\n\t\t\t\treal.close();\n\t\t\t}\n\t\t},\n\t\tsnapshot(history = [], stoppedAt = 'iterations') {\n\t\t\treturn makeSolution(spot, ctx, solver, completed, offset + completed, [...history], stoppedAt, threadCount);\n\t\t},\n\t};\n}\n\n/**\n * Whether two configurations describe the very same game. Limits and how\n * runouts are stored do not change the game, so they are left out.\n */\nfunction sameSpot(a: SpotConfig, b: SpotConfig): boolean {\n\tconst plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, ...game }: SpotConfig): string =>\n\t\tJSON.stringify(game, (_, value: unknown) => (value instanceof Float64Array ? Array.from(value) : value));\n\treturn plain(a) === plain(b);\n}\n\n/** Largest rank distance within a runout bucket, for `runoutBuckets: true`. */\nconst DEFAULT_BUCKET_GAP = 1;\n\n/** Rank swaps that keep every hand of both ranges in its range. */\nfunction rangeRankMerge(players: readonly [PlayerIndex, PlayerIndex], maxGap: number): RunoutMerge {\n\tconst allowed = new Uint8Array(13 * 13);\n\tfor (let a = 0; a < 13; a++) {\n\t\tfor (let b = a; b < 13; b++) {\n\t\t\tconst map = rankSwap(a, b);\n\t\t\tlet ok = true;\n\t\t\tfor (const player of players) {\n\t\t\t\tfor (let i = 0; ok && i < player.count; i++) {\n\t\t\t\t\tconst combo = player.combos[i];\n\t\t\t\t\tconst image = comboIndex(map[COMBO_CARDS[combo * 2]], map[COMBO_CARDS[combo * 2 + 1]]);\n\t\t\t\t\tif (player.slot[image] < 0) ok = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tallowed[a * 13 + b] = allowed[b * 13 + a] = ok ? 1 : 0;\n\t\t}\n\t}\n\treturn { ranks: (a, b) => allowed[a * 13 + b] === 1, maxGap };\n}\n\nlet warnedThreads = false;\n\n/**\n * Threads a run will use. The browser build has none to offer, so anything\n * above one falls back to the calling thread, with a single warning.\n */\nfunction resolveWorkers(options: SolveOptions): number {\n\tif (options.analysisOnly) return 1;\n\tconst asked = options.workers === 'auto' ? defaultWorkerCount() : (options.workers ?? 1);\n\tif (asked > 1 && !THREADS_AVAILABLE) {\n\t\tif (!warnedThreads) {\n\t\t\twarnedThreads = true;\n\t\t\tconsole.warn(`poker-flopsolve: worker threads are Node-only; solving on one thread (${PLATFORM} build)`);\n\t\t}\n\t\treturn 1;\n\t}\n\treturn asked;\n}\n\n/** View a buffer as regret storage of the given precision. */\nexport function makeRegretStore(precision: Precision, buffer: ArrayBuffer | SharedArrayBuffer): RegretStore {\n\tif (precision === 'f64') return new Float64Array(buffer);\n\treturn precision === 'f32' ? new Float32Array(buffer) : new Int16Array(buffer);\n}\n\n/** View a buffer as strategy-sum storage of the given precision. */\nexport function makeSumStore(precision: Precision, buffer: ArrayBuffer | SharedArrayBuffer): SumStore {\n\tif (precision === 'f64') return new Float64Array(buffer);\n\treturn precision === 'f32' ? new Float32Array(buffer) : new Uint16Array(buffer);\n}\n\n/**\n * Solve a prepared spot.\n * @param spot from {@link defineSpot}\n * @param options solver tuning\n */\nexport function solve(spot: Spot, options: SolveOptions = {}): Solution {\n\tconst iterations = options.iterations ?? 500;\n\tconst target = options.targetPercent ?? 0;\n\tconst fixed = options.exploitEvery ?? 0;\n\tconst run = createRun(spot, options);\n\tconst history: Progress[] = [];\n\tconst started = Date.now();\n\n\ttry {\n\t\treturn runAll();\n\t} finally {\n\t\trun.close();\n\t}\n\n\tfunction runAll(): Solution {\n\t\t// Nothing to measure for: run straight through in one call.\n\t\tif (fixed <= 0 && target <= 0) {\n\t\t\trun.step(iterations);\n\t\t\treturn run.snapshot(history, 'iterations');\n\t\t}\n\n\t\tlet stoppedAt: 'target' | 'iterations' = 'iterations';\n\t\tlet done = 0;\n\t\tlet next = fixed > 0 ? fixed : Math.min(iterations, FIRST_CHECK);\n\t\tlet prevIteration = 0;\n\t\tlet prevExploitability = 0;\n\n\t\twhile (done < iterations) {\n\t\t\tconst until = Math.min(next, iterations);\n\t\t\trun.step(until - done);\n\t\t\tdone = until;\n\n\t\t\t// One snapshot, because it caches the best-response pass that both\n\t\t\t// of these read. Two calls on the run itself would pay for it twice.\n\t\t\tconst measured = run.snapshot();\n\t\t\tconst info: Progress = {\n\t\t\t\titeration: done,\n\t\t\t\texploitability: measured.exploitability(),\n\t\t\t\telapsedMs: Date.now() - started,\n\t\t\t};\n\t\t\thistory.push(info);\n\t\t\toptions.onProgress?.(info);\n\n\t\t\tif (target > 0 && measured.exploitabilityPercent() <= target) {\n\t\t\t\tstoppedAt = 'target';\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (fixed > 0) {\n\t\t\t\tnext = done + fixed;\n\t\t\t} else {\n\t\t\t\t// Aim just short of where the target is predicted to be met, so\n\t\t\t\t// the overshoot is a few iterations rather than a whole doubling.\n\t\t\t\tconst predicted = predictCrossing(\n\t\t\t\t\tprevIteration,\n\t\t\t\t\tprevExploitability,\n\t\t\t\t\tdone,\n\t\t\t\t\tinfo.exploitability,\n\t\t\t\t\t(target * spot.potUnits) / (100 * spot.chipScale),\n\t\t\t\t);\n\t\t\t\tconst aim = predicted > 0 ? predicted * 0.95 : done * MAX_GROWTH;\n\t\t\t\tconst bounded = Math.min(Math.max(aim, done * MIN_GROWTH), done * MAX_GROWTH);\n\t\t\t\tnext = Math.max(done + 1, Math.ceil(bounded));\n\t\t\t\tprevIteration = done;\n\t\t\t\tprevExploitability = info.exploitability;\n\t\t\t}\n\t\t}\n\t\treturn run.snapshot(history, stoppedAt);\n\t}\n}\n\n/** Iterations before the first exploitability check. */\nconst FIRST_CHECK = 10;\n\n/** Bounds on how far ahead the next check may be scheduled. */\nconst MIN_GROWTH = 1.1;\nconst MAX_GROWTH = 2;\n\n/**\n * Predict the iteration at which exploitability will reach `target`.\n *\n * CFR+ exploitability falls as roughly `C / T^p`, so two measurements pin both\n * constants and the crossing follows. This beats any fixed cadence badly enough\n * to be worth the eight lines: a check is a full best-response pass for both\n * players, as costly as an iteration.\n *\n * Returns 0 when the two points say nothing useful — equal values, a rise, or a\n * non-finite fit — and the caller falls back to stepping the gap up.\n *\n * Exported because the browser UI drives its own loop, to stay stoppable, and\n * should schedule its checks the same way rather than reinventing a cadence.\n * Unit-agnostic: `e1`, `e2` and `target` need only share units.\n */\nexport function predictCrossing(\n\tt1: number,\n\te1: number,\n\tt2: number,\n\te2: number,\n\ttarget: number,\n): number {\n\tif (!(e1 > e2) || !(e2 > 0) || t2 <= t1) return 0;\n\tconst p = Math.log(e1 / e2) / Math.log(t2 / t1);\n\tif (!(p > 0)) return 0;\n\tconst predicted = t2 * (e2 / target) ** (1 / p);\n\treturn Number.isFinite(predicted) ? predicted : 0;\n}\n\nfunction makeSolution(\n\tspot: Spot,\n\tctx: Context,\n\tsolver: Solver,\n\titerations: number,\n\ttotalIterations: number,\n\thistory: Progress[],\n\tstoppedAt: 'target' | 'iterations',\n\tworkers: number,\n): Solution {\n\tconst { tree } = spot;\n\tconst parent = new Int32Array(tree.nodeCount).fill(-1);\n\tconst viaEdge = new Int32Array(tree.nodeCount).fill(-1);\n\tfor (let node = 0; node < tree.nodeCount; node++) {\n\t\tfor (let e = 0; e < tree.numEdges[node]; e++) {\n\t\t\tconst edge = tree.firstEdge[node] + e;\n\t\t\tparent[tree.edgeChild[edge]] = node;\n\t\t\tviaEdge[tree.edgeChild[edge]] = edge;\n\t\t}\n\t}\n\n\tconst label = (edge: number): string => {\n\t\tconst kind = tree.edgeAction[edge];\n\t\tconst amount = tree.edgeTarget[edge] / spot.chipScale;\n\t\treturn kind >= ActionKind.Bet ? `${ACTION_LABELS[kind]} ${amount}` : ACTION_LABELS[kind];\n\t};\n\n\tconst reachAt = (node: number, board: number, player: 0 | 1): Float64Array => {\n\t\tconst index = spot.players[player];\n\t\tconst reach = new Float64Array(COMBOS);\n\t\tfor (let i = 0; i < index.count; i++) reach[index.combos[i]] = index.weights[index.combos[i]];\n\t\tconst round = tree.round[node];\n\n\t\tfor (let current = node; parent[current] >= 0; current = parent[current]) {\n\t\t\tconst owner = parent[current];\n\t\t\tif (tree.kind[owner] !== NodeKind.Decision || tree.player[owner] !== player) continue;\n\t\t\tconst at = boardAtRound(spot.runouts, board, round, tree.round[owner]);\n\t\t\tconst { actions, probs } = solver.averageStrategyAt(owner, at);\n\t\t\tconst action = viaEdge[current] - tree.firstEdge[owner];\n\t\t\tfor (let i = 0; i < index.count; i++) reach[index.combos[i]] *= probs[i * actions + action];\n\t\t}\n\t\treturn reach;\n\t};\n\n\tlet cachedEv: [number, number] | null = null;\n\tlet cachedExploit: number | null = null;\n\n\treturn {\n\t\tspot,\n\t\titerations,\n\t\ttotalIterations,\n\t\tstoppedAt,\n\t\tworkers,\n\t\tsolver,\n\t\thistory,\n\t\tev(player) {\n\t\t\tcachedEv ??= solver.expectedValue();\n\t\t\treturn cachedEv[player];\n\t\t},\n\t\texploitability() {\n\t\t\tcachedExploit ??= solver.exploitability();\n\t\t\treturn cachedExploit;\n\t\t},\n\t\texploitabilityPercent() {\n\t\t\tcachedExploit ??= solver.exploitability();\n\t\t\treturn (100 * cachedExploit) / (spot.potUnits / spot.chipScale);\n\t\t},\n\t\tstrategyAt(node, board) {\n\t\t\tif (tree.kind[node] !== NodeKind.Decision) throw new Error(`Node ${node} is not a decision`);\n\t\t\tconst owner = tree.player[node] as 0 | 1;\n\t\t\tconst { actions, probs } = solver.averageStrategyAt(node, board);\n\t\t\tconst names: string[] = [];\n\t\t\tfor (let a = 0; a < actions; a++) names.push(label(tree.firstEdge[node] + a));\n\t\t\treturn { node, board, player: owner, actions: names, combos: spot.players[owner].combos, probs };\n\t\t},\n\t\tpath(node) {\n\t\t\tconst steps: string[] = [];\n\t\t\tlet current = node;\n\t\t\twhile (parent[current] >= 0) {\n\t\t\t\tconst owner = parent[current];\n\t\t\t\tsteps.push(tree.kind[owner] === NodeKind.Decision ? label(viaEdge[current]) : '/');\n\t\t\t\tcurrent = owner;\n\t\t\t}\n\t\t\treturn steps.reverse().join(' ') || '(root)';\n\t\t},\n\t\treachAt,\n\t\tsubgameAt(node, board, betting = {}) {\n\t\t\tconst opensRound = node === 0 || (parent[node] >= 0 && tree.kind[parent[node]] === NodeKind.Chance);\n\t\t\tif (tree.kind[node] !== NodeKind.Decision || !opensRound) {\n\t\t\t\tthrow new Error(`Node ${node} does not open a betting round; a subgame must start where one does`);\n\t\t\t}\n\t\t\tconst round = tree.round[node];\n\t\t\tif (board < 0 || board >= spot.runouts.counts[round]) {\n\t\t\t\tthrow new Error(`Board ${board} is out of range for round ${round}`);\n\t\t\t}\n\n\t\t\t// A round opens with both players level, so what is in the middle\n\t\t\t// is dead money from here on and the stacks have shrunk equally.\n\t\t\tconst width = spot.runouts.width[round];\n\t\t\tconst cards = spot.runouts.cards[round].subarray(board * width, board * width + width);\n\t\t\tconst invested = (tree.pot[node] - spot.potUnits) / 2;\n\t\t\tconst { source } = spot;\n\t\t\t// Settings given per round lose the rounds already played.\n\t\t\tconst later = <T>(value: T | readonly T[], listed: boolean): T | readonly T[] =>\n\t\t\t\tlisted && (value as readonly T[]).length > 1 ? (value as readonly T[]).slice(round) : value;\n\t\t\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\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\tminWeight: source.minWeight,\n\t\t\t\tisomorphism: source.isomorphism,\n\t\t\t\tmaxCombos: 'maxCombos' in betting ? betting.maxCombos : source.maxCombos,\n\t\t\t\tmaxBytes: 'maxBytes' in betting ? betting.maxBytes : source.maxBytes,\n\t\t\t\tchipScale: spot.chipScale,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport { formatCards, parseCards };\n"],"mappings":";AAgBA,SAAS,YAAY,kBAAkB;;;ACDvC,IAAM,aAAa;AAGnB,IAAM,aAAa;AAGZ,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,QAA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AS,cAAc,QAAQ,SAAS,CAAC,IAAI,MAAM,CAAC;AAAA,EACtF;AAEA,UAAQ,IAAI,SAAS,QAAQ,MAAM,CAAC;AACpC,UAAQ,OAAO,SAAS,QAAQ,IAAI;AACrC;AAEA,YAAY,MAAM;","names":["relevant","i","config","ctx","childCols","active","regretMatch","weights","weights","showdown","makeBuffers","simd","treeDepth","ctx","reachMe","reachOpp","weights","walk","weights","RANK_CHARS","high","span","weights","config","weights","layout","precision"]}
|
|
1
|
+
{"version":3,"sources":["../src/worker.ts","../src/cards.ts","../src/eval7.ts","../src/showdown.ts","../src/hands.ts","../src/tree.ts","../src/pairs.ts","../src/wasm/kernels.ts","../src/kernels.ts","../src/cfr.ts","../src/abstraction.ts","../src/runouts.ts","../src/range.ts","../src/platform/node.ts","../src/parallel.ts","../src/history-merge.ts","../src/betting.ts","../src/index.ts"],"sourcesContent":["/**\n * Solver worker.\n *\n * Purpose: traverse one shard of the runout space.\n *\n * A worker owns a contiguous range of runouts at the split round; the main\n * thread owns the first, so worker `n` takes shard `n + 1`. Because\n * storage is indexed runout-outermost, everything it writes below that round is\n * its own; nothing is shared and nothing is locked. It never visits a node above\n * the split, so the non-linear CFR+ clamp there stays the main thread's job.\n *\n * The spot is rebuilt from its config rather than shipped across as typed\n * arrays: `defineSpot` is deterministic, so both sides derive byte-identical\n * structures, and only the two accumulators are actually shared.\n */\n\nimport { parentPort, workerData } from 'node:worker_threads';\nimport { COMBOS } from './cards.ts';\nimport type { CompactPlan, Context, Mode } from './cfr.ts';\nimport {\n\tbuildActiveLists,\n\tbuildLayout,\n\tmakeSampling,\n\tmakeSolver,\n\tmakeTerminalScratch,\n\tmatchupMass,\n\tplanSampling,\n\trunoutWeights,\n} from './cfr.ts';\nimport { defineSpot, makeRegretStore, makeSumStore, PRECISION_BYTES } from './index.ts';\nimport type { Approximations, Precision, SpotConfig } from './index.ts';\nimport { buildShowdownTable } from './showdown.ts';\nimport { buildHandSpace } from './hands.ts';\nimport type { WorkerSetup } from './parallel.ts';\nimport { COMMAND, CONTROL } from './parallel.ts';\n\nconst setup = workerData as WorkerSetup;\nconst { config, dcfr, precision, simd, compact, approximations } = setup.payload as {\n\tconfig: SpotConfig;\n\tdcfr: boolean;\n\tprecision: Precision;\n\tsimd: boolean;\n\tcompact: CompactPlan | null;\n\tapproximations?: Approximations;\n};\n\nconst spot = defineSpot(config);\nconst relevant = new Uint8Array(COMBOS);\nfor (const combo of spot.players[0].combos) relevant[combo] = 1;\nfor (const combo of spot.players[1].combos) relevant[combo] = 1;\n\nconst weights = runoutWeights(spot.runouts);\nconst layout = buildLayout(\n\tspot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision], spot.historyAlias, compact ?? undefined,\n);\n\nconst showdown = buildShowdownTable(spot.runouts, relevant);\nconst active = buildActiveLists(spot.runouts, spot.players, showdown);\nconst hands = buildHandSpace(spot.runouts, spot.players, active);\nconst ctx: Context = {\n\ttree: spot.tree,\n\trunouts: spot.runouts,\n\tplayers: spot.players,\n\tlayout,\n\tshowdown,\n\tregret: makeRegretStore(precision, setup.regret),\n\tstrategySum: makeSumStore(precision, setup.strategySum),\n\tregretScale: setup.regretScale ? new Float64Array(setup.regretScale) : null,\n\tsumScale: setup.sumScale ? new Float64Array(setup.sumScale) : null,\n\tcompact,\n\tcompactRegret:\n\t\tsetup.compactRegret?.map((chunk) => (compact?.float ? new Float32Array(chunk) : new Int8Array(chunk))) ?? null,\n\thandShift: setup.handShift?.map((chunk) => new Uint8Array(chunk)) ?? null,\n\tcompactSum: setup.compactSum?.map((chunk) => new Uint8Array(chunk)) ?? null,\n\tsumShift: setup.sumShift?.map((chunk) => new Uint8Array(chunk)) ?? null,\n\tcompactScale: setup.compactScale ? new Float64Array(setup.compactScale) : null,\n\tscratch: makeTerminalScratch(),\n\tchipScale: spot.chipScale,\n\tactive,\n\thands,\n\trunoutWeight: weights,\n\ttotalMass: matchupMass(spot.players[0].weights, spot.players[1].weights) * weights[0],\n\tdcfr,\n\tshardStart: setup.shardStart,\n\tshardEnd: setup.shardEnd,\n\tshardRound: setup.plan.round,\n\tapplyUpdates: true,\n\tchanceCollect: null,\n\tchanceOverride: null,\n\tentryIndexOf: null,\n\texpandOrbits: false,\n\tsimd,\n\t// This worker's runouts are its own, so are their blocks and the marks on them.\n\tdiscounted: layout.shared ? new Int32Array(layout.blocks) : null,\n};\n\n// Chance sampling's state lives in shared memory; this worker's runouts own\n// their baselines and marks there, as they own their storage.\nconst samplingOptions = approximations?.chanceSampling;\nif (samplingOptions && setup.sampling) {\n\tconst [baseline, lastWalk, lastUpdate] = setup.sampling;\n\tctx.sampling = makeSampling(planSampling(spot.tree, spot.runouts, active, layout, samplingOptions), {\n\t\tbaseline: new Float32Array(baseline),\n\t\tlastWalk: new Int32Array(lastWalk),\n\t\tlastUpdate: new Int32Array(lastUpdate),\n\t});\n}\n\nconst solver = makeSolver(ctx);\nconst control = new Int32Array(setup.control);\nconst exchange = new Float64Array(setup.exchange);\nconst reachFloats = setup.entryCount * 2 * COMBOS;\nconst partialBase = reachFloats + setup.workerId * setup.entryCount * COMBOS;\n\nconst reachMe = new Float64Array(COMBOS);\nconst reachOpp = new Float64Array(COMBOS);\n\n// Latch the generation BEFORE announcing readiness, so no dispatch that happens\n// after this point can be missed.\nlet generation = Atomics.load(control, CONTROL.generation);\nAtomics.add(control, CONTROL.ready, 1);\nAtomics.notify(control, CONTROL.ready);\n\nfor (;;) {\n\tAtomics.wait(control, CONTROL.generation, generation);\n\tgeneration = Atomics.load(control, CONTROL.generation);\n\tif (Atomics.load(control, CONTROL.command) === COMMAND.exit) break;\n\n\tconst mode = Atomics.load(control, CONTROL.mode) as Mode;\n\tconst traverser = Atomics.load(control, CONTROL.traverser) as 0 | 1;\n\tconst iterWeight = Atomics.load(control, CONTROL.iterWeight);\n\n\ttry {\n\t\tfor (let entry = 0; entry < setup.plan.entryNodes.length; entry++) {\n\t\t\tconst node = setup.plan.entryNodes[entry];\n\t\t\tfor (let i = 0; i < COMBOS; i++) {\n\t\t\t\treachMe[i] = exchange[entry * 2 * COMBOS + i];\n\t\t\t\treachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];\n\t\t\t}\n\t\t\tconst value = solver.traverseChance(mode, traverser, iterWeight, node, reachMe, reachOpp);\n\t\t\tfor (let i = 0; i < COMBOS; i++) exchange[partialBase + entry * COMBOS + i] = value[i];\n\t\t}\n\t} catch (error) {\n\t\t// The main thread is blocked in Atomics.wait and cannot see this\n\t\t// thread's error event, so say so in shared memory (and count as\n\t\t// done, below).\n\t\tAtomics.store(control, CONTROL.failed, 1);\n\t\tthrow error;\n\t} finally {\n\t\tAtomics.add(control, CONTROL.done, 1);\n\t\tAtomics.notify(control, CONTROL.done);\n\t}\n}\n\nparentPort?.close();\n","/**\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 * 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 * 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 * 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/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBycDC3JlZ3JldE1hdGNoAAAMYXZlcmFnZU1hdGNoAAEGbWVtb3J5AgAK0AkC8AMDB38BfAJ7IARBfnEhCANAIAQgBUoEQCACIAVBA3RqRAAAA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AS3o/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, 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","/**\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 * Node platform.\n *\n * Purpose: the one place the solver touches Node-only APIs. A browser build\n * swaps this module for `browser.ts`, which has the same exports; see\n * `scripts/browser-platform.ts`.\n */\n\nimport { availableParallelism } from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport type { WorkerSetup } from '../parallel.ts';\nimport type { EngineWorkerSetup } from '../engine.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'node';\n\n/**\n * The most threads a solve can use here: as many as asked, on either engine.\n * @param _engine whether the WebAssembly engine is to run\n */\nexport function threadLimit(_engine: boolean): number {\n\treturn Infinity;\n}\n\n/** Default ceiling on solver storage. */\nexport const DEFAULT_MAX_BYTES = 6 * 1024 * 1024 * 1024;\n\n/**\n * The parent's Node flags, minus any a worker started from a file rejects:\n * `--input-type` is for code given as a string (`node -e`), and a worker\n * inheriting it fails to start.\n */\nfunction workerFlags(): string[] {\n\treturn process.execArgv.filter((flag) => !flag.startsWith('--input-type'));\n}\n\n/** A spawned solver thread. */\nexport interface WorkerHandle {\n\tterminate(): void;\n}\n\n/**\n * Suggested worker count for this machine, the calling thread included.\n *\n * One less than the available parallelism, but never under two. Scaling stays\n * monotone right up to the core count — a flop solve measured 3.3x on 4\n * workers, 3.9x on 6 and 4.3x on 8 across 8 cores — so the only reason to hold\n * one back is leaving the machine responsive, and on two cores that would mean\n * not splitting at all.\n */\nexport function defaultWorkerCount(): number {\n\tconst cores = availableParallelism();\n\treturn cores < 2 ? 1 : Math.max(2, cores - 1);\n}\n\n/**\n * Start one solver thread on `worker.ts`.\n *\n * @param setup everything the worker needs to rebuild the solver\n * @param onError called if the thread dies, so the pool can stop waiting on it\n */\nexport function spawnWorker(setup: WorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\t// From source the worker is TypeScript; from a build it sits beside this\n\t// bundle as JavaScript.\n\tconst url = new URL(import.meta.url.endsWith('.ts') ? '../worker.ts' : './worker.js', import.meta.url);\n\tconst thread = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });\n\tthread.on('error', onError);\n\tthread.unref();\n\treturn {\n\t\tterminate() {\n\t\t\tvoid thread.terminate();\n\t\t},\n\t};\n}\n\n/** Start one WebAssembly engine thread on `engine-worker.ts`. */\nexport function spawnEngineWorker(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst url = new URL(import.meta.url.endsWith('.ts') ? '../engine-worker.ts' : './engine-worker.js', import.meta.url);\n\tconst thread = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });\n\tthread.on('error', onError);\n\tthread.unref();\n\treturn {\n\t\tterminate() {\n\t\t\tvoid thread.terminate();\n\t\t},\n\t};\n}\n\n/**\n * Why a solve gets fewer threads than it asked for: never, in Node.\n * @param _engine whether the WebAssembly engine is to run\n */\nexport function threadAdvice(_engine: boolean): string {\n\treturn '';\n}\n\n/** Node always has worker threads. */\nexport function threadsUnavailableReason(): string | null {\n\treturn null;\n}\n\n/**\n * Nothing to start ahead of time in Node: threads start with each solve.\n * @param count threads wanted, this one included; defaults to {@link defaultWorkerCount}\n */\nexport async function prepareThreads(count?: number): Promise<number> {\n\treturn Math.max(1, Math.floor(count ?? defaultWorkerCount()));\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 * 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 * 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":";AAgBA,SAAS,YAAY,kBAAkB;;;ACDvC,IAAM,aAAa;AAGnB,IAAM,aAAa;AAGZ,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,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Aa,QAAQ,KAAK,SAAS,QAAQ,UAAU;AACrD,MAAI,QAAQ,KAAK,SAAS,QAAQ,OAAO,MAAM,QAAQ,KAAM;AAE7D,QAAM,OAAO,QAAQ,KAAK,SAAS,QAAQ,IAAI;AAC/C,QAAM,YAAY,QAAQ,KAAK,SAAS,QAAQ,SAAS;AACzD,QAAM,aAAa,QAAQ,KAAK,SAAS,QAAQ,UAAU;AAE3D,MAAI;AACH,aAAS,QAAQ,GAAG,QAAQ,MAAM,KAAK,WAAW,QAAQ,SAAS;AAClE,YAAM,OAAO,MAAM,KAAK,WAAW,KAAK;AACxC,eAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAChC,gBAAQ,CAAC,IAAI,SAAS,QAAQ,IAAI,SAAS,CAAC;AAC5C,iBAAS,CAAC,IAAI,SAAS,QAAQ,IAAI,SAAS,SAAS,CAAC;AAAA,MACvD;AACA,YAAM,QAAQ,OAAO,eAAe,MAAM,WAAW,YAAY,MAAM,SAAS,QAAQ;AACxF,eAAS,IAAI,GAAG,IAAI,QAAQ,IAAK,UAAS,cAAc,QAAQ,SAAS,CAAC,IAAI,MAAM,CAAC;AAAA,IACtF;AAAA,EACD,SAAS,OAAO;AAIf,YAAQ,MAAM,SAAS,QAAQ,QAAQ,CAAC;AACxC,UAAM;AAAA,EACP,UAAE;AACD,YAAQ,IAAI,SAAS,QAAQ,MAAM,CAAC;AACpC,YAAQ,OAAO,SAAS,QAAQ,IAAI;AAAA,EACrC;AACD;AAEA,YAAY,MAAM;","names":["compact","relevant","i","config","ctx","hands","childCols","regretMatch","weights","compact","width","hands","active","layout","p","ctx","weights","showdown","makeBuffers","simd","treeDepth","reachMe","reachOpp","hands","stochastic","high","walk","weights","RANK_CHARS","high","span","weights","walk","config","config","weights","layout","compact","precision"]}
|