{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "explorer-app",
  "title": "Explorer",
  "description": "pokerstudy.ai's Explorer: walk every solved preflop tree (hold'em, PLO, PLO5, PLO6 heads-up, PLO 9-max, tournament and ICM) seat by seat, with the strategy grid or PLO hand lists, hand search, bucket mixes and the solution picker, and, where the host serves a solver, inline postflop solves. Point it at your feeds and switch features with setExplorerHost (lib/explorer/host.ts).",
  "dependencies": [
    "@base-ui/react",
    "@hugeicons/core-free-icons",
    "@hugeicons/react",
    "@xyflow/react",
    "class-variance-authority",
    "clsx",
    "lucide-react",
    "sonner",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://www.pokerstudy.ai/r/button.json",
    "https://www.pokerstudy.ai/r/side-panel.json",
    "https://www.pokerstudy.ai/r/search-field.json",
    "https://www.pokerstudy.ai/r/hand-matrix.json",
    "https://www.pokerstudy.ai/r/playing-card.json",
    "https://www.pokerstudy.ai/r/trainer-cards.json",
    "https://www.pokerstudy.ai/r/trainer-theme.json",
    "https://www.pokerstudy.ai/r/poker-core.json",
    "https://www.pokerstudy.ai/r/trainer-types.json"
  ],
  "files": [
    {
      "path": "src/components/blocks/filtering-1.tsx",
      "content": "\"use client\";\n\n// Facet-filter parts from React Bits Pro App UI `filtering-1` (\"Faceted\n// product filters\"): the ruled facet rail with per-option counts, removable\n// filter chips with \"Clear all\", the mobile \"Filters\" toggle, the result frame\n// and the no-results state. The block's demo catalogue is stripped; only the\n// reusable pieces and their tokens are kept, unchanged, so every picker built\n// on them looks like the rest of App UI. First used by the Explorer's\n// Solutions drawer (components/explorer/solution-selector.tsx).\n\nimport type { ReactNode } from \"react\";\nimport { HugeiconsIcon } from \"@hugeicons/react\";\nimport {\n  Cancel01Icon,\n  SlidersHorizontalIcon,\n  Tick02Icon,\n} from \"@hugeicons/core-free-icons\";\n\nconst cx = (...c: (string | false | null | undefined)[]) =>\n  c.filter(Boolean).join(\" \");\n\nconst text1 =\n  \"text-neutral-900 dark:text-neutral-100\";\nconst text3 =\n  \"text-neutral-900/66 dark:text-neutral-100/66\";\nconst controlEdge =\n  \"border border-neutral-900/12 dark:border-neutral-100/14\";\nconst rowsRuled =\n  \"divide-y divide-neutral-900/8 dark:divide-neutral-100/8\";\nconst typeLabel =\n  \"text-[14px]/[16px] font-[450]\";\nconst typeBodySm =\n  \"text-[13px]/[18px] font-normal\";\nconst typeCaption =\n  \"text-[12px]/[16px] font-normal tabular-nums\";\nconst primaryButton =\n  \"relative inline-flex shrink-0 cursor-pointer items-center justify-center whitespace-nowrap select-none transition-[color,background-color,border-color,box-shadow,outline-color,scale,filter] duration-[120ms] ease-[cubic-bezier(0.2,0,0,1)] active:scale-[0.98] active:duration-[60ms] motion-reduce:active:scale-100 disabled:cursor-not-allowed aria-busy:cursor-progress focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--rb-accent,oklch(20.5%_0_0))] dark:focus-visible:outline-[var(--rb-accent,oklch(100%_0_0))] bg-[linear-gradient(180deg,color-mix(in_oklab,var(--rb-accent,oklch(20.5%_0_0))_84%,white),color-mix(in_oklab,var(--rb-accent,oklch(20.5%_0_0))_94%,black))] text-[var(--rb-accent-fg,oklch(100%_0_0))] shadow-[inset_0_2px_0_-1px_rgb(255_255_255/0.2),inset_0_-2px_0_-1px_rgb(0_0_0/0.3),inset_0_0_0_1px_color-mix(in_oklab,var(--rb-accent,oklch(20.5%_0_0))_88%,black),0_1px_1px_rgb(0_0_0/0.22),0_2px_5px_-2px_rgb(0_0_0/0.3)] hover:not-disabled:brightness-110 active:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--rb-accent,oklch(20.5%_0_0))_88%,black),inset_0_1px_2px_rgb(0_0_0/0.42)] disabled:opacity-40 disabled:shadow-none dark:bg-[linear-gradient(180deg,color-mix(in_oklab,var(--rb-accent,oklch(100%_0_0))_84%,white),color-mix(in_oklab,var(--rb-accent,oklch(100%_0_0))_94%,black))] dark:text-[var(--rb-accent-fg,oklch(20.5%_0_0))] dark:shadow-[inset_0_2px_0_-1px_rgb(255_255_255/0.2),inset_0_-2px_0_-1px_rgb(0_0_0/0.3),inset_0_0_0_1px_color-mix(in_oklab,var(--rb-accent,oklch(100%_0_0))_88%,black),0_1px_1px_rgb(0_0_0/0.66),0_2px_5px_-2px_rgb(0_0_0/0.9)] dark:active:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--rb-accent,oklch(100%_0_0))_88%,black),inset_0_1px_2px_rgb(0_0_0/0.42)] dark:disabled:shadow-none\";\nconst secondaryButton =\n  \"relative inline-flex shrink-0 cursor-pointer items-center justify-center whitespace-nowrap select-none transition-[color,background-color,border-color,box-shadow,outline-color,scale,filter] duration-[120ms] ease-[cubic-bezier(0.2,0,0,1)] active:scale-[0.98] active:duration-[60ms] motion-reduce:active:scale-100 disabled:cursor-not-allowed aria-busy:cursor-progress focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--rb-accent,oklch(20.5%_0_0))] dark:focus-visible:outline-[var(--rb-accent,oklch(100%_0_0))] border border-neutral-900/12 bg-white text-neutral-900 shadow-[0_1px_2px_-1px_rgb(0_0_0/0.12)] hover:not-disabled:border-neutral-900/32 hover:not-disabled:bg-linear-to-b hover:not-disabled:from-neutral-900/3 hover:not-disabled:to-neutral-900/3 active:shadow-[inset_0_1px_2px_rgb(0_0_0/0.12)] disabled:border-neutral-900/8 disabled:text-neutral-900/40 disabled:shadow-none dark:border-neutral-100/14 dark:bg-neutral-900 dark:text-neutral-100 dark:shadow-[0_1px_2px_-1px_rgb(0_0_0/0.36)] dark:hover:not-disabled:border-neutral-100/32 dark:hover:not-disabled:from-neutral-100/3 dark:hover:not-disabled:to-neutral-100/3 dark:active:shadow-[inset_0_1px_2px_rgb(0_0_0/0.4)] dark:disabled:border-neutral-100/8 dark:disabled:text-neutral-100/40\";\nconst buttonMd =\n  \"h-8 gap-2 rounded-[var(--rb-r-sm,6px)] px-4 text-[14px]/[16px] font-[450]\";\nconst chip =\n  \"relative inline-flex h-7 max-w-full min-w-0 shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-[var(--rb-r-sm,6px)] border border-neutral-900/12 dark:border-neutral-100/14 bg-white dark:bg-neutral-900 px-2.5 text-[14px]/[16px] font-[450] text-neutral-900 dark:text-neutral-100 select-none shadow-[0_1px_2px_-1px_rgb(0_0_0/0.12)] dark:shadow-[0_1px_2px_-1px_rgb(0_0_0/0.36)] transition-[background-color,border-color,color,scale,outline-color] duration-[120ms] ease-[cubic-bezier(0.2,0,0,1)] active:scale-[0.98] active:duration-[60ms] motion-reduce:active:scale-100 hover:not-disabled:border-neutral-900/32 aria-pressed:border-neutral-900/32 aria-pressed:bg-neutral-900/9 aria-expanded:border-neutral-900/32 disabled:cursor-not-allowed disabled:text-neutral-900/40 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--rb-accent,oklch(20.5%_0_0))] dark:focus-visible:outline-[var(--rb-accent,oklch(100%_0_0))] dark:hover:not-disabled:border-neutral-100/32 dark:aria-pressed:border-neutral-100/32 dark:aria-pressed:bg-neutral-100/16 dark:aria-expanded:border-neutral-100/32 dark:disabled:text-neutral-100/40\";\nconst chipRemove =\n  \"-me-1.5 inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-[var(--rb-r-xs,4px)] text-neutral-900/80 dark:text-neutral-100/80 hover:bg-neutral-900/5 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--rb-accent,oklch(20.5%_0_0))] dark:focus-visible:outline-[var(--rb-accent,oklch(100%_0_0))] dark:hover:bg-neutral-100/5 dark:hover:text-neutral-100\";\nconst frame =\n  \"relative flex min-w-0 flex-col overflow-hidden rounded-[var(--rb-r-lg,10px)] border border-neutral-900/10 dark:border-neutral-100/14 bg-white dark:bg-neutral-900 text-neutral-900 dark:text-neutral-100\";\nconst frameTitle =\n  \"min-w-0 truncate text-[14px]/[16px] font-[450] text-neutral-900 dark:text-neutral-100\";\nconst emptyTitle =\n  \"text-[16px]/[20px] font-[450] tracking-[-0.015em] text-neutral-900 dark:text-neutral-100\";\nconst emptyDescription =\n  \"max-w-[48ch] text-[13px]/[18px] text-neutral-900/80 dark:text-neutral-100/80\";\nconst navItem =\n  \"flex h-8 w-full min-w-0 cursor-pointer items-center gap-2 rounded-[var(--rb-r-sm,6px)] px-2 text-left text-[14px]/[16px] font-[450] text-neutral-900/80 transition-[background-color,color] duration-[120ms] ease-[cubic-bezier(0.2,0,0,1)] [&_svg]:shrink-0 hover:bg-neutral-900/5 hover:text-neutral-900 aria-[current=page]:bg-neutral-900/9 aria-[current=page]:text-neutral-900 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[var(--rb-accent,oklch(20.5%_0_0))] dark:focus-visible:outline-[var(--rb-accent,oklch(100%_0_0))] dark:text-neutral-100/80 dark:hover:bg-neutral-100/5 dark:hover:text-neutral-100 dark:aria-[current=page]:bg-neutral-100/9 dark:aria-[current=page]:text-neutral-100\";\nconst navCount =\n  \"ms-auto text-[12px]/[16px] font-[450] tabular-nums text-neutral-900/66 dark:text-neutral-100/66\";\nconst clearFilters =\n  \"inline-flex h-7 cursor-pointer items-center rounded-[var(--rb-r-sm,6px)] px-2 text-[14px]/[16px] font-[450] text-neutral-900/80 dark:text-neutral-100/80 decoration-1 underline-offset-4 hover:text-neutral-900 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--rb-accent,oklch(20.5%_0_0))] dark:focus-visible:outline-[var(--rb-accent,oklch(100%_0_0))] dark:hover:text-neutral-100\";\nconst metaText = cx(typeBodySm, text3);\nconst captionText = cx(typeCaption, text3);\n// The block's checkbox, drawn round for single-choice facets.\nconst radio =\n  \"peer size-4 shrink-0 cursor-pointer appearance-none rounded-full border border-neutral-900/50 bg-white transition-[background-color,border-color,box-shadow] duration-[120ms] ease-[cubic-bezier(0.2,0,0,1)] checked:border-[5px] checked:border-[var(--rb-accent,oklch(20.5%_0_0))] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--rb-accent,oklch(20.5%_0_0))] dark:border-neutral-100/50 dark:bg-neutral-900 dark:checked:border-[var(--rb-accent,oklch(100%_0_0))] dark:focus-visible:outline-[var(--rb-accent,oklch(100%_0_0))]\";\n\nexport const filteringTokens = { text1, text3, metaText, captionText, typeLabel, frameTitle };\n\n/** The facet rail: groups separated by hairline rules. */\nexport function FacetRail({ children }: { children: ReactNode }) {\n  return <div className={rowsRuled}>{children}</div>;\n}\n\n/** One facet group inside a {@link FacetRail}. */\nexport function FacetGroup({ label, children }: { label: string; children: ReactNode }) {\n  return (\n    <fieldset className=\"py-4 first:pt-0 last:pb-0\">\n      <legend className={cx(typeLabel, text1, \"float-left mb-3 w-full\")}>{label}</legend>\n      <div className=\"clear-both\">{children}</div>\n    </fieldset>\n  );\n}\n\nexport interface FacetOption<T extends string> {\n  value: T;\n  label: string;\n  /** Results this option would show given the other facets. */\n  count: number;\n}\n\n/**\n * A single-choice facet: one row per option with its result count. Options\n * that would show nothing are dimmed (still pickable), as in the block.\n */\nexport function FacetRadioList<T extends string>({\n  name,\n  options,\n  value,\n  onChange,\n}: {\n  name: string;\n  options: FacetOption<T>[];\n  value: T;\n  onChange: (value: T) => void;\n}) {\n  return (\n    <ul className=\"-mx-2 space-y-0.5\">\n      {options.map((o) => {\n        const on = o.value === value;\n        return (\n          <li key={o.value}>\n            <label\n              aria-current={on ? \"page\" : undefined}\n              className={cx(navItem, \"max-md:h-10\", o.count === 0 && !on && \"opacity-40\")}\n            >\n              <input\n                type=\"radio\"\n                name={name}\n                value={o.value}\n                checked={on}\n                onChange={() => onChange(o.value)}\n                className={radio}\n              />\n              <span className=\"min-w-0 flex-1 truncate\">{o.label}</span>\n              <span className={cx(navCount, \"shrink-0\")}>{o.count}</span>\n            </label>\n          </li>\n        );\n      })}\n    </ul>\n  );\n}\n\n/** Active filters as removable chips, with \"Clear all\". */\nexport function ActiveFilterChips({\n  chips,\n  onClearAll,\n}: {\n  chips: { key: string; label: string; onRemove: () => void }[];\n  onClearAll: () => void;\n}) {\n  if (chips.length === 0) return null;\n  return (\n    <div className=\"flex flex-wrap items-center gap-2\">\n      {chips.map((c) => (\n        <span key={c.key} className={chip}>\n          {c.label}\n          <button\n            type=\"button\"\n            aria-label={`Remove ${c.label} filter`}\n            onClick={c.onRemove}\n            className={chipRemove}\n          >\n            <HugeiconsIcon icon={Cancel01Icon} size={12} strokeWidth={1.8} aria-hidden=\"true\" />\n          </button>\n        </span>\n      ))}\n      <button type=\"button\" onClick={onClearAll} className={clearFilters}>\n        Clear all\n      </button>\n    </div>\n  );\n}\n\n/** The block's \"Filters (n)\" button that shows the rail on small screens. */\nexport function FilterToggleButton({\n  open,\n  count,\n  onClick,\n  className,\n}: {\n  open: boolean;\n  count: number;\n  onClick: () => void;\n  className?: string;\n}) {\n  return (\n    <button\n      type=\"button\"\n      aria-expanded={open}\n      onClick={onClick}\n      className={cx(secondaryButton, buttonMd, \"h-9\", className)}\n    >\n      <HugeiconsIcon icon={SlidersHorizontalIcon} size={16} strokeWidth={1.8} aria-hidden=\"true\" />\n      Filters\n      {count > 0 ? <span className=\"tabular-nums\">({count})</span> : null}\n    </button>\n  );\n}\n\n/** A result frame: a header row (title, meta, tags) over its body. */\nexport function ResultFrame({\n  title,\n  meta,\n  tags,\n  aside,\n  muted = false,\n  children,\n}: {\n  title: ReactNode;\n  meta?: ReactNode;\n  tags?: string[];\n  /** Right-hand note in the header, e.g. \"Not browsable yet\". */\n  aside?: ReactNode;\n  muted?: boolean;\n  children: ReactNode;\n}) {\n  return (\n    <section className={cx(frame, \"gap-3 p-4\", muted && \"opacity-60\")}>\n      <header className=\"flex items-start justify-between gap-3\">\n        <div className=\"min-w-0\">\n          <h3 className={cx(frameTitle, \"whitespace-normal\")}>{title}</h3>\n          {meta ? <p className={cx(captionText, \"mt-1\")}>{meta}</p> : null}\n        </div>\n        {aside ? <span className={cx(captionText, \"shrink-0\")}>{aside}</span> : null}\n      </header>\n      {tags && tags.length > 0 ? (\n        <div className=\"-mt-1 flex flex-wrap gap-1.5\">\n          {tags.map((t) => (\n            <span\n              key={t}\n              className={cx(\n                controlEdge,\n                captionText,\n                \"inline-flex h-6 items-center rounded-[var(--rb-r-xs,4px)] px-2\",\n              )}\n            >\n              {t}\n            </span>\n          ))}\n        </div>\n      ) : null}\n      {children}\n    </section>\n  );\n}\n\n/**\n * A pickable item inside a {@link ResultFrame} (the block's chip, sized as a\n * tap target). `current` marks the selection on screen.\n */\nexport function ResultChoice({\n  label,\n  current = false,\n  disabled = false,\n  onClick,\n  title,\n}: {\n  label: string;\n  current?: boolean;\n  disabled?: boolean;\n  onClick: () => void;\n  title?: string;\n}) {\n  return (\n    <button\n      type=\"button\"\n      disabled={disabled}\n      onClick={onClick}\n      title={title}\n      aria-current={current ? \"true\" : undefined}\n      aria-pressed={current}\n      className={cx(chip, \"h-10 min-w-[4.5rem] justify-center px-3 tabular-nums\")}\n    >\n      {current ? (\n        <HugeiconsIcon icon={Tick02Icon} size={14} strokeWidth={2} aria-hidden=\"true\" />\n      ) : null}\n      {label}\n    </button>\n  );\n}\n\n/** The block's no-results state with a primary \"Clear all filters\". */\nexport function EmptyResults({\n  title,\n  description,\n  onClear,\n}: {\n  title: string;\n  description: string;\n  onClear: () => void;\n}) {\n  return (\n    <div className={cx(frame, \"items-center justify-center px-6 py-16 text-center\")}>\n      <p className={emptyTitle}>{title}</p>\n      <p className={cx(emptyDescription, \"mt-1 max-w-[320px]\")}>{description}</p>\n      <button type=\"button\" onClick={onClear} className={cx(primaryButton, buttonMd, \"mt-5\")}>\n        Clear all filters\n      </button>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/filtering-1.tsx"
    },
    {
      "path": "src/components/explorer/bottom-sheet.tsx",
      "content": "\"use client\";\n\n// Shared bottom-sheet chrome for the viewer's node editors (Edit Node, lock\n// strategy): backdrop + slide-up panel + header/body/footer scaffolding, so\n// every editor opened from a node card presents identically.\n\nimport { useEffect, type ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\n\nexport function BottomSheet({\n  title,\n  icon,\n  onClose,\n  children,\n  footer,\n}: {\n  title: string;\n  icon?: ReactNode;\n  onClose: () => void;\n  children: ReactNode;\n  /** Pinned action row under the scrollable body. */\n  footer?: ReactNode;\n}) {\n  useEffect(() => {\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") onClose();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [onClose]);\n\n  return (\n    <div\n      className=\"fixed inset-0 z-50 flex flex-col justify-end bg-black/60\"\n      role=\"dialog\"\n      aria-modal=\"true\"\n      aria-label={title}\n      onClick={onClose}\n    >\n      <div\n        className=\"animate-in fade-in slide-in-from-bottom-8 mx-auto flex w-full max-w-2xl flex-col rounded-t-2xl border border-b-0 border-border bg-card shadow-2xl duration-200\"\n        onClick={(e) => e.stopPropagation()}\n      >\n        <div className=\"mx-auto mt-2 h-1 w-10 shrink-0 rounded-full bg-border\" aria-hidden />\n        <div className=\"flex items-center justify-between px-4 py-3\">\n          <span className=\"flex items-center gap-2 text-base font-semibold text-foreground\">\n            {icon}\n            {title}\n          </span>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            aria-label=\"Close\"\n            className=\"rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n          >\n            <X className=\"size-4\" />\n          </button>\n        </div>\n        <div className=\"flex max-h-[55vh] flex-col gap-2 overflow-y-auto px-4 pb-3\">\n          {children}\n        </div>\n        {footer ? (\n          <div className=\"flex items-center justify-between gap-2 border-t border-border px-4 py-3\">\n            {footer}\n          </div>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\n/** Uniform row style for sheet content (action rows, size rows). */\nexport const SHEET_ROW = \"flex items-center gap-3 rounded-lg bg-accent/40 px-3 py-2\";\n",
      "type": "registry:component",
      "target": "components/explorer/bottom-sheet.tsx"
    },
    {
      "path": "src/components/explorer/builder.tsx",
      "content": "\"use client\";\n\n// The custom-solution builder. A focused NLHE postflop setup form (board,\n// ranges via the preflop scenario picker, bet tree) that solves with the engine\n// in `dump_nodes` mode so the whole strategy tree comes back — flop solves are\n// first-class: the defaults mirror the sample fixtures (0.75 sizing + all-in,\n// #220 river action abstraction) and a product-quality flop solve runs\n// ~10-15 min on the worker. The job lives server-side, so the builder records\n// the job id in localStorage and can re-attach after a tab reload (\"Resume\").\n// Results preview in the full SolutionViewer, then save (title + tags) to the\n// Explorer catalog and open in the viewer proper.\n\nimport { explorerHost } from \"@/lib/explorer/host\";\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { Loader2, Lock, Play, Save, Sparkles, X, Eye } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport { ScenarioStrip, type ResolvedScenario } from \"@/components/solver/scenario-strip\";\nimport { resumeSolve, startSolve, type SolveHandle } from \"@/lib/solver/client\";\nimport {\n  fullRange,\n  isEmptyRange,\n  weightsToEngineString,\n  type RangeWeights,\n} from \"@/lib/solver/range-model\";\nimport type {\n  LockedNode,\n  SolveRequest,\n  SolverProgress,\n  SolverResult,\n} from \"@/lib/solver/types\";\nimport { buildLockedResolveRequest, isWarmStartFailure } from \"@/lib/explorer/locks\";\nimport {\n  betSizingLabel,\n  streetForBoard,\n  type CustomSolutionBundle,\n  type CustomSolutionMeta,\n  type CustomSolutionSummary,\n} from \"@/lib/explorer/types\";\nimport {\n  buildPostflopSolveRequest,\n  sameSolveGeometry,\n  clearPendingSolve,\n  CUSTOM_SOLVE_DEFAULTS,\n  describeSolveError,\n  readPendingSolve,\n  solveEtaHint,\n  writePendingSolve,\n  type PendingSolve,\n} from \"@/lib/explorer/custom-solve\";\nimport { SolutionViewer } from \"./solution-viewer\";\nimport { CardGridPicker } from \"./card-picker\";\nimport { RangeGridEditor } from \"./range-grid-editor\";\nimport {\n  emptySizingGrid,\n  sizingFromEditor,\n  TreeSizingEditor,\n  type NodeEdit,\n  type SizingBase,\n  type SizingGrid,\n} from \"./tree-sizing-editor\";\nimport { TreeVisualizationModal } from \"./tree-visualization-modal\";\nimport { MiniCard } from \"@/components/trainer/cards\";\n\n/** AI solve is disabled pending a solve path that's correct at all stack\n *  depths (#234: one-shot depth-limited solves produce phantom aggression at\n *  high SPR). Internal testing can re-enable with NEXT_PUBLIC_AI_SOLVE=1. */\nconst AI_SOLVE_ENABLED = process.env.NEXT_PUBLIC_AI_SOLVE === \"1\";\n\nconst DEFAULTS = {\n  board: \"Qs Jh 2h\",\n  pot: \"5.5\",\n  effective_stack: \"97\",\n  bet_sizes: CUSTOM_SOLVE_DEFAULTS.betSizes.join(\", \"),\n  max_aggressions: String(CUSTOM_SOLVE_DEFAULTS.maxAggressions),\n  river_bet_sizes: CUSTOM_SOLVE_DEFAULTS.riverBetSizes.join(\", \"),\n  river_max_aggressions: String(CUSTOM_SOLVE_DEFAULTS.riverMaxAggressions),\n  iterations: String(CUSTOM_SOLVE_DEFAULTS.iterations),\n  target_exploitability: String(CUSTOM_SOLVE_DEFAULTS.targetExploitability),\n};\n\nfunction parseNum(s: string, label: string): number {\n  const n = Number(s.trim());\n  if (!Number.isFinite(n)) throw new Error(`${label} must be a number`);\n  return n;\n}\n\nfunction parseSizes(s: string, label: string): number[] {\n  return s\n    .split(\",\")\n    .map((t) => t.trim())\n    .filter(Boolean)\n    .map((t, i) => parseNum(t, `${label} #${i + 1}`));\n}\n\nfunction Field({\n  label,\n  value,\n  onChange,\n  placeholder,\n  hint,\n}: {\n  label: string;\n  value: string;\n  onChange: (v: string) => void;\n  placeholder?: string;\n  hint?: string;\n}) {\n  return (\n    <label className=\"flex flex-col gap-1.5\">\n      <span className=\"text-xs font-medium text-muted-foreground\">{label}</span>\n      <input\n        value={value}\n        onChange={(e) => onChange(e.target.value)}\n        placeholder={placeholder}\n        spellCheck={false}\n        autoCapitalize=\"none\"\n        className=\"h-9 rounded-lg border border-input bg-card px-3 text-sm text-foreground outline-none transition-colors placeholder:text-muted-foreground/60 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40\"\n      />\n      {hint ? <span className=\"text-[11px] text-muted-foreground/70\">{hint}</span> : null}\n    </label>\n  );\n}\n\n/** The bet-tree / iteration knobs. Shown plainly in the full builder; tucked\n *  behind a disclosure in the inline (seeded) flow so the defaults just work. */\nfunction Advanced({\n  collapsible,\n  children,\n}: {\n  collapsible: boolean;\n  children: React.ReactNode;\n}) {\n  if (!collapsible) return <>{children}</>;\n  return (\n    <details className=\"group rounded-lg border border-border bg-card/40 p-3\">\n      <summary className=\"flex cursor-pointer list-none items-center justify-between text-xs font-medium text-muted-foreground\">\n        Solve settings\n        <span className=\"text-muted-foreground/60 transition-transform group-open:rotate-180\">▾</span>\n      </summary>\n      <div className=\"flex flex-col gap-4 pt-3\">{children}</div>\n    </details>\n  );\n}\n\n\n/** The slim summary the solve setup collapses into once solved — keeps the flop\n *  visible while the postflop navigator takes the stage, with a way back in. */\nfunction CollapsedSpot({\n  board,\n  sizing,\n  onEdit,\n}: {\n  board: string;\n  sizing: string;\n  onEdit: () => void;\n}) {\n  const cards = board.trim().split(/\\s+/).filter(Boolean);\n  return (\n    <div className=\"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-card/40 px-4 py-2.5\">\n      <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground\">\n        <span className=\"text-[10px] uppercase tracking-wide text-muted-foreground/70\">Flop</span>\n        <span className=\"inline-flex items-center gap-1 text-sm font-semibold tabular-nums\">\n          {cards.map((c, i) => (\n            <MiniCard key={i} card={c} className=\"h-6 w-[18px] text-[15px]\" />\n          ))}\n        </span>\n        {sizing ? (\n          <>\n            <span className=\"text-muted-foreground/70\">·</span>\n            <span>{sizing}</span>\n          </>\n        ) : null}\n      </div>\n      <button\n        type=\"button\"\n        onClick={onEdit}\n        className=\"shrink-0 rounded-md border border-border bg-card px-2.5 py-1 text-[11px] font-medium text-foreground transition-colors hover:bg-accent\"\n      >\n        Edit spot · re-solve\n      </button>\n    </div>\n  );\n}\n\n/** A preflop spot handed in from the Explorer: ranges, geometry, and the chosen\n *  board already fixed, so the builder can solve immediately. */\nexport interface BuilderSeed {\n  oopWeights: RangeWeights;\n  ipWeights: RangeWeights;\n  potBb: number;\n  effStackBb: number;\n  oopLabel: string;\n  ipLabel: string;\n  /** Flop (or turn/river) chosen in the picker, space-separated. */\n  board: string;\n  /** OOP called the last preflop raise instead of making it. Such a player has\n   *  effectively no donk range (our own solves put them at ~99% check), so the\n   *  flop lead is pruned by default — see `NO_FLOP_DONK_EDIT`. */\n  oopIsPreflopCaller?: boolean;\n}\n\nconst round1 = (n: number) => String(Math.round(n * 10) / 10);\n\n/**\n * The \"no flop donk\" preset: a node edit on the ROOT (OOP's first flop\n * decision) that offers neither a bet nor a shove, leaving Check as the only\n * action. Deliberately a node edit and not a street rule — a street-level\n * `oop_bet_sizes: []` also erases OOP's check-raise, because raise sizes\n * mirror the player's street bet sizes once those are set (see tree.rs\n * `root_override_removes_the_flop_donk_only`). Only meaningful on a 3-card\n * board, where the root IS the flop lead node.\n */\nconst NO_FLOP_DONK_EDIT: NodeEdit = { path: [], sizes: \"none\", allin: \"off\" };\n\n/** Stable empty grid for when the custom-tree toggle is off — a fresh object\n *  per render would loop the tree-preview's rebuild memo. */\nconst EMPTY_GRID = emptySizingGrid();\n\nconst isNoFlopDonkEdit = (e: NodeEdit) => e.path.length === 0 && e.sizes.trim() === \"none\";\n\nfunction formatElapsed(ms: number): string {\n  const s = Math.max(0, Math.floor(ms / 1000));\n  const m = Math.floor(s / 60);\n  return m > 0 ? `${m}m ${String(s % 60).padStart(2, \"0\")}s` : `${s}s`;\n}\n\nexport function Builder({\n  onSaved,\n  seed,\n  layout = \"page\",\n  stripPrefix,\n  stripLead,\n  onSolvedChange,\n  setupless = false,\n  autoSolve = false,\n  onRunningChange,\n  onSetupError,\n}: {\n  /** Called after a successful save with the summary + the full bundle, so the\n   *  caller can open it straight in the SolutionViewer. */\n  onSaved: (s: CustomSolutionSummary, bundle: CustomSolutionBundle) => void;\n  seed?: BuilderSeed;\n  /** \"drawer\"/\"inline\" stack inputs over output in a single column; \"inline\"\n   *  also collapses the advanced solve settings so the seeded flow stays lean. */\n  layout?: \"page\" | \"drawer\" | \"inline\";\n  /** (inline) Leading cards for the postflop navigator's strip — the preflop\n   *  seat cards, so preflop + postflop form one continuous action bar. */\n  stripPrefix?: ReactNode;\n  /** (inline) The game card, pinned left of the navigator's strip. */\n  stripLead?: ReactNode;\n  /** (inline) Fired when a result appears (true) or a solve (re)starts (false),\n   *  so the parent can hide its own seat strip while the navigator is up. */\n  onSolvedChange?: (solved: boolean) => void;\n  /** (inline) Never show the setup form up front — the Explorer's picker-drawer\n   *  flow already fixed the board, and the solve starts on its own. The full\n   *  form stays reachable post-solve via \"Edit spot · re-solve\". */\n  setupless?: boolean;\n  /** Kick the solve off on mount when the seeded board is complete. Held while\n   *  a previous session's solve is pending (Resume / Discard decides first). */\n  autoSolve?: boolean;\n  /** Mirrors the base solve's running state, so the parent can render the\n   *  acting card as a loading placeholder in its own strip. */\n  onRunningChange?: (running: boolean) => void;\n  /** The solve was refused before it was sent (empty range, bad input). The\n   *  running mirror never flips for these, so without this the parent's\n   *  loading card would spin forever. */\n  onSetupError?: (message: string) => void;\n}) {\n  const inline = layout === \"inline\";\n  const stacked = layout === \"drawer\" || inline;\n  // When seeded from a closed preflop spot, the board is the only thing left to\n  // choose, and the ranges/pot/stack come pre-filled.\n  const [board, setBoard] = useState(() => seed?.board ?? (seed ? \"\" : DEFAULTS.board));\n  const [pot, setPot] = useState(() => (seed ? round1(seed.potBb) : DEFAULTS.pot));\n  const [stack, setStack] = useState(() => (seed ? round1(seed.effStackBb) : DEFAULTS.effective_stack));\n  const [betSizes, setBetSizes] = useState(DEFAULTS.bet_sizes);\n  // All-in is off by default: the default tree (0.75 pot) rarely uses it at a\n  // meaningful frequency and it clutters every acting card with an \"AllIn 0%\"\n  // row. \"Always offer all-in\" in the solve settings turns it back on.\n  const [addAllin, setAddAllin] = useState(false);\n  const [maxAggr, setMaxAggr] = useState(DEFAULTS.max_aggressions);\n  const [riverBetSizes, setRiverBetSizes] = useState(DEFAULTS.river_bet_sizes);\n  const [riverMaxAggr, setRiverMaxAggr] = useState(DEFAULTS.river_max_aggressions);\n  // Per-street/per-player tree overrides (GTO-Wizard-style). The grid only\n  // ships with the request while the toggle is on, so switching it off\n  // restores the exact legacy geometry (and its warm-start compatibility).\n  const [customTree, setCustomTree] = useState(false);\n  const [sizingGrid, setSizingGrid] = useState<SizingGrid>(emptySizingGrid);\n  // Seeded with the no-flop-donk preset when the preflop line handed us an OOP\n  // caller: the donk is ~0% of a real solution, and pruning it off the root\n  // cuts the widest branch of the flop tree.\n  const [nodeEdits, setNodeEdits] = useState<NodeEdit[]>(() =>\n    seed?.oopIsPreflopCaller ? [NO_FLOP_DONK_EDIT] : [],\n  );\n  const [iterations, setIterations] = useState(DEFAULTS.iterations);\n  const [targetExp, setTargetExp] = useState(DEFAULTS.target_exploitability);\n  const [oopWeights, setOopWeights] = useState<RangeWeights>(() => (seed ? seed.oopWeights : fullRange()));\n  const [ipWeights, setIpWeights] = useState<RangeWeights>(() => (seed ? seed.ipWeights : fullRange()));\n  const [scenario, setScenario] = useState<ResolvedScenario | null>(null);\n\n  const [running, setRunning] = useState(false);\n  const [runningAi, setRunningAi] = useState(false);\n  const [queued, setQueued] = useState(false);\n  const [progress, setProgress] = useState<SolverProgress | null>(null);\n  const [startedAt, setStartedAt] = useState<number | null>(null);\n  const [elapsedMs, setElapsedMs] = useState(0);\n  const [result, setResult] = useState<SolverResult | null>(null);\n  const [solvedConfig, setSolvedConfig] = useState<SolveRequest | null>(null);\n  /** Last COMPLETED solve (job id + request) — the warm-start source (#262).\n   *  Locked what-if re-solves (#268) read it but NEVER update it: the\n   *  unlocked base stays the one warm-start source.\n   *\n   *  `cached` marks a solve the shared cache answered: correct strategy, but no\n   *  worker job behind it and therefore no snapshot, so a locked re-solve has to\n   *  re-run the base for real first. */\n  const lastSolveRef = useRef<{ jobId: string; request: SolveRequest; cached: boolean } | null>(\n    null,\n  );\n  const [labels, setLabels] = useState<{ oop: string; ip: string }>({ oop: \"OOP\", ip: \"IP\" });\n  const [error, setError] = useState<string | null>(null);\n  const handleRef = useRef<SolveHandle | null>(null);\n\n  // Locked what-if re-solve (#268) — kept fully apart from the base solve\n  // state so a what-if never contaminates the base result, the save panel, or\n  // the warm-start ref.\n  const [whatIf, setWhatIf] = useState<{ config: SolveRequest; result: SolverResult } | null>(\n    null,\n  );\n  const [lockBusy, setLockBusy] = useState(false);\n  const [lockProgress, setLockProgress] = useState<SolverProgress | null>(null);\n  const [lockError, setLockError] = useState<string | null>(null);\n  const lockHandleRef = useRef<SolveHandle | null>(null);\n\n  // A solve left running on the worker by an earlier session (tab reload).\n  // Lazy-read: the builder only mounts client-side (the drawer opens on user\n  // interaction), so localStorage is available and there's no hydration skew.\n  const [pending, setPending] = useState<PendingSolve | null>(() =>\n    typeof window === \"undefined\" ? null : readPendingSolve(),\n  );\n\n  // Save panel\n  const [title, setTitle] = useState(\"\");\n  const [tagsInput, setTagsInput] = useState(\"\");\n  const [saving, setSaving] = useState(false);\n  const [saveError, setSaveError] = useState<string | null>(null);\n\n  // Once solved, the inline flow collapses the setup form so the postflop\n  // navigator becomes the continuation; \"Edit spot\" reopens it.\n  const [editing, setEditing] = useState(false);\n\n  // Tree visualization + pruning modal (React Flow), opened before a solve.\n  const [treePreviewOpen, setTreePreviewOpen] = useState(false);\n\n  // Elapsed ticker while a solve runs.\n  useEffect(() => {\n    if (!running || startedAt === null) return;\n    const t = setInterval(() => setElapsedMs(Date.now() - startedAt), 1000);\n    return () => clearInterval(t);\n  }, [running, startedAt]);\n\n\n  const onScenarioResolved = (r: ResolvedScenario | null) => {\n    setScenario(r);\n    setOopWeights(r ? r.oop : fullRange());\n    setIpWeights(r ? r.ip : fullRange());\n  };\n\n  const boardCards = board.trim().split(/\\s+/).filter(Boolean).length;\n\n  // The root preset prunes a FLOP lead. On a turn/river start the root is that\n  // street's lead node instead, which we leave alone — so drop it there.\n  const forBoard = (edits: NodeEdit[]) =>\n    boardCards === 3 ? edits : edits.filter((e) => !isNoFlopDonkEdit(e));\n  const effectiveNodeEdits = useMemo(\n    () => (boardCards === 3 ? nodeEdits : nodeEdits.filter((e) => !isNoFlopDonkEdit(e))),\n    [nodeEdits, boardCards],\n  );\n  const noFlopDonk = nodeEdits.some(isNoFlopDonkEdit);\n  const setNoFlopDonk = (on: boolean) =>\n    setNodeEdits((prev) => {\n      const rest = prev.filter((e) => !isNoFlopDonkEdit(e));\n      // Appended last so an explicit root edit of the user's own still wins:\n      // the engine applies the FIRST override whose path matches.\n      return on ? [...rest, NO_FLOP_DONK_EDIT] : rest;\n    });\n\n  // Lenient view of the base fields for the tree-edit node preview (invalid\n  // text falls back to defaults; the strict parse happens on Solve).\n  const sizingBase = useMemo<SizingBase>(() => {\n    const nums = (s: string) =>\n      s\n        .split(\",\")\n        .map((t) => Number(t.trim()))\n        .filter((n) => Number.isFinite(n) && n > 0);\n    const bets = nums(betSizes);\n    const aggr = Math.floor(Number(maxAggr));\n    const riverAggr = Math.floor(Number(riverMaxAggr));\n    return {\n      betSizes: bets.length > 0 ? bets : [0.75],\n      riverBetSizes: nums(riverBetSizes),\n      addAllin,\n      maxAggressions: Number.isFinite(aggr) && aggr >= 0 ? aggr : 2,\n      riverMaxAggressions: Number.isFinite(riverAggr) && riverAggr >= 0 ? riverAggr : undefined,\n      potBb: Number(pot) > 0 ? Number(pot) : 1,\n      effStackBb: Number(stack) > 0 ? Number(stack) : 100,\n    };\n  }, [betSizes, riverBetSizes, addAllin, maxAggr, riverMaxAggr, pot, stack]);\n\n  /** Drive a handle (fresh or resumed) to completion and adopt its outcome. */\n  const drive = async (\n    handle: SolveHandle,\n    request: SolveRequest,\n    ctx: { oop: string; ip: string; title: string },\n  ): Promise<string | null> => {\n    handleRef.current = handle;\n    setRunning(true);\n    setQueued(true);\n    onSolvedChange?.(false);\n    try {\n      const outcome = await handle.promise;\n      setResult(outcome.result);\n      setSolvedConfig(request);\n      setLabels({ oop: ctx.oop, ip: ctx.ip });\n      setTitle(ctx.title);\n      clearPendingSolve();\n      setPending(null);\n      onSolvedChange?.(true);\n      // Remember the completed job for warm re-solves (#262): the worker kept\n      // its snapshot, so a same-geometry follow-up starts from this solution.\n      // A cache-served solve has no snapshot — recorded here so the locked\n      // re-solve path knows it must run the base for real first.\n      Promise.all([handle.jobId, handle.cached])\n        .then(([jobId, cached]) => {\n          lastSolveRef.current = { jobId, request, cached };\n        })\n        .catch(() => {});\n      return null;\n    } catch (e) {\n      const msg = e instanceof Error ? e.message : String(e);\n      setError(describeSolveError(msg));\n      // A job the worker no longer knows (restarted) can't be resumed — drop it.\n      if (/no such job/i.test(msg)) {\n        clearPendingSolve();\n        setPending(null);\n      }\n      return msg;\n    } finally {\n      setRunning(false);\n      setQueued(false);\n      handleRef.current = null;\n    }\n  };\n\n  const onSolve = async (ai: boolean, treeOverride?: { nodeEdits: NodeEdit[] }) => {\n    setError(null);\n    setResult(null);\n    setSolvedConfig(null);\n    setProgress(null);\n    setSaveError(null);\n    // A new base solve invalidates any locked what-if built on the old one.\n    lockHandleRef.current?.cancel().catch(() => {});\n    setWhatIf(null);\n    setLockError(null);\n    // Collapse the setup back down as the (re-)solve kicks off.\n    setEditing(false);\n\n    let request: SolveRequest;\n    try {\n      if (isEmptyRange(oopWeights)) throw new Error(\"OOP range is empty — pick a scenario or reset.\");\n      if (isEmptyRange(ipWeights)) throw new Error(\"IP range is empty — pick a scenario or reset.\");\n      const target = targetExp.trim() ? parseNum(targetExp, \"target exploitability\") : undefined;\n      const riverSizes = parseSizes(riverBetSizes, \"river bet size\");\n      request = buildPostflopSolveRequest({\n        board: board.trim(),\n        potBb: parseNum(pot, \"pot\"),\n        effStackBb: parseNum(stack, \"effective stack\"),\n        betSizes: parseSizes(betSizes, \"bet size\"),\n        addAllin,\n        maxAggressions: parseNum(maxAggr, \"max aggressions\"),\n        riverBetSizes: riverSizes.length > 0 ? riverSizes : undefined,\n        riverMaxAggressions: riverMaxAggr.trim()\n          ? parseNum(riverMaxAggr, \"river max aggressions\")\n          : undefined,\n        // Node edits always ship — an Edit Node from the viewer (#390) and the\n        // no-flop-donk preset are both explicit tree intent, independent of\n        // the \"customize tree\" toggle. The grid stays gated by that toggle, so\n        // switching it off still restores the legacy geometry. With neither,\n        // `sizingFromEditor` returns undefined and the request is unchanged.\n        sizing: sizingFromEditor(\n          customTree || treeOverride ? sizingGrid : EMPTY_GRID,\n          forBoard(treeOverride ? treeOverride.nodeEdits : nodeEdits),\n        ),\n        // AI solves converge on iteration budget alone — no target field.\n        iterations: ai ? CUSTOM_SOLVE_DEFAULTS.aiIterations : parseNum(iterations, \"iterations\"),\n        targetExploitability: ai ? undefined : target,\n        // Plateau stop only at study-grade targets. Deep spots decay\n        // ~1/iterations, so the default 1% target can be unreachable — the\n        // plateau ends the solve once converged instead of grinding to the\n        // cap. But a user who TYPES a tighter target (< 1%) is explicitly\n        // buying precision; the plateau would silently cap them near ~1.2%\n        // regardless, so high-precision runs let the target/cap govern.\n        convergencePlateau:\n          ai || (target !== undefined && target < CUSTOM_SOLVE_DEFAULTS.targetExploitability)\n            ? undefined\n            : CUSTOM_SOLVE_DEFAULTS.convergencePlateau,\n        oopRange: weightsToEngineString(oopWeights),\n        ipRange: weightsToEngineString(ipWeights),\n        aiSolve: ai,\n      });\n    } catch (e) {\n      const msg = e instanceof Error ? e.message : \"invalid input\";\n      setError(msg);\n      onSetupError?.(msg);\n      return;\n    }\n\n    // Warm re-solve (#262): if the tree geometry is unchanged since the last\n    // completed solve (only convergence knobs tweaked), start from its\n    // snapshot — seconds instead of minutes. The engine fingerprint verifies\n    // server-side; the client-side check just avoids sending doomed requests.\n    const last = lastSolveRef.current;\n    if (!ai && last && sameSolveGeometry(request, last.request)) {\n      request.warm_start_from = last.jobId;\n    }\n\n    const oop = seed ? seed.oopLabel : scenario ? scenario.oopPos : \"OOP\";\n    const ip = seed ? seed.ipLabel : scenario ? scenario.ipPos : \"IP\";\n    const suggestedTitle = `${oop} vs ${ip} · ${request.board}`;\n\n    const launch = async (req: SolveRequest): Promise<string | null> => {\n      const t0 = Date.now();\n      setStartedAt(t0);\n      setElapsedMs(0);\n      setRunningAi(ai);\n      const handle = startSolve(req, (p) => {\n        setQueued(false);\n        setProgress(p);\n      });\n      // Record the job for resume as soon as the worker accepts it — the solve\n      // runs server-side, so a closed tab doesn't lose it.\n      handle.jobId\n        .then((jobId) =>\n          writePendingSolve({\n            jobId,\n            request: req,\n            startedAt: t0,\n            oopLabel: oop,\n            ipLabel: ip,\n            title: suggestedTitle,\n            ai,\n          }),\n        )\n        .catch(() => {});\n      return drive(handle, req, { oop, ip, title: suggestedTitle });\n    };\n\n    const err = await launch(request);\n    // Snapshot evicted / worker restarted / fingerprint mismatch: fall back\n    // to a cold solve automatically rather than surfacing a warm-start error.\n    if (err && request.warm_start_from && /snapshot|warm/i.test(err)) {\n      lastSolveRef.current = null;\n      const { warm_start_from: _dropped, ...cold } = request;\n      setError(null);\n      await launch(cold as SolveRequest);\n    }\n  };\n\n  // Mirror the running flag out to the parent (strip loading card).\n  useEffect(() => {\n    onRunningChange?.(running);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [running]);\n\n  // Auto-solve (Explorer picker flow): the drawer fixed the board, so the\n  // solve starts the moment this mounts. Deferred while a previous session's\n  // job is pending — Resume/Discard decides — and never re-fired after a\n  // cancel or failure (the parent's retry card remounts us with a fresh key).\n  const autoStarted = useRef(false);\n  useEffect(() => {\n    if (!autoSolve || autoStarted.current) return;\n    if (pending || running || result) return;\n    if (boardCards < 3) return;\n    autoStarted.current = true;\n    void onSolve(false);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [autoSolve, pending]);\n\n  const onResume = async (p: PendingSolve) => {\n    setError(null);\n    setResult(null);\n    setSolvedConfig(null);\n    setProgress(null);\n    setSaveError(null);\n    setStartedAt(p.startedAt);\n    setElapsedMs(Date.now() - p.startedAt);\n    setRunningAi(Boolean(p.ai));\n    const handle = resumeSolve(p.jobId, (tick) => {\n      setQueued(false);\n      setProgress(tick);\n    });\n    await drive(handle, p.request, { oop: p.oopLabel, ip: p.ipLabel, title: p.title });\n  };\n\n  const onDiscardPending = () => {\n    // Best-effort cancel so an abandoned flop solve frees its worker slot.\n    if (pending) resumeSolve(pending.jobId).cancel().catch(() => {});\n    clearPendingSolve();\n    setPending(null);\n  };\n\n  const onCancel = () => {\n    handleRef.current?.cancel().catch(() => {});\n  };\n\n  /**\n   * \"Re-solve with edits\" (#268): the base config + `locked_nodes` +\n   * `warm_start_from` the base job. The warm start is REQUIRED, not an\n   * optimization — a cold locked solve can never train the response behind a\n   * zeroed action (PR #269), so when no base snapshot exists we error out\n   * instead of falling back to cold (unlike the base solve's fallback).\n   *\n   * When the base was served from the shared solve cache there is no worker job\n   * to warm-start from, so the base is re-run on the worker (`noCache`) first.\n   * That's slow — it's the solve the cache just saved — but it's the only honest\n   * way to edit nodes, and it happens once per cached spot the user edits.\n   */\n  const onLockedResolve = async (locks: LockedNode[]) => {\n    if (!solvedConfig || lockBusy) return;\n    setLockError(null);\n    let last = lastSolveRef.current;\n    if (!last || !sameSolveGeometry(solvedConfig, last.request)) {\n      setLockError(\n        \"No warm-start snapshot for this spot — run the base solve first. Locked re-solves always start from the unlocked solution (a cold locked solve reads wrong wherever an action is locked to 0%).\",\n      );\n      return;\n    }\n\n    if (last.cached) {\n      setLockBusy(true);\n      setLockProgress(null);\n      const baseRequest: SolveRequest = { ...last.request, noCache: true };\n      const baseHandle = startSolve(baseRequest, (p) => setLockProgress(p));\n      lockHandleRef.current = baseHandle;\n      try {\n        await baseHandle.promise;\n        const jobId = await baseHandle.jobId;\n        last = { jobId, request: baseRequest, cached: false };\n        lastSolveRef.current = last;\n      } catch (e) {\n        setLockError(\n          `Couldn't re-run the base solve needed to edit nodes: ${describeSolveError(\n            e instanceof Error ? e.message : String(e),\n          )}`,\n        );\n        setLockBusy(false);\n        setLockProgress(null);\n        lockHandleRef.current = null;\n        return;\n      }\n    }\n\n    let request: SolveRequest;\n    try {\n      request = buildLockedResolveRequest(solvedConfig, locks, last.jobId);\n    } catch (e) {\n      setLockError(e instanceof Error ? e.message : String(e));\n      setLockBusy(false);\n      setLockProgress(null);\n      lockHandleRef.current = null;\n      return;\n    }\n    setLockBusy(true);\n    setLockProgress(null);\n    const handle = startSolve(request, (p) => setLockProgress(p));\n    lockHandleRef.current = handle;\n    try {\n      const outcome = await handle.promise;\n      // A cancelled what-if is abandoned (unlike base solves, where the\n      // partial strategy is worth keeping — a what-if is cheap to redo warm).\n      if (!outcome.cancelled) setWhatIf({ config: request, result: outcome.result });\n    } catch (e) {\n      const msg = e instanceof Error ? e.message : String(e);\n      setLockError(\n        isWarmStartFailure(msg)\n          ? \"The base solve's snapshot is no longer on the worker — run the base solve again, then re-apply your edits. (Locked re-solves never run cold: the response behind a zeroed action would stay untrained and silently wrong.)\"\n          : describeSolveError(msg),\n      );\n    } finally {\n      setLockBusy(false);\n      setLockProgress(null);\n      lockHandleRef.current = null;\n    }\n  };\n\n  /**\n   * Structural \"Edit Node\" from the viewer (#390): merge the node's new action\n   * set into `nodeEdits` and re-solve the whole tree. Always a cold solve — a\n   * changed action set is a different geometry, so no warm start.\n   */\n  const onNodeEditApply = (path: string[], sizes: number[], allin: boolean) => {\n    const sizesText =\n      sizes.length === 0\n        ? \"none\"\n        : sizes.map((f) => String(Math.round(f * 1000) / 1000)).join(\", \");\n    const next: NodeEdit = { path, sizes: sizesText, allin: allin ? \"on\" : \"off\" };\n    const merged = [...nodeEdits.filter((e) => e.path.join(\" \") !== path.join(\" \")), next];\n    setNodeEdits(merged);\n    setCustomTree(true);\n    void onSolve(false, { nodeEdits: merged });\n  };\n\n  const onNodeEditsClearAll = () => {\n    setNodeEdits([]);\n    void onSolve(false, { nodeEdits: [] });\n  };\n\n  const onCancelLockedResolve = () => {\n    lockHandleRef.current?.cancel().catch(() => {});\n  };\n\n  const onSave = async () => {\n    if (!result || !solvedConfig) return;\n    setSaving(true);\n    setSaveError(null);\n    try {\n      const meta: CustomSolutionMeta = {\n        potBb: solvedConfig.pot,\n        effStackBb: solvedConfig.effective_stack,\n        betSizing: betSizingLabel(solvedConfig),\n        oopLabel: labels.oop,\n        ipLabel: labels.ip,\n        startStreet: streetForBoard(solvedConfig.board),\n        ai: solvedConfig.aiSolve === true,\n      };\n      const tags = tagsInput\n        .split(\",\")\n        .map((t) => t.trim())\n        .filter(Boolean);\n      const solutionsApi = explorerHost().solutions;\n      if (!solutionsApi) throw new Error(\"Saving solutions isn't available here.\");\n      const res = await fetch(solutionsApi, {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: JSON.stringify({ title: title.trim(), tags, config: solvedConfig, result, meta }),\n      });\n      if (!res.ok) {\n        const body = (await res.json().catch(() => ({}))) as { error?: string };\n        throw new Error(body.error ?? `save failed (${res.status})`);\n      }\n      const { solution } = (await res.json()) as { solution: CustomSolutionSummary };\n      onSaved(solution, {\n        id: solution.id,\n        title: solution.title,\n        tags: solution.tags,\n        board: solvedConfig.board,\n        meta,\n        config: solvedConfig,\n        result,\n        generatedAt: solution.createdAt,\n      });\n    } catch (e) {\n      setSaveError(e instanceof Error ? e.message : String(e));\n    } finally {\n      setSaving(false);\n    }\n  };\n\n  // Ephemeral bundle so the fresh result previews in the real viewer (the same\n  // component saved solutions open in), on-demand river solves included.\n  const previewBundle = useMemo<CustomSolutionBundle | null>(() => {\n    if (!result || !solvedConfig) return null;\n    return {\n      id: \"preview\",\n      title: title.trim() || \"Custom solve\",\n      tags: [],\n      board: solvedConfig.board,\n      meta: {\n        potBb: solvedConfig.pot,\n        effStackBb: solvedConfig.effective_stack,\n        betSizing: betSizingLabel(solvedConfig),\n        oopLabel: labels.oop,\n        ipLabel: labels.ip,\n        startStreet: streetForBoard(solvedConfig.board),\n        ai: solvedConfig.aiSolve === true,\n      },\n      config: solvedConfig,\n      result,\n      generatedAt: new Date().toISOString(),\n    };\n    // Title is intentionally omitted: retyping the save title shouldn't remount\n    // the viewer (and reset its navigation) on every keystroke.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [result, solvedConfig, labels]);\n\n  // The locked what-if bundle (#268): same viewer, clearly labelled, NOT\n  // saveable in v1 (the save panel is hidden while it's shown).\n  const whatIfBundle = useMemo<CustomSolutionBundle | null>(() => {\n    if (!whatIf) return null;\n    return {\n      id: \"locked-what-if\",\n      title: `${title.trim() || \"Custom solve\"} · locked what-if`,\n      tags: [],\n      board: whatIf.config.board,\n      meta: {\n        potBb: whatIf.config.pot,\n        effStackBb: whatIf.config.effective_stack,\n        betSizing: betSizingLabel(whatIf.config),\n        oopLabel: labels.oop,\n        ipLabel: labels.ip,\n        startStreet: streetForBoard(whatIf.config.board),\n      },\n      config: whatIf.config,\n      result: whatIf.result,\n      generatedAt: new Date().toISOString(),\n    };\n    // Title omitted for the same reason as previewBundle.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [whatIf, labels]);\n\n  const solved = Boolean(result && solvedConfig);\n  // Inline: hide the setup form once solved so the navigator is the continuation.\n  // Setupless (Explorer picker flow): the form only ever appears via \"Edit spot\".\n  const showSetup = setupless ? editing : !inline || !solved || editing;\n\n  // A leftover job from a previous session. Normally shown inside the setup\n  // form; with the form hidden it renders standalone so Resume/Discard stays\n  // reachable (auto-solve waits on this decision).\n  const pendingBanner =\n    pending && !running && !result ? (\n      <div className=\"flex flex-col gap-2 rounded-lg border border-border bg-card/60 p-3\">\n        <span className=\"text-xs font-medium text-foreground\">\n          A solve from a previous session is still on the server\n        </span>\n        <span className=\"text-[11px] text-muted-foreground\">\n          {pending.title} · started {formatElapsed(Date.now() - pending.startedAt)} ago.\n          Jobs keep running server-side — re-attach to see progress and the result.\n        </span>\n        <div className=\"flex gap-2\">\n          <Button size=\"sm\" onClick={() => onResume(pending)}>\n            <Play className=\"size-3.5\" /> Resume\n          </Button>\n          <Button size=\"sm\" variant=\"outline\" onClick={onDiscardPending}>\n            Discard\n          </Button>\n        </div>\n      </div>\n    ) : null;\n\n  // The two post-solve blocks, ordered differently inline (viewer flows first,\n  // straight off the preflop strip) vs. standalone (save panel on top).\n  const resultBlocks =\n    result && solvedConfig ? (\n      {\n        // Locked what-ifs are not saveable in v1 — the save panel yields to\n        // the what-if banner while one is on screen.\n        save: whatIf ? null : (\n          <div className=\"flex flex-col gap-3 rounded-xl border border-border bg-card/40 p-4\">\n            <div className=\"flex flex-col gap-1\">\n              <span className=\"text-sm font-medium text-foreground\">Save this solution</span>\n              <span className=\"text-xs text-muted-foreground\">\n                {solvedConfig.aiSolve\n                  ? \"AI solve (exploitability not measurable)\"\n                  : `Exploitability ${result.exploitability.percent.toFixed(3)}%`}{\" \"}\n                · {result.iterations_run} iters · {result.elapsed_seconds.toFixed(1)}s\n              </span>\n            </div>\n            <Field label=\"Title\" value={title} onChange={setTitle} placeholder=\"e.g. BTN vs CO 3-bet · QJ2\" />\n            <Field\n              label=\"Tags (comma-separated)\"\n              value={tagsInput}\n              onChange={setTagsInput}\n              placeholder=\"3bet-pot, BTN-vs-CO, two-tone\"\n            />\n            {saveError ? <p className=\"text-xs text-destructive\">{saveError}</p> : null}\n            <Button onClick={onSave} disabled={saving || !title.trim()} className=\"self-start\">\n              {saving ? (\n                <>\n                  <Loader2 className=\"size-4 animate-spin\" /> Saving…\n                </>\n              ) : (\n                <>\n                  <Save className=\"size-4\" /> Save &amp; open in viewer\n                </>\n              )}\n            </Button>\n          </div>\n        ),\n        viewer: (\n          <div\n            className={\n              inline\n                ? \"flex flex-col gap-3\"\n                : \"flex flex-col gap-3 rounded-xl border border-border bg-card/20 p-4\"\n            }\n          >\n            {lockError ? (\n              <div className=\"rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-2.5 text-sm text-destructive\">\n                {lockError}\n              </div>\n            ) : null}\n            {lockBusy ? (\n              <div className=\"flex items-center gap-3 rounded-lg border border-amber-500/40 bg-amber-500/[0.06] px-4 py-2.5 text-sm text-muted-foreground\">\n                <Loader2 className=\"size-4 shrink-0 animate-spin\" />\n                <span className=\"tabular-nums\">\n                  Re-solving with your locked edits (warm start — usually seconds)…{\" \"}\n                  {lockProgress\n                    ? `iter ${lockProgress.iter} · expl ${lockProgress.percent.toFixed(2)}%`\n                    : \"starting\"}\n                </span>\n                <button\n                  type=\"button\"\n                  onClick={onCancelLockedResolve}\n                  aria-label=\"Cancel locked re-solve\"\n                  className=\"ml-auto rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                >\n                  <X className=\"size-4\" />\n                </button>\n              </div>\n            ) : null}\n            {whatIf && whatIfBundle ? (\n              <>\n                <div className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/[0.06] px-4 py-2.5 text-sm\">\n                  <Lock className=\"size-4 shrink-0 text-amber-400\" />\n                  <span className=\"text-foreground\">\n                    Locked what-if — {whatIf.config.locked_nodes?.length ?? 0} node\n                    {(whatIf.config.locked_nodes?.length ?? 0) === 1 ? \"\" : \"s\"} play your\n                    edits verbatim; the rest of the tree re-equilibrated against them.\n                  </span>\n                  <span className=\"text-xs text-muted-foreground tabular-nums\">\n                    composed expl {whatIf.result.exploitability.percent.toFixed(2)}% (the lock\n                    sets the floor)\n                  </span>\n                  <button\n                    type=\"button\"\n                    onClick={() => setWhatIf(null)}\n                    className=\"ml-auto shrink-0 rounded-md border border-border bg-card px-2.5 py-1 text-[11px] font-medium text-foreground transition-colors hover:bg-accent\"\n                  >\n                    Back to base solution\n                  </button>\n                </div>\n                <SolutionViewer key=\"what-if\" bundle={whatIfBundle} embedded={inline} stripPrefix={stripPrefix} stripLead={stripLead} />\n              </>\n            ) : previewBundle && result.nodes && result.nodes.length > 0 ? (\n              <SolutionViewer\n                key=\"base\"\n                bundle={previewBundle}\n                embedded={inline}\n                stripPrefix={stripPrefix}\n                stripLead={stripLead}\n                // Node locking (#268) needs the base job's snapshot to warm-start\n                // from; AI solves never snapshot, so they can't be edited.\n                locking={\n                  !solvedConfig.aiSolve\n                    ? { onResolve: onLockedResolve, busy: lockBusy }\n                    : undefined\n                }\n                // Structural Edit Node (#390) — full cold re-solve on confirm.\n                nodeEditing={\n                  !solvedConfig.aiSolve\n                    ? {\n                        onApply: onNodeEditApply,\n                        onClearAll: onNodeEditsClearAll,\n                        editedKeys: nodeEdits.map((e) => e.path.join(\" \")),\n                        busy: running,\n                      }\n                    : undefined\n                }\n              />\n            ) : (\n              <p className=\"text-sm text-muted-foreground\">\n                The solve returned no node tree to walk — try a smaller spot.\n              </p>\n            )}\n          </div>\n        ),\n      }\n    ) : null;\n\n  return (\n    <div\n      className={\n        stacked\n          ? \"flex flex-col gap-6\"\n          : \"grid gap-6 lg:grid-cols-[minmax(0,360px)_minmax(0,1fr)]\"\n      }\n    >\n      {/* ---- Inputs ---- */}\n      {showSetup ? (\n      <div className=\"flex flex-col gap-4 rounded-xl border border-border bg-card/40 p-4\">\n        {pendingBanner}\n\n        {seed ? (\n          <div className=\"flex flex-col gap-2\">\n            <span className=\"text-xs font-medium text-muted-foreground\">Flop / board</span>\n            <CardGridPicker\n              value={board.trim().split(/\\s+/).filter(Boolean)}\n              onChange={(next) => setBoard(next.join(\" \"))}\n            />\n            <span className=\"text-[11px] text-muted-foreground/70\">\n              3 / 4 / 5 cards → flop / turn / river\n            </span>\n          </div>\n        ) : (\n          <Field\n            label=\"Board\"\n            value={board}\n            onChange={setBoard}\n            placeholder=\"Qs Jh 2h\"\n            hint=\"3 / 4 / 5 cards → flop / turn / river\"\n          />\n        )}\n        <div className=\"grid grid-cols-2 gap-3\">\n          <Field label=\"Pot (bb)\" value={pot} onChange={setPot} />\n          <Field label=\"Eff. stack (bb)\" value={stack} onChange={setStack} />\n        </div>\n        <Advanced collapsible={inline}>\n          <Field\n            label=\"Bet sizes (× pot)\"\n            value={betSizes}\n            onChange={setBetSizes}\n            placeholder=\"0.5, 0.75, 1\"\n          />\n          <label className=\"flex items-center justify-between gap-2\">\n            <span className=\"text-xs font-medium text-muted-foreground\">Always offer all-in</span>\n            <input\n              type=\"checkbox\"\n              checked={addAllin}\n              onChange={(e) => setAddAllin(e.target.checked)}\n              className=\"size-4 accent-primary\"\n            />\n          </label>\n          <div className=\"grid grid-cols-2 gap-3\">\n            <Field label=\"Max aggressions\" value={maxAggr} onChange={setMaxAggr} />\n            <Field label=\"Iterations\" value={iterations} onChange={setIterations} />\n          </div>\n          <div className=\"grid grid-cols-2 gap-3\">\n            <Field\n              label=\"River bet sizes (× pot)\"\n              value={riverBetSizes}\n              onChange={setRiverBetSizes}\n              placeholder=\"0.75\"\n            />\n            <Field label=\"River max aggr.\" value={riverMaxAggr} onChange={setRiverMaxAggr} />\n          </div>\n          <span className=\"-mt-2 text-[11px] text-muted-foreground/70\">\n            A coarser river-only abstraction keeps full flop trees solvable. Leave river\n            sizes empty to reuse the main sizes.\n          </span>\n          <label className=\"flex items-center justify-between gap-2\">\n            <span className=\"flex flex-col\">\n              <span className=\"text-xs font-medium text-foreground\">No flop donk</span>\n              <span className=\"text-[11px] text-muted-foreground/70\">\n                OOP can only check the flop. The preflop caller donks at ~0% anyway,\n                so dropping the lead narrows the tree and speeds the solve up. Their\n                check-raise and later-street leads are untouched.\n              </span>\n            </span>\n            <input\n              type=\"checkbox\"\n              checked={noFlopDonk}\n              disabled={boardCards !== 3}\n              onChange={(e) => setNoFlopDonk(e.target.checked)}\n              className=\"size-4 accent-primary disabled:opacity-40\"\n            />\n          </label>\n          <div className=\"flex flex-col gap-3 rounded-lg border border-border bg-card/60 p-3\">\n            <label className=\"flex items-center justify-between gap-2\">\n              <span className=\"flex flex-col\">\n                <span className=\"text-xs font-medium text-foreground\">Tree edit</span>\n                <span className=\"text-[11px] text-muted-foreground/70\">\n                  See every betting node the solve will offer and edit OOP / IP sizes per\n                  street, GTO-Wizard style.\n                </span>\n              </span>\n              <input\n                type=\"checkbox\"\n                checked={customTree}\n                onChange={(e) => setCustomTree(e.target.checked)}\n                className=\"size-4 accent-primary\"\n              />\n            </label>\n            {customTree ? (\n              <TreeSizingEditor\n                grid={sizingGrid}\n                onChange={setSizingGrid}\n                nodeEdits={effectiveNodeEdits}\n                onNodeEditsChange={setNodeEdits}\n                boardCards={boardCards}\n                base={sizingBase}\n              />\n            ) : null}\n          </div>\n          <Field\n            label=\"Target expl. % (optional)\"\n            value={targetExp}\n            onChange={setTargetExp}\n            placeholder=\"e.g. 0.5\"\n            hint=\"Stop early once exploitability drops below this. 1% is study grade (charts are visually converged); type 0.5 for high precision — slower, and deep spots may run to the iteration cap. Solves also end on their own when improvement stalls.\"\n          />\n        </Advanced>\n        <div className=\"border-t border-border pt-4\">\n          {seed ? (\n            <div className=\"flex flex-col gap-2\">\n              <span className=\"text-xs font-medium text-muted-foreground\">\n                Ranges — seeded from the preflop line, click or drag to edit\n              </span>\n              <div className=\"grid gap-2 sm:grid-cols-2\">\n                <RangeGridEditor\n                  pos={seed.oopLabel}\n                  role=\"oop\"\n                  weights={oopWeights}\n                  onChange={setOopWeights}\n                  seed={seed.oopWeights}\n                />\n                <RangeGridEditor\n                  pos={seed.ipLabel}\n                  role=\"ip\"\n                  weights={ipWeights}\n                  onChange={setIpWeights}\n                  seed={seed.ipWeights}\n                />\n              </div>\n            </div>\n          ) : (\n            <ScenarioStrip onResolved={onScenarioResolved} />\n          )}\n        </div>\n\n        {boardCards === 3 ? (\n          <div className=\"rounded-lg border border-border bg-card/60 px-3 py-2 text-[11px] text-muted-foreground\">\n            Full flop solution: every turn subtree is solved and dumped; river runouts\n            open on demand in the viewer. Expect ~3–8 minutes (deep stacks trend higher;\n            the solve ends early once it converges) — it runs on the server, so you can\n            close this tab and resume from here later.\n            {Number(maxAggr) > 2 || betSizes.split(\",\").filter((s) => s.trim()).length > 1 ? (\n              <span className=\"mt-1 block\">\n                Heads-up: extra sizes or more than 2 aggressions on a flop start can make\n                the strategy dump too large to load back — keep the tree small.\n              </span>\n            ) : null}\n          </div>\n        ) : null}\n\n        <div className=\"flex flex-col gap-2\">\n          <div className=\"flex gap-2\">\n            {/* AI solve is gated off (#234): the one-shot depth-limited path\n                produces distorted flop strategies at high SPR (e.g. phantom\n                donk ranges vs a ~100% exact check). Re-enable via the env flag\n                only for internal testing until the solve path is corrected. */}\n            {boardCards === 3 && AI_SOLVE_ENABLED ? (\n              <>\n                <Button onClick={() => onSolve(true)} disabled={running} className=\"flex-1\">\n                  {running && runningAi ? (\n                    <>\n                      <Loader2 className=\"size-4 animate-spin\" /> Solving…\n                    </>\n                  ) : (\n                    <>\n                      <Sparkles className=\"size-4\" /> AI solve\n                    </>\n                  )}\n                </Button>\n                <Button\n                  variant=\"outline\"\n                  onClick={() => onSolve(false)}\n                  disabled={running}\n                  className=\"flex-1\"\n                >\n                  {running && !runningAi ? (\n                    <>\n                      <Loader2 className=\"size-4 animate-spin\" /> Solving…\n                    </>\n                  ) : (\n                    \"Exact solve\"\n                  )}\n                </Button>\n              </>\n            ) : (\n              <Button onClick={() => onSolve(false)} disabled={running || boardCards < 3} className=\"flex-1\">\n                {running ? (\n                  <>\n                    <Loader2 className=\"size-4 animate-spin\" /> Solving…\n                  </>\n                ) : boardCards < 3 ? (\n                  \"Pick a flop to solve\"\n                ) : (\n                  \"Solve\"\n                )}\n              </Button>\n            )}\n            {boardCards === 3 && !running ? (\n              <Button\n                variant=\"outline\"\n                onClick={() => setTreePreviewOpen(true)}\n                title=\"Visualize game tree and prune branches before solving\"\n              >\n                <Eye className=\"size-4\" /> Preview tree\n              </Button>\n            ) : null}\n            {running ? (\n              <Button variant=\"outline\" onClick={onCancel}>\n                Cancel\n              </Button>\n            ) : null}\n          </div>\n          {boardCards === 3 && AI_SOLVE_ENABLED ? (\n            <span className=\"text-[11px] text-muted-foreground/70\">\n              AI solve: seconds–minutes (beta), AI-assisted accuracy ~1–2% of pot vs 0.5%\n              exact. Turn cards open via fast exact re-solves in the viewer.\n            </span>\n          ) : null}\n        </div>\n      </div>\n      ) : null}\n\n      {/* ---- Output ---- */}\n      <div className=\"flex flex-col gap-4\">\n        {!showSetup ? pendingBanner : null}\n        {error ? (\n          <div className=\"rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive\">\n            {error}\n          </div>\n        ) : null}\n\n        {running ? (\n          <div className=\"flex flex-col gap-2 rounded-lg border border-border bg-card/40 px-4 py-3\">\n            <div className=\"flex items-center justify-between gap-3 text-sm text-muted-foreground tabular-nums\">\n              {queued && !progress ? (\n                <span className=\"flex items-center gap-2\">\n                  <Loader2 className=\"size-4 animate-spin\" />\n                  Waiting for a solver slot (the worker runs 2 solves at a time)…\n                </span>\n              ) : progress ? (\n                <span>\n                  {/* AI solves run a fixed iteration budget, and exploitability\n                      isn't computable in the depth-limited game — show honest\n                      progress instead of a meaningless 0.000%. */}\n                  {runningAi\n                    ? `iter ${progress.iter} / ${CUSTOM_SOLVE_DEFAULTS.aiIterations}`\n                    : `iter ${progress.iter} · expl ${progress.percent.toFixed(3)}%`}{\" \"}\n                  · {formatElapsed(elapsedMs)} elapsed\n                </span>\n              ) : (\n                <span>Starting solve…</span>\n              )}\n              <span className=\"flex shrink-0 items-center gap-2\">\n                <span className=\"text-[11px] text-muted-foreground/70\">\n                  {solveEtaHint(boardCards, runningAi)}\n                </span>\n                {/* With the setup form hidden (picker flow) this is the only\n                    cancel affordance. */}\n                {!showSetup ? (\n                  <button\n                    type=\"button\"\n                    onClick={onCancel}\n                    aria-label=\"Cancel solve\"\n                    className=\"rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                  >\n                    <X className=\"size-4\" />\n                  </button>\n                ) : null}\n              </span>\n            </div>\n            <span className=\"text-[11px] text-muted-foreground/70\">\n              Runs server-side — closing this tab won&apos;t stop it; reopen the builder to\n              resume.\n            </span>\n          </div>\n        ) : null}\n\n        {resultBlocks ? (\n          inline ? (\n            // Inline: the postflop navigator flows straight off the preflop\n            // strip; the collapsed spot + save panel sit below it.\n            <>\n              {resultBlocks.viewer}\n              {!editing ? (\n                <CollapsedSpot\n                  board={solvedConfig?.board ?? board}\n                  sizing={solvedConfig ? betSizingLabel(solvedConfig) : \"\"}\n                  onEdit={() => setEditing(true)}\n                />\n              ) : null}\n              {resultBlocks.save}\n            </>\n          ) : (\n            <>\n              {resultBlocks.save}\n              {resultBlocks.viewer}\n            </>\n          )\n        ) : !running ? (\n          <div className=\"flex min-h-[200px] items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground\">\n            Set up a postflop spot and hit Solve. The full strategy tree is solved,\n            then you can name, tag, and save it.\n          </div>\n        ) : null}\n      </div>\n\n      {/* Tree visualization + pruning modal (React Flow, editable nodes).\n          Node edits made in the flow land in the SAME nodeEdits state the\n          Tree-edit strip uses, and node edits always ship with the solve. */}\n      {treePreviewOpen ? (\n        <TreeVisualizationModal\n          open={treePreviewOpen}\n          onOpenChange={setTreePreviewOpen}\n          grid={customTree ? sizingGrid : EMPTY_GRID}\n          base={sizingBase}\n          boardCards={boardCards}\n          nodeEdits={effectiveNodeEdits}\n          onNodeEditsChange={setNodeEdits}\n          result={result}\n          onSolve={() => {\n            setTreePreviewOpen(false);\n            onSolve(false);\n          }}\n          isSolving={running}\n        />\n      ) : null}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/builder.tsx"
    },
    {
      "path": "src/components/explorer/card-picker.tsx",
      "content": "\"use client\";\n\n// A GTO-Wizard-style card grid for choosing a board: four suit rows × thirteen\n// ranks. Click to add a card; click a used (highlighted) card to remove it.\n// Used to select a flop (and optionally a turn/river) when a closed preflop\n// line goes postflop.\n\nimport { Trash2 } from \"lucide-react\";\nimport { MiniCard } from \"@/components/trainer/cards\";\nimport { suitTile } from \"@/components/trainer/theme\";\n\nconst RANKS = [\"A\", \"K\", \"Q\", \"J\", \"T\", \"9\", \"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\"];\nconst SUITS = [\"s\", \"h\", \"d\", \"c\"] as const;\n\n// Suit rows use the table's four-color deck (`suitTile`), like every other card.\nconst SUIT_GLYPH: Record<string, string> = { s: \"♠\", h: \"♥\", d: \"♦\", c: \"♣\" };\n\nexport function CardGridPicker({\n  value,\n  onChange,\n  max = 5,\n  dead = [],\n}: {\n  value: string[];\n  onChange: (next: string[]) => void;\n  max?: number;\n  /** Cards already on the board, shown but not pickable. */\n  dead?: string[];\n}) {\n  const toggle = (card: string) => {\n    if (value.includes(card)) onChange(value.filter((c) => c !== card));\n    else if (value.length < max) onChange([...value, card]);\n  };\n\n  return (\n    <div className=\"flex w-full max-w-[460px] flex-col gap-3\">\n      {/* Selected board */}\n      <div className=\"flex items-center gap-2\">\n        <div className=\"flex min-h-[30px] flex-1 flex-wrap items-center gap-1\">\n          {value.length === 0 ? (\n            <span className=\"text-xs text-muted-foreground\">Pick a flop (3 cards)…</span>\n          ) : (\n            value.map((c, i) => (\n              <MiniCard key={i} card={c} className=\"h-8 w-6 text-xl\" />\n            ))\n          )}\n        </div>\n        {value.length > 0 ? (\n          <button\n            type=\"button\"\n            onClick={() => onChange([])}\n            aria-label=\"Clear board\"\n            className=\"rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n          >\n            <Trash2 className=\"size-4\" />\n          </button>\n        ) : null}\n      </div>\n\n      {/* Suit rows */}\n      <div className=\"flex flex-col gap-1\">\n        {SUITS.map((suit) => (\n          <div\n            key={suit}\n            className=\"grid grid-cols-[repeat(13,minmax(0,1fr))] gap-1\"\n          >\n            {RANKS.map((rank) => {\n              const card = `${rank}${suit}`;\n              const used = value.includes(card);\n              const disabled = dead.includes(card) || (!used && value.length >= max);\n              return (\n                <button\n                  key={card}\n                  type=\"button\"\n                  disabled={disabled}\n                  onClick={() => toggle(card)}\n                  style={{ backgroundColor: suitTile(suit).bg, opacity: used ? 0.35 : disabled ? 0.25 : 1 }}\n                  className={`flex h-8 items-center justify-center rounded border border-white/25 text-sm font-bold text-white transition ${\n                    used ? \"ring-2 ring-white/80\" : disabled ? \"cursor-not-allowed\" : \"hover:brightness-110\"\n                  }`}\n                  title={`${rank}${SUIT_GLYPH[suit]}`}\n                >\n                  {rank}\n                </button>\n              );\n            })}\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/card-picker.tsx"
    },
    {
      "path": "src/components/explorer/explorer-app.tsx",
      "content": "\"use client\";\n\n// The Explorer — one continuous screen, modeled on GTO Wizard's Study mode.\n//\n// You walk the precomputed multiway NLHE tree one seat at a time. The moment a\n// line closes heads-up, the postflop solve panel appears inline right below the\n// seat strip — pick a flop, tweak the seeded continue ranges, and solve, all in\n// the same scroll (no drawer, no separate \"postflop\" screen). Results preview in\n// the full SolutionViewer and save with one button.\n//\n// Saved and sample solutions live on their own page, /library — this screen is\n// only the walk.\n\nimport { PreflopBrowser } from \"./preflop-browser\";\nimport { ExplorerUrlProvider } from \"./explorer-url\";\nimport type { ExplorerUrlState } from \"@/lib/explorer/share-url\";\n\nexport function ExplorerApp({ initial = {} }: { initial?: ExplorerUrlState }) {\n  return (\n    <ExplorerUrlProvider initial={initial}>\n      <PreflopBrowser />\n    </ExplorerUrlProvider>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/explorer-app.tsx"
    },
    {
      "path": "src/components/explorer/explorer-tabs.tsx",
      "content": "\"use client\";\n\n// One panel, two views: stored suit-bucket mixes, and the range explorer.\n// Games without a stored bucket tree show a placeholder on the Buckets tab.\n\nimport { useState, type ReactNode } from \"react\";\nimport { useExplorerUrl } from \"./explorer-url\";\n\nexport function BucketsComingSoon() {\n  return (\n    <p className=\"px-3 py-12 text-center text-sm text-muted-foreground\">Coming soon</p>\n  );\n}\n\nexport function ExplorerTabs({\n  buckets,\n  explorer,\n}: {\n  /** Stored bucket tree. Omitted games get the coming-soon placeholder. */\n  buckets?: ReactNode;\n  explorer: ReactNode;\n}) {\n  // The open tab is part of the shareable URL (?tab=buckets; Explorer is the default).\n  const url = useExplorerUrl();\n  const [tab, setTabState] = useState<\"buckets\" | \"explorer\">(() =>\n    url.get(\"tab\") === \"buckets\" ? \"buckets\" : \"explorer\",\n  );\n  const setTab = (next: \"buckets\" | \"explorer\") => {\n    setTabState(next);\n    url.set({ tab: next === \"buckets\" ? \"buckets\" : null });\n  };\n  const tabs = [\n    { id: \"buckets\" as const, label: \"Buckets\" },\n    { id: \"explorer\" as const, label: \"Explorer\" },\n  ];\n\n  return (\n    <div className=\"overflow-hidden rounded-xl border border-border bg-card/40\">\n      <div\n        role=\"tablist\"\n        aria-label=\"Range view\"\n        className=\"flex gap-1 border-b border-border px-2 pt-2\"\n      >\n        {tabs.map((item) => {\n          const selected = tab === item.id;\n          return (\n            <button\n              key={item.id}\n              type=\"button\"\n              role=\"tab\"\n              id={`range-tab-${item.id}`}\n              aria-selected={selected}\n              aria-controls={`range-panel-${item.id}`}\n              onClick={() => setTab(item.id)}\n              className={\n                selected\n                  ? \"-mb-px border-b-2 border-foreground px-3 py-1.5 text-xs font-medium text-foreground\"\n                  : \"-mb-px border-b-2 border-transparent px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground\"\n              }\n            >\n              {item.label}\n            </button>\n          );\n        })}\n      </div>\n      <div\n        role=\"tabpanel\"\n        id=\"range-panel-buckets\"\n        aria-labelledby=\"range-tab-buckets\"\n        className={tab === \"buckets\" ? \"px-2 py-2\" : \"hidden\"}\n      >\n        {buckets ?? <BucketsComingSoon />}\n      </div>\n      <div\n        role=\"tabpanel\"\n        id=\"range-panel-explorer\"\n        aria-labelledby=\"range-tab-explorer\"\n        className={tab === \"explorer\" ? \"p-3\" : \"hidden\"}\n      >\n        {explorer}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/explorer-tabs.tsx"
    },
    {
      "path": "src/components/explorer/explorer-url.tsx",
      "content": "\"use client\";\n\n// Keeps the Explorer's view in the address bar so any view is a shareable\n// link. The page reads the query on the server and hands it down as `initial`\n// (no useSearchParams, so nothing needs its own Suspense boundary); components\n// read their starting value from here and write changes back with\n// history.replaceState, which updates the URL without a navigation or a new\n// history entry per click.\n//\n// Without a provider (the explorer pieces rendered elsewhere) reads return\n// nothing and writes are dropped, so the components behave as before.\n\nimport { createContext, useContext, useMemo, useRef, type ReactNode } from \"react\";\nimport { mergeSearch, type ExplorerUrlKey, type ExplorerUrlState } from \"@/lib/explorer/share-url\";\n\ninterface ExplorerUrlApi {\n  get: (key: ExplorerUrlKey) => string | undefined;\n  set: (patch: Partial<Record<ExplorerUrlKey, string | null>>) => void;\n}\n\nconst NOOP: ExplorerUrlApi = { get: () => undefined, set: () => {} };\nconst Ctx = createContext<ExplorerUrlApi>(NOOP);\n\nexport function ExplorerUrlProvider({\n  initial,\n  children,\n}: {\n  initial: ExplorerUrlState;\n  children: ReactNode;\n}) {\n  // The current values, so a component that mounts later (a tab panel after a\n  // game switch) starts from what the URL says now, not what it said on load.\n  const state = useRef<ExplorerUrlState>({ ...initial });\n  const api = useMemo<ExplorerUrlApi>(\n    () => ({\n      get: (key) => state.current[key],\n      set: (patch) => {\n        let changed = false;\n        for (const [k, v] of Object.entries(patch) as [ExplorerUrlKey, string | null][]) {\n          const next = v == null || v === \"\" ? undefined : v;\n          if (state.current[k] !== next) {\n            changed = true;\n            if (next === undefined) delete state.current[k];\n            else state.current[k] = next;\n          }\n        }\n        if (!changed || typeof window === \"undefined\") return;\n        // `download` is a one-off error flag from a failed pack download; a\n        // shared link shouldn't carry it.\n        const search = mergeSearch(window.location.search, { ...patch, download: null });\n        const url = `${window.location.pathname}${search}${window.location.hash}`;\n        window.history.replaceState(null, \"\", url);\n      },\n    }),\n    [],\n  );\n  return <Ctx.Provider value={api}>{children}</Ctx.Provider>;\n}\n\nexport function useExplorerUrl(): ExplorerUrlApi {\n  return useContext(Ctx);\n}\n",
      "type": "registry:component",
      "target": "components/explorer/explorer-url.tsx"
    },
    {
      "path": "src/components/explorer/hand-search-bar.tsx",
      "content": "\"use client\";\n\n// Hand search for the PLO Explorer, in GTO Wizard's syntax (parser and\n// definitions in lib/hand-search). The field is the shared SearchField block;\n// this file only supplies the syntax reference shown in its ? popover.\n\nimport type { ReactNode } from \"react\";\n\nimport { SearchField } from \"@/components/blocks/search-field\";\nimport {\n  DRAW_MACROS,\n  POSTFLOP_MACROS,\n  PREFLOP_MACROS,\n} from \"@/lib/hand-search\";\n\nconst GENERAL: [string, string][] = [\n  [\"*\", \"Any single rank\"],\n  [\"AKQJT98765432\", \"Ranks, ace down to two\"],\n  [\n    \"R O N\",\n    \"Rank variables: R (or P) and O bind a rank, so RR is a pair; N is a rank held once\",\n  ],\n  [\n    \"[ ]\",\n    \"A list of ranks, suits or cards for one position: [AK], [T-A], A[sh], [As,Kd]\",\n  ],\n  [\"s h d c\", \"Suits: spades, hearts, diamonds, clubs\"],\n  [\n    \"w x y z\",\n    \"Suit variables: same letter same suit, different letters different suits\",\n  ],\n];\n\nconst OPERATORS: [string, string][] = [\n  [\",\", \"Union: either side\"],\n  [\":\", \"Intersection: both sides\"],\n  [\n    \"!\",\n    \"Difference: left side without the right (!AA alone = every hand but AA)\",\n  ],\n  [\"( )\", \"Group to set the order\"],\n  [\">\", \"Equal or better than a made-hand category (needs a board)\"],\n  [\"<\", \"Worse than a made-hand category (needs a board)\"],\n];\n\nconst EXAMPLES = [\n  [\"AA**:$ds\", \"Double-suited aces\"],\n  [\"AxKx**\", \"A and K of one suit\"],\n  [\"RROO\", \"Two pair\"],\n  [\"$0g!$rb\", \"Rundowns that aren't rainbow\"],\n  [\"[T-A][T-A][T-A][T-A]\", \"Four Broadway cards\"],\n  [\"(KK,QQ):$dsn\", \"KK or QQ, double-suited with a nut suit\"],\n].map(([code, text]) => ({ code, text }));\n\nexport function HandSearchBar({\n  value,\n  onChange,\n  error,\n  note,\n}: {\n  value: string;\n  onChange: (next: string) => void;\n  error: string | null;\n  note: string | null;\n}) {\n  return (\n    <SearchField\n      value={value}\n      onChange={onChange}\n      label=\"Search hands\"\n      placeholder=\"Search hands, e.g. AA**:$ds\"\n      error={error}\n      note={note}\n      helpLabel=\"Hand search syntax\"\n      examples={EXAMPLES}\n      help={\n        <>\n          <HelpSection title=\"General\">\n            <Rows rows={GENERAL} />\n          </HelpSection>\n          <HelpSection title=\"Operators\">\n            <Rows rows={OPERATORS} />\n          </HelpSection>\n          <HelpSection title=\"Preflop macros\">\n            <Rows rows={PREFLOP_MACROS.map((m) => [m.name, m.help])} />\n          </HelpSection>\n          <HelpSection\n            title=\"Postflop macros\"\n            hint=\"Need a board, so they don't filter preflop ranges.\"\n          >\n            <Rows rows={POSTFLOP_MACROS.map((m) => [m.name, m.help])} />\n          </HelpSection>\n          <HelpSection title=\"Draws and blockers\" hint=\"Need a board too.\">\n            <Rows rows={DRAW_MACROS.map((m) => [m.name, m.help])} />\n          </HelpSection>\n        </>\n      }\n    />\n  );\n}\n\nfunction HelpSection({\n  title,\n  hint,\n  children,\n}: {\n  title: string;\n  hint?: string;\n  children: ReactNode;\n}) {\n  return (\n    <section className=\"flex flex-col gap-1.5\">\n      <h3 className=\"text-[12px] font-medium uppercase tracking-wide text-muted-foreground\">\n        {title}\n      </h3>\n      {hint ? (\n        <p className=\"text-[12px] text-muted-foreground\">{hint}</p>\n      ) : null}\n      {children}\n    </section>\n  );\n}\n\nfunction Rows({ rows }: { rows: [string, string][] }) {\n  return (\n    <dl className=\"grid grid-cols-[minmax(0,9.5rem)_1fr] gap-x-3 gap-y-1 px-1\">\n      {rows.map(([k, v]) => (\n        <div key={k} className=\"contents\">\n          <dt className=\"font-mono text-[12px] text-foreground\">{k}</dt>\n          <dd className=\"text-[12px] text-muted-foreground\">{v}</dd>\n        </div>\n      ))}\n    </dl>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/hand-search-bar.tsx"
    },
    {
      "path": "src/components/explorer/hand-summary.tsx",
      "content": "\"use client\";\n\n// GTO-Wizard-style hand summary for the preflop browser. One row per in-range\n// hand class: the class label, a mini strategy bar (the action split), the\n// hand's EV, and the share of the range it represents. Sorted so the hands that\n// keep going (raise/all-in) sit on top, like GTO Wizard's Summary tab.\n//\n// EV comes from the v2 ranges dataset (`/api/ranges/nl/v2/node`), which carries\n// per-action EV in small blinds. The hand's EV is the strategy-frequency-\n// weighted average of the EVs of the actions it takes (at equilibrium those are\n// indifferent), shown in big blinds. When a node has no EV (legacy data), the\n// column is hidden rather than faked.\n\nimport { useMemo } from \"react\";\nimport { ALL_HANDS, comboCountOf } from \"@/lib/solver/range-model\";\nimport { colorActions } from \"./preflop-strategy-grid\";\nimport type { NodeAction } from \"@/lib/solver/preflop\";\n\ninterface Row {\n  hand: string;\n  /** Per-action frequency for this class, parallel to the colored actions. */\n  freqs: number[];\n  /** In-range fraction (Σ freqs). */\n  total: number;\n  /** Weighted concrete combos (total × comboCount). */\n  combos: number;\n  /** Raise + all-in frequency (the EV tiebreak: how much the hand raises). */\n  raiseFreq: number;\n  /** Strategy-weighted EV in big blinds, when the dataset carries EV. */\n  evBb?: number;\n}\n\nexport function PreflopHandSummary({\n  actions,\n  evUnit = \"sb\",\n}: {\n  actions: NodeAction[];\n  /** Unit of the actions' `evs`: small blinds (shown as bb), or tournament\n   *  dollars on the ICM sets (shown as $). */\n  evUnit?: \"sb\" | \"usd\";\n}) {\n  const usd = evUnit === \"usd\";\n  const colored = useMemo(() => colorActions(actions), [actions]);\n\n  const { rows, rangeCombos, hasEv } = useMemo(() => {\n    const out: Row[] = [];\n    let rangeCombos = 0;\n    let hasEv = false;\n    for (const hand of ALL_HANDS) {\n      const freqs = colored.map(({ action }) => action.weights[hand] ?? 0);\n      const total = freqs.reduce((s, f) => s + f, 0);\n      if (total <= 0.0005) continue;\n      const combos = total * comboCountOf(hand);\n      rangeCombos += combos;\n\n      // How much the hand raises (raise + all-in share) — the EV tiebreak.\n      let raiseW = 0;\n      colored.forEach(({ action }, a) => {\n        if (action.kind === \"raise\" || action.kind === \"allin\") raiseW += freqs[a];\n      });\n      const raiseFreq = raiseW / (total || 1);\n\n      // Hand EV = strategy-weighted mean of the EVs of the actions it takes\n      // (small blinds → bb). Only counts actions that carry an EV for this hand.\n      let evWeighted = 0;\n      let evDenom = 0;\n      colored.forEach(({ action }, a) => {\n        const e = action.evs?.[hand];\n        if (e === undefined) return;\n        const f = freqs[a];\n        if (f > 0) {\n          evWeighted += f * e;\n          evDenom += f;\n        }\n      });\n      const evBb = evDenom > 0 ? evWeighted / evDenom / (usd ? 1 : 2) : undefined;\n      if (evBb !== undefined) hasEv = true;\n\n      out.push({ hand, freqs, total, combos, raiseFreq, evBb });\n    }\n    // Highest EV on top. Hands that show the same EV (rounded to the displayed\n    // 0.01bb — the indifferent \"zero-EV mixed\" cluster) are ordered by how much\n    // they raise. Hands without EV fall to the bottom, also by raise frequency.\n    const r2 = (x: number) => Math.round(x * 100) / 100;\n    out.sort((a, b) => {\n      if (a.evBb !== undefined && b.evBb !== undefined) {\n        const d = r2(b.evBb) - r2(a.evBb);\n        if (d !== 0) return d;\n        return b.raiseFreq - a.raiseFreq || b.combos - a.combos;\n      }\n      if (a.evBb !== undefined) return -1;\n      if (b.evBb !== undefined) return 1;\n      return b.raiseFreq - a.raiseFreq || b.combos - a.combos;\n    });\n    return { rows: out, rangeCombos, hasEv };\n  }, [colored, usd]);\n\n  const cols = hasEv ? \"52px minmax(0,1fr) 58px 56px\" : \"52px minmax(0,1fr) 62px\";\n\n  return (\n    <div className=\"flex flex-col gap-2\">\n      <span className=\"text-[10px] uppercase tracking-wide text-muted-foreground\">Hand summary</span>\n      <div\n        className=\"grid gap-2 px-1 text-[10px] uppercase tracking-wide text-muted-foreground/70\"\n        style={{ gridTemplateColumns: cols }}\n      >\n        <span>Hand</span>\n        <span>Strategy</span>\n        {hasEv ? <span className=\"text-right\">{usd ? \"EV $\" : \"EV bb\"}</span> : null}\n        <span className=\"text-right\">Range</span>\n      </div>\n      <div className=\"flex max-h-[460px] flex-col overflow-y-auto pr-0.5\">\n        {rows.map((r) => {\n          const rangePct = rangeCombos > 0 ? (r.combos / rangeCombos) * 100 : 0;\n          return (\n            <div\n              key={r.hand}\n              className=\"grid items-center gap-2 rounded px-1 py-1 hover:bg-accent/30\"\n              style={{ gridTemplateColumns: cols }}\n            >\n              <span className=\"text-xs font-semibold text-foreground tabular-nums\">{r.hand}</span>\n              <div className=\"flex h-2 overflow-hidden rounded-full bg-white/[0.06]\">\n                {r.freqs.map((f, a) =>\n                  f <= 0.001 ? null : (\n                    <div key={a} style={{ flexGrow: f, backgroundColor: colored[a].color }} />\n                  ),\n                )}\n              </div>\n              {hasEv ? (\n                <span\n                  className={`text-right text-[11px] tabular-nums ${\n                    r.evBb === undefined\n                      ? \"text-muted-foreground/40\"\n                      : r.evBb >= 0\n                        ? \"text-emerald-400\"\n                        : \"text-rose-400\"\n                  }`}\n                >\n                  {r.evBb === undefined ? \"—\" : `${r.evBb >= 0 ? \"+\" : \"\"}${r.evBb.toFixed(2)}`}\n                </span>\n              ) : null}\n              <span className=\"text-right text-[11px] text-muted-foreground tabular-nums\">\n                {rangePct.toFixed(1)}%\n              </span>\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/hand-summary.tsx"
    },
    {
      "path": "src/components/explorer/lock-editor.tsx",
      "content": "\"use client\";\n\n// The node strategy editor (#268): opened from the solution viewer at an\n// action node, one slider + number input per action. Values are free-form\n// weights, displayed and applied as the normalized percentage split (so\n// dragging one slider never has to fight the others to stay at 100%). Applying\n// produces an aggregate (`all_hands`) lock — every combo of the acting\n// player's range plays the same frequencies verbatim in the re-solve.\n// Presented in the shared BottomSheet chrome so it matches the Edit Node sheet.\n\nimport { useMemo, useState } from \"react\";\nimport { Lock, Trash2 } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport { ACTION_COLORS } from \"@/components/solver/strategy-grid\";\nimport type { SolverActionInfo } from \"@/lib/solver/types\";\nimport { normalizeLockFreqs } from \"@/lib/explorer/locks\";\nimport { BottomSheet, SHEET_ROW } from \"./bottom-sheet\";\n\nexport function LockEditor({\n  actions,\n  pot,\n  initial,\n  hasLock,\n  onApply,\n  onRemove,\n  onCancel,\n}: {\n  actions: SolverActionInfo[];\n  /** Pot before the player acts, for the %-pot hint on bets/raises. */\n  pot: number;\n  /** Starting frequencies — the existing lock, or the node's current\n   *  aggregate strategy (so \"apply\" with no edits locks the solver line). */\n  initial: number[];\n  /** True when this node already has a pending lock (shows Remove). */\n  hasLock: boolean;\n  /** Called with the normalized frequency vector (one per action, sum 1). */\n  onApply: (freqs: number[]) => void;\n  onRemove: () => void;\n  onCancel: () => void;\n}) {\n  const [weights, setWeights] = useState<number[]>(() =>\n    actions.map((_, i) => Math.max(0, (initial[i] ?? 0) * 100)),\n  );\n\n  const normalized = useMemo(() => normalizeLockFreqs(weights), [weights]);\n\n  const setWeight = (i: number, v: number) => {\n    setWeights((w) => w.map((x, j) => (j === i ? Math.min(100, Math.max(0, v)) : x)));\n  };\n\n  return (\n    <BottomSheet\n      title=\"Lock strategy — this node\"\n      icon={<Lock className=\"size-4 text-amber-400\" />}\n      onClose={onCancel}\n      footer={\n        <>\n          <span className=\"flex items-center gap-2\">\n            {hasLock ? (\n              <Button size=\"sm\" variant=\"outline\" onClick={onRemove}>\n                <Trash2 className=\"size-3.5\" /> Remove lock\n              </Button>\n            ) : null}\n            {!normalized ? (\n              <span className=\"text-xs text-destructive\">\n                At least one action needs a positive weight.\n              </span>\n            ) : null}\n          </span>\n          <Button size=\"sm\" onClick={() => normalized && onApply(normalized)} disabled={!normalized}>\n            <Lock className=\"size-3.5\" /> {hasLock ? \"Update lock\" : \"Apply lock\"}\n          </Button>\n        </>\n      }\n    >\n      <p className=\"text-[11px] text-muted-foreground/70\">\n        Every hand in range will play this exact split (an aggregate lock). Frequencies\n        normalize to 100% automatically. Re-solving makes the rest of the tree adjust\n        against it.\n      </p>\n\n      {actions.map((action, i) => {\n        const pct = normalized ? normalized[i] * 100 : 0;\n        return (\n          <div key={i} className={SHEET_ROW}>\n            <span className=\"flex w-32 shrink-0 items-center gap-2 text-sm text-foreground\">\n              <span\n                className=\"size-3 shrink-0 rounded-[3px]\"\n                style={{ backgroundColor: ACTION_COLORS[action.label] }}\n              />\n              <span className=\"truncate\">\n                {action.label}\n                {action.add > 0 ? (\n                  <span className=\"ml-1 text-xs text-muted-foreground tabular-nums\">\n                    {Math.round(action.add * 10) / 10}bb\n                    {pot > 0 && (action.label === \"Bet\" || action.label === \"Raise\")\n                      ? ` · ${Math.round((action.add / pot) * 100)}%`\n                      : \"\"}\n                  </span>\n                ) : null}\n              </span>\n            </span>\n            <input\n              type=\"range\"\n              min={0}\n              max={100}\n              step={1}\n              value={weights[i]}\n              onChange={(e) => setWeight(i, Number(e.target.value))}\n              aria-label={`${action.label} weight`}\n              className=\"min-w-0 flex-1 accent-amber-400\"\n            />\n            <span className=\"flex items-center rounded-md border border-input bg-card\">\n              <input\n                type=\"number\"\n                min={0}\n                max={100}\n                step={1}\n                value={Math.round(weights[i] * 10) / 10}\n                onChange={(e) => setWeight(i, Number(e.target.value))}\n                aria-label={`${action.label} percent`}\n                className=\"h-8 w-14 bg-transparent px-2 text-right text-sm text-foreground tabular-nums outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none\"\n              />\n              <span className=\"pr-2 text-xs text-muted-foreground\">%</span>\n            </span>\n            <span className=\"w-14 shrink-0 text-right text-xs text-muted-foreground tabular-nums\">\n              → {pct.toFixed(1)}%\n            </span>\n          </div>\n        );\n      })}\n\n      {/* Normalized split preview bar */}\n      <div className=\"flex h-2 w-full overflow-hidden rounded-full bg-white/[0.06]\">\n        {normalized\n          ? actions.map((action, i) =>\n              normalized[i] > 0 ? (\n                <div\n                  key={i}\n                  style={{\n                    flexGrow: normalized[i],\n                    backgroundColor: ACTION_COLORS[action.label],\n                  }}\n                />\n              ) : null,\n            )\n          : null}\n      </div>\n    </BottomSheet>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/lock-editor.tsx"
    },
    {
      "path": "src/components/explorer/node-edit-modal.tsx",
      "content": "\"use client\";\n\n// GTO-Wizard-style \"Edit node\" sheet (#390 + node cards): edit the ACTION SET\n// at one decision point — bet/raise sizes as % of pot, plus the all-in shove.\n// Confirming lowers the rows to a `sizing.nodes` entry (engine NodeSizingConfig)\n// and re-solves the tree; this is a structural edit, so unlike a frequency\n// lock it can never warm-start. Presented in the shared BottomSheet chrome so\n// it matches the lock editor.\n\nimport { useMemo, useState } from \"react\";\nimport { Pencil, Plus, X } from \"lucide-react\";\nimport type { SolverActionInfo } from \"@/lib/solver/types\";\nimport { BottomSheet, SHEET_ROW } from \"./bottom-sheet\";\n\n/** Engine formula inverted: add = toCall + f·(pot + toCall). */\nfunction fracOf(add: number, pot: number, toCall: number): number {\n  return (add - toCall) / (pot + toCall);\n}\n\nexport function NodeEditModal({\n  actorLabel,\n  pot,\n  actions,\n  hasEdits,\n  busy,\n  onConfirm,\n  onClearAll,\n  onClose,\n}: {\n  actorLabel: string;\n  /** Pot before this player acts (bb). */\n  pot: number;\n  /** The node's current actions (engine dump order). */\n  actions: SolverActionInfo[];\n  /** Any node edits are active anywhere in the tree. */\n  hasEdits: boolean;\n  /** A re-solve is already running. */\n  busy: boolean;\n  /** Lowered rows: pot fractions (sorted asc) + whether to keep the shove. */\n  onConfirm: (sizes: number[], allin: boolean) => void;\n  /** Remove every node edit in the tree (then re-solve). */\n  onClearAll?: () => void;\n  onClose: () => void;\n}) {\n  const toCall = actions.find((a) => a.label === \"Call\")?.add ?? 0;\n  const passive = useMemo(\n    () => actions.filter((a) => a.label === \"Check\" || a.label === \"Fold\" || a.label === \"Call\"),\n    [actions],\n  );\n  const aggressive = actions.filter((a) => a.label === \"Bet\" || a.label === \"Raise\");\n  const betWord = toCall > 0 ? \"Raise\" : \"Bet\";\n\n  // Rows are % of pot (integers in the UI, fractions on confirm).\n  const [rows, setRows] = useState<number[]>(() =>\n    aggressive.map((a) => Math.round(fracOf(a.add, pot, toCall) * 100)),\n  );\n  const [allin, setAllin] = useState(() => actions.some((a) => a.label === \"AllIn\"));\n\n  const setRow = (i: number, pct: number) =>\n    setRows((r) => r.map((v, j) => (j === i ? pct : v)));\n  const removeRow = (i: number) => setRows((r) => r.filter((_, j) => j !== i));\n  const addRow = () => setRows((r) => [...r, 50]);\n\n  const valid = rows.every((p) => Number.isFinite(p) && p > 0);\n  const confirm = () => {\n    if (!valid || busy) return;\n    const sizes = [...new Set(rows.map((p) => p / 100))].sort((a, b) => a - b);\n    onConfirm(sizes, allin);\n  };\n\n  return (\n    <BottomSheet\n      title={`Edit node · ${actorLabel}`}\n      icon={<Pencil className=\"size-4 text-muted-foreground\" />}\n      onClose={onClose}\n      footer={\n        <>\n          {hasEdits && onClearAll ? (\n            <button\n              type=\"button\"\n              onClick={onClearAll}\n              disabled={busy}\n              className=\"text-sm font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50\"\n            >\n              Delete All Node Edits\n            </button>\n          ) : (\n            <span />\n          )}\n          <button\n            type=\"button\"\n            onClick={confirm}\n            disabled={!valid || busy}\n            className=\"rounded-lg bg-foreground px-4 py-2 text-sm font-semibold text-background transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50\"\n          >\n            Confirm\n          </button>\n        </>\n      }\n    >\n      {passive.map((a) => (\n        <div key={a.label} className={SHEET_ROW}>\n          <span className=\"flex-1 text-sm text-foreground\">\n            {a.label}\n            {a.add > 0 ? (\n              <span className=\"ml-2 text-xs text-muted-foreground tabular-nums\">\n                {Math.round(a.add * 10) / 10}bb\n              </span>\n            ) : null}\n          </span>\n          <span className=\"text-[10px] text-muted-foreground/60\">always kept</span>\n        </div>\n      ))}\n\n      {rows.map((pct, i) => (\n        <div key={i} className={SHEET_ROW}>\n          <span className=\"w-11 text-sm text-foreground\">{betWord}</span>\n          <span className=\"flex items-center rounded-md border border-input bg-card\">\n            <input\n              value={Number.isFinite(pct) ? String(pct) : \"\"}\n              onChange={(e) => setRow(i, Number(e.target.value))}\n              inputMode=\"numeric\"\n              aria-label={`${betWord} size ${i + 1} (% of pot)`}\n              className=\"h-8 w-14 bg-transparent px-2 text-right text-sm text-foreground tabular-nums outline-none\"\n            />\n            <span className=\"pr-2 text-xs text-muted-foreground\">%</span>\n          </span>\n          <input\n            type=\"range\"\n            min={5}\n            max={200}\n            step={1}\n            value={Math.min(Math.max(Number.isFinite(pct) ? pct : 5, 5), 200)}\n            onChange={(e) => setRow(i, Number(e.target.value))}\n            aria-label={`${betWord} size ${i + 1} slider`}\n            className=\"min-w-0 flex-1 accent-foreground\"\n          />\n          <button\n            type=\"button\"\n            onClick={() => removeRow(i)}\n            aria-label={`Remove ${betWord.toLowerCase()} size`}\n            className=\"rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n          >\n            <X className=\"size-4\" />\n          </button>\n        </div>\n      ))}\n\n      <div className={SHEET_ROW}>\n        <span className=\"flex-1 text-sm text-foreground\">All-in</span>\n        <input\n          type=\"checkbox\"\n          checked={allin}\n          onChange={(e) => setAllin(e.target.checked)}\n          aria-label=\"Include all-in\"\n          className=\"size-4 accent-foreground\"\n        />\n      </div>\n\n      <button\n        type=\"button\"\n        onClick={addRow}\n        className=\"flex items-center justify-between rounded-lg border border-dashed border-border px-3 py-2 text-left text-sm text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground\"\n      >\n        {betWord}\n        <Plus className=\"size-4\" />\n      </button>\n\n      <p className=\"text-[11px] text-muted-foreground/70\">\n        Confirm rebuilds the game tree with these actions and re-solves the spot from\n        scratch (a structural edit can&apos;t warm-start).\n      </p>\n    </BottomSheet>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/node-edit-modal.tsx"
    },
    {
      "path": "src/components/explorer/plo-range-list.tsx",
      "content": "\"use client\";\n\n// PLO hand-class viewer for the Explorer: one section per action (Fold / Call /\n// Raise pot …), each listing every hand that takes it, sorted by EV. Omaha has\n// no 13×13 grid — 16,432 suit-isomorphism classes — so hands render as compact\n// card tiles and the filter chips (suitedness / connectedness / pairing /\n// height) slice every section at once.\n//\n// Ported from pokerdata.io's explorer, restyled onto this app's tokens: the\n// action palette is the solver grid's (`colorActions`), and the cards are the\n// same white faces with four-color suits the trainer and hand replayer use,\n// rather than pokerdata's solid suit-tinted tiles.\n\nimport { useDeferredValue, useMemo, useState } from \"react\";\nimport { useExplorerUrl } from \"./explorer-url\";\nimport { HandSearchBar } from \"./hand-search-bar\";\nimport { matchesHandClass, parseHandQuery } from \"@/lib/hand-search\";\n\nimport {\n  FILTER_GROUPS,\n  handProps,\n  matchesFilters,\n  type FilterId,\n  type HandProps,\n} from \"@/lib/explorer/plo-filter\";\nimport { ploLabelForAction, sortActionsForDisplay, type NodeAction } from \"@/lib/solver/preflop\";\nimport { MiniCard } from \"@/components/trainer/cards\";\nimport { ploStringToCards } from \"@/lib/trainer/plo-hand\";\nimport { classComboCount } from \"@/lib/plo-ranges/combos\";\n\nimport { colorActions, type PreflopActionItem } from \"./preflop-strategy-grid\";\n\nconst comboMemo = new Map<string, number>();\n\n/** Concrete combos a Monker hand class stands for (\"(2A)AA\" → 12), memoized. */\nfunction combosOf(hand: string): number {\n  let n = comboMemo.get(hand);\n  if (n === undefined) {\n    n = classComboCount(hand);\n    comboMemo.set(hand, n);\n  }\n  return n;\n}\n\n/** Σ weight × combos: the share of the 270,725 starting hands, as solvers report it. */\nfunction comboMass(weights: Record<string, number>): number {\n  let s = 0;\n  for (const [hand, w] of Object.entries(weights)) if (w > 0) s += w * combosOf(hand);\n  return s;\n}\n\n/**\n * Aggregate action shares for the seat cards, weighted by concrete combos.\n *\n * A class like \"AAAA\" is 1 combo and \"AKQJ\" rainbow is 24, so counting classes\n * misstates the split (heads-up PLO4 SB root: 6.8/27.5/65.7 by class against\n * 6.4/25.7/68.0 by combo). Solvers and GTO Wizard report combo shares.\n */\nexport function ploActionItems(actions: NodeAction[], stack: number): PreflopActionItem[] {\n  const colored = colorActions(sortActionsForDisplay(actions));\n  const mass = colored.map(({ action }) => comboMass(action.weights));\n  const denom = mass.reduce((s, m) => s + m, 0) || 1;\n  return colored.map(({ action, color }, i) => ({\n    action,\n    label: ploLabelForAction(action, stack),\n    color,\n    freq: mass[i] / denom,\n    combos: mass[i],\n  }));\n}\n\n/** One hand's line in an action column. */\nexport interface BreakdownRow {\n  /** Stable key: a Monker class string preflop, a concrete combo postflop. */\n  key: string;\n  /** The hand's cards, any order (they render high first). */\n  cards: string[];\n  /** Frequency of taking THIS action, in [0, 1]. */\n  freq: number;\n  /** EV (bb) of this action, when the dataset carries EV. */\n  evBb: number | null;\n  /** EV edge (bb) over the hand's best alternative action; null if unknown. */\n  evDiffBb: number | null;\n  props: HandProps;\n  /** This row's share of the range: freq × combos preflop, freq × reach postflop.\n   *  Filters recompute each column's percent from these. */\n  weight: number;\n}\n\n/** One action column: its header share and every hand that takes it. */\nexport interface BreakdownSection {\n  key: string;\n  label: string;\n  color: string;\n  /** The action's share of the whole range, in percent (unfiltered). */\n  pct: number;\n  /** Sorted rows, best EV first. */\n  rows: BreakdownRow[];\n}\n\n/** Rows rendered per section before \"show all\" — the 13k-hand fold list would\n *  otherwise lock the tab on first paint. */\nconst SECTION_PREVIEW = 150;\n\nexport function PloRangeList({ actions, stack }: { actions: NodeAction[]; stack: number }) {\n  const colored = useMemo(() => colorActions(sortActionsForDisplay(actions)), [actions]);\n\n  const sections = useMemo<BreakdownSection[]>(() => {\n    // hand → filterable props, computed once across every action's key set.\n    const propsByHand = new Map<string, HandProps>();\n    for (const { action } of colored) {\n      for (const h of Object.keys(action.weights)) if (!propsByHand.has(h)) propsByHand.set(h, handProps(h));\n    }\n    const built = colored.map(({ action, color }, idx) => {\n      const rows: BreakdownRow[] = [];\n      let mass = 0;\n      for (const [hand, freq] of Object.entries(action.weights)) {\n        if (freq <= 0.0005) continue;\n        const ev = action.evs?.[hand];\n        // Edge over the best alternative action that carries an EV for this hand.\n        let bestOther: number | null = null;\n        colored.forEach(({ action: other }, j) => {\n          if (j === idx) return;\n          const e = other.evs?.[hand];\n          if (e !== undefined && (bestOther === null || e > bestOther)) bestOther = e;\n        });\n        const weight = freq * combosOf(hand);\n        mass += weight;\n        rows.push({\n          key: hand,\n          cards: ploStringToCards(hand),\n          freq,\n          // The dataset's EV is in small blinds; the Explorer talks in bb.\n          evBb: ev === undefined ? null : ev / 2,\n          evDiffBb: ev === undefined || bestOther === null ? null : (ev - bestOther) / 2,\n          props: propsByHand.get(hand)!,\n          weight,\n        });\n      }\n      rows.sort((a, b) => (b.evBb ?? -Infinity) - (a.evBb ?? -Infinity) || b.freq - a.freq);\n      return { key: action.action, label: ploLabelForAction(action, stack), color, rows, mass };\n    });\n    const total = built.reduce((s, sec) => s + sec.mass, 0) || 1;\n    return built.map(({ mass, ...sec }) => ({ ...sec, pct: (mass / total) * 100 }));\n  }, [colored, stack]);\n\n  return <PloActionBreakdown sections={sections} />;\n}\n\n/**\n * The per-action range breakdown: hand search, filter chips, then one column\n * per action with its share, hand count and hand list (freq, EV, diff). The\n * preflop Explorer and the PLO postflop view both render through this.\n *\n * Without `board` the rows are suit-isomorphism classes (preflop); with it they\n * are concrete combos, and board-aware searches (TP, FD, >2P …) apply.\n */\nexport function PloActionBreakdown({\n  sections,\n  board,\n  sampleOf,\n}: {\n  sections: BreakdownSection[];\n  board?: string[];\n  /** Set when the rows are a sample of the range: the sample's size. */\n  sampleOf?: number;\n}) {\n  // Active chips are part of the shareable URL (?f=ds,rundown).\n  const url = useExplorerUrl();\n  const [active, setActiveState] = useState<Set<FilterId>>(() => {\n    const known = new Set<string>(FILTER_GROUPS.flatMap((g) => g.chips.map((c) => c.id)));\n    const ids = (url.get(\"f\") ?? \"\").split(\",\").filter((id) => known.has(id));\n    return new Set(ids as FilterId[]);\n  });\n  const setActive = (update: (prev: Set<FilterId>) => Set<FilterId>) => {\n    const next = update(active);\n    setActiveState(next);\n    url.set({ f: [...next].join(\",\") || null });\n  };\n  const [expanded, setExpanded] = useState<Set<string>>(() => new Set());\n\n  // Hand search (GTO Wizard syntax), also in the URL (?s=AA**:$ds).\n  const [search, setSearchState] = useState(() => url.get(\"s\") ?? \"\");\n  const setSearch = (next: string) => {\n    setSearchState(next);\n    url.set({ s: next.trim() || null });\n  };\n  const deferredSearch = useDeferredValue(search);\n  const parsed = useMemo(() => {\n    const text = deferredSearch.trim();\n    return text ? parseHandQuery(text) : null;\n  }, [deferredSearch]);\n  // A query filters when it parses, and needs no board or has one.\n  const query = parsed?.ok && (!parsed.query.needsBoard || board) ? parsed.query : null;\n  const searchError = parsed && !parsed.ok ? `${parsed.error} (at character ${parsed.index + 1})` : null;\n  const searchNote =\n    parsed?.ok && parsed.query.needsBoard && !board\n      ? \"Postflop and draw macros (TP, FD, >2P …) need a board. These are preflop ranges, so this search isn't applied.\"\n      : null;\n\n  // Every distinct hand across the columns.\n  const hands = useMemo(() => {\n    const map = new Map<string, BreakdownRow>();\n    for (const sec of sections) for (const r of sec.rows) if (!map.has(r.key)) map.set(r.key, r);\n    return map;\n  }, [sections]);\n\n  const toggle = (id: FilterId) =>\n    setActive((prev) => {\n      const next = new Set(prev);\n      if (next.has(id)) next.delete(id);\n      else next.add(id);\n      return next;\n    });\n\n  // Hands passing the chips AND the search; null = no filter at all.\n  const passing = useMemo(() => {\n    if (active.size === 0 && !query) return null;\n    const out = new Set<string>();\n    for (const [key, r] of hands) {\n      if (active.size > 0 && !matchesFilters(r.props, active)) continue;\n      if (query) {\n        // Concrete combos on a board are tested as dealt; classes try each suit relabelling.\n        const ok = board ? query.test(r.cards, board) : matchesHandClass(query, r.cards);\n        if (!ok) continue;\n      }\n      out.add(key);\n    }\n    return out;\n  }, [hands, active, query, board]);\n\n  // With a filter on, each column's percent is its share of the hands that\n  // pass, weighted the same way as the unfiltered figure (combos × freq).\n  const filtered = useMemo(() => {\n    if (passing === null) return sections;\n    const kept = sections.map((sec) => {\n      const rows = sec.rows.filter((r) => passing.has(r.key));\n      return { ...sec, rows, mass: rows.reduce((s, r) => s + r.weight, 0) };\n    });\n    const total = kept.reduce((s, sec) => s + sec.mass, 0);\n    return kept.map(({ mass, ...sec }) => ({ ...sec, pct: total > 0 ? (mass / total) * 100 : 0 }));\n  }, [sections, passing]);\n\n  const matching = passing === null ? hands.size : passing.size;\n  const anyFilter = active.size > 0 || search.trim() !== \"\";\n\n  const hasEv = sections.some((s) => s.rows.some((r) => r.evBb !== null));\n  const cols = hasEv\n    ? \"grid-cols-[minmax(0,1fr)_44px_52px_52px]\"\n    : \"grid-cols-[minmax(0,1fr)_44px]\";\n\n  return (\n    <div className=\"flex flex-col gap-3\">\n      <HandSearchBar value={search} onChange={setSearch} error={searchError} note={searchNote} />\n\n      <div className=\"flex items-center justify-between gap-3\">\n        <span className=\"text-xs tabular-nums text-muted-foreground\">\n          {matching.toLocaleString(\"en-US\")} of{\" \"}\n          {sampleOf !== undefined\n            ? `a ${sampleOf.toLocaleString(\"en-US\")}-hand sample`\n            : `${hands.size.toLocaleString(\"en-US\")} hands`}\n        </span>\n        {anyFilter ? (\n          <button\n            type=\"button\"\n            onClick={() => {\n              setActive(() => new Set());\n              setSearch(\"\");\n            }}\n            className=\"text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground\"\n          >\n            Clear filters\n          </button>\n        ) : null}\n      </div>\n\n      {/* OR within a group, AND across groups. */}\n      <div className=\"flex flex-wrap items-center gap-1.5\">\n        {FILTER_GROUPS.map((group, gi) => (\n          <div key={group.key} className=\"flex items-center gap-1.5\">\n            {gi > 0 ? <span aria-hidden className=\"h-4 w-px bg-border\" /> : null}\n            {group.chips.map((chip) => {\n              const on = active.has(chip.id);\n              return (\n                <button\n                  key={chip.id}\n                  type=\"button\"\n                  onClick={() => toggle(chip.id)}\n                  aria-pressed={on}\n                  className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${\n                    on\n                      ? \"bg-primary text-primary-foreground\"\n                      : \"bg-secondary text-muted-foreground hover:bg-accent hover:text-foreground\"\n                  }`}\n                >\n                  {chip.label}\n                </button>\n              );\n            })}\n          </div>\n        ))}\n      </div>\n\n      <div className=\"grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(280px,1fr))]\">\n        {filtered.map((sec) => {\n          const isOpen = expanded.has(sec.key);\n          const shown = isOpen ? sec.rows : sec.rows.slice(0, SECTION_PREVIEW);\n          const pct = sec.pct;\n          return (\n            <section\n              key={sec.key}\n              className=\"flex flex-col overflow-hidden rounded-xl border border-border bg-card/40\"\n            >\n              {/* Header tinted by the action's own color, as in the grid legend. */}\n              <div\n                className=\"flex flex-col gap-1.5 px-3 py-2.5\"\n                style={{ backgroundColor: `${sec.color}26` }}\n              >\n                <div className=\"flex items-baseline justify-between gap-2\">\n                  <span className=\"text-sm font-medium text-foreground\">{sec.label}</span>\n                  <span className=\"text-[11px] tabular-nums text-muted-foreground\">\n                    {sec.rows.length.toLocaleString(\"en-US\")}{\" \"}\n                    {sec.rows.length === 1 ? \"hand\" : \"hands\"}\n                  </span>\n                </div>\n                <div className=\"flex items-center gap-2\">\n                  <span className=\"text-base font-semibold tabular-nums text-foreground\">\n                    {pct.toFixed(1)}%\n                  </span>\n                  <div className=\"flex h-1.5 flex-1 overflow-hidden rounded-full bg-foreground/10\">\n                    <div style={{ width: `${pct}%`, backgroundColor: sec.color }} />\n                  </div>\n                </div>\n              </div>\n\n              <div className=\"flex max-h-[560px] flex-col overflow-y-auto px-2 pb-2\">\n                <div\n                  className={`sticky top-0 z-10 grid items-center gap-2 bg-card px-1 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70 ${cols}`}\n                >\n                  <span>Hand</span>\n                  <span className=\"text-right\">Freq %</span>\n                  {hasEv ? (\n                    <>\n                      <span className=\"text-right\">EV bb</span>\n                      <span className=\"text-right\">Diff bb</span>\n                    </>\n                  ) : null}\n                </div>\n                {shown.length === 0 ? (\n                  <p className=\"py-6 text-center text-xs text-muted-foreground\">\n                    No hands match {query ? \"this search\" : \"these filters\"}.\n                  </p>\n                ) : (\n                  shown.map((r) => (\n                    <div\n                      key={r.key}\n                      className={`grid items-center gap-2 rounded px-1 py-[3px] hover:bg-accent/40 ${cols}`}\n                      // Keeps thousands of rows cheap to scroll.\n                      style={{ contentVisibility: \"auto\", containIntrinsicSize: \"auto 30px\" }}\n                    >\n                      <HandCards id={r.key} cards={r.cards} />\n                      <span className=\"text-right text-[11px] tabular-nums text-foreground\">\n                        {Math.round(r.freq * 100)}\n                      </span>\n                      {hasEv ? (\n                        <>\n                          <span className=\"text-right text-[11px] tabular-nums text-foreground\">\n                            {r.evBb === null ? \"—\" : r.evBb.toFixed(2)}\n                          </span>\n                          <span\n                            className={`text-right text-[11px] tabular-nums ${\n                              r.evDiffBb === null\n                                ? \"text-muted-foreground/60\"\n                                : r.evDiffBb >= 0\n                                  ? \"text-emerald-500\"\n                                  : \"text-rose-500\"\n                            }`}\n                          >\n                            {r.evDiffBb === null\n                              ? \"—\"\n                              : `${r.evDiffBb >= 0 ? \"+\" : \"\"}${r.evDiffBb.toFixed(2)}`}\n                          </span>\n                        </>\n                      ) : null}\n                    </div>\n                  ))\n                )}\n                {!isOpen && sec.rows.length > SECTION_PREVIEW ? (\n                  <button\n                    type=\"button\"\n                    onClick={() => setExpanded((prev) => new Set(prev).add(sec.key))}\n                    className=\"mx-1 my-1 self-start rounded-full border border-border px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                  >\n                    Show all {sec.rows.length.toLocaleString(\"en-US\")} ↓\n                  </button>\n                ) : null}\n              </div>\n            </section>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\nconst RANK_ORDER = \"23456789TJQKA\";\nconst SUIT_ORDER = \"shdc\";\n\n/** Highest rank on the left, lowest on the right (GTO Wizard's order), ties\n *  by suit so paired cards keep a stable colour order. Same rule as the\n *  PLO5/PLO6 lists (`cardsOf` in plo5-range-panel). */\nfunction highFirst(cards: string[]): string[] {\n  return [...cards].sort(\n    (a, b) =>\n      RANK_ORDER.indexOf(b[0]) - RANK_ORDER.indexOf(a[0]) ||\n      SUIT_ORDER.indexOf(a[1]) - SUIT_ORDER.indexOf(b[1]),\n  );\n}\n\n/** A hand's cards, high first, as miniature app card faces. */\nfunction HandCards({ id, cards }: { id: string; cards: string[] }) {\n  return (\n    <div className=\"flex items-center gap-[3px]\">\n      {highFirst(cards).map((card, i) => (\n        <MiniCard key={`${id}-${i}`} card={card} className=\"h-[26px] w-5 text-base\" />\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/plo-range-list.tsx"
    },
    {
      "path": "src/components/explorer/plo4hu-postflop.tsx",
      "content": "\"use client\";\n\n// Heads-up PLO4 postflop in the Explorer. The flop is the MonkerSolver\n// postflop blueprint itself (looked up, not solved); every turn card re-solves\n// the turn from the ranges the blueprint reaches there, and every river card\n// re-solves the river exactly, hand by hand (the engine is solver-engine's\n// PLO4 heads-up explorer service, see `@/lib/explorer/plo4hu-postflop`).\n//\n// The rail continues the preflop seat strip: a street card per board, then one\n// decision card per action taken, the acting card last. Below it, the acting\n// range's sample in the preflop Explorer's per-action columns (search, chips,\n// freq / EV / diff per hand).\n//\n// ui-exception: the decision rail and the per-hand strategy rows match the\n// preflop rail cards this view continues (`preflop-browser.tsx`); no App UI\n// block renders a poker action tree.\n\nimport { explorerHost } from \"@/lib/explorer/host\";\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { Loader2 } from \"lucide-react\";\nimport { MiniCard } from \"@/components/trainer/cards\";\nimport { actionColor } from \"@/lib/pokerstudy/poker\";\nimport { handProps } from \"@/lib/explorer/plo-filter\";\nimport { streetBetPotPct } from \"@/lib/explorer/bet-size\";\nimport { cardsToPloString } from \"@/lib/trainer/plo-hand\";\nimport type { Card } from \"@/lib/trainer/hand\";\nimport { PloActionBreakdown, type BreakdownRow, type BreakdownSection } from \"./plo-range-list\";\nimport { BottomSheet } from \"./bottom-sheet\";\nimport { CardGridPicker } from \"./card-picker\";\nimport { RailRow } from \"./rail-row\";\n\ntype Next = \"action\" | \"deal\" | \"fold\" | \"allin\" | \"showdown\";\n\ninterface NodeSummary {\n  path: string[];\n  player: 0 | 1;\n  actions: { label: string; freq: number; next: Next }[];\n  combos: number;\n}\n\ninterface Street {\n  id: string;\n  status: \"queued\" | \"running\" | \"done\" | \"failed\" | \"missing\" | \"lost\";\n  board?: string;\n  pot?: number;\n  stack?: number;\n  nodes?: NodeSummary[];\n  error?: string;\n  elapsed?: number;\n  exploitability_pct?: number;\n  /** \"blueprint\" for the flop looked up from the Monker blueprint. */\n  source?: string;\n  /** True when the street was solved per hand, without grouping. */\n  exact?: boolean;\n}\n\ninterface NodeDetail {\n  path: string[];\n  player: 0 | 1;\n  actions: string[];\n  range_freqs: number[];\n  combos: number;\n  hands: { combo: string; reach: number; freqs: number[]; evs: number[] | null }[];\n}\n\n/** The host's heads-up PLO4 postflop routes (the Explorer only mounts this\n *  panel where the host serves them). */\nconst api = () => explorerHost().plo4huPostflop ?? \"/api/explorer/plo4hu-postflop\";\n/** Solver player 0 is out of position: the big blind, heads-up. */\nconst SEAT = [\"BB\", \"SB\"] as const;\nconst STREET_NAME = [\"Flop\", \"Turn\", \"River\"];\n\nfunction kindOf(label: string): \"fold\" | \"check\" | \"call\" | \"raise\" | \"allin\" {\n  const k = label.split(\" \")[0];\n  if (k === \"Fold\") return \"fold\";\n  if (k === \"Check\") return \"check\";\n  if (k === \"Call\") return \"call\";\n  if (k === \"AllIn\") return \"allin\";\n  return \"raise\";\n}\n\nfunction colorOf(label: string): string {\n  return actionColor(kindOf(label), label);\n}\n\n/** \"Bet 1\" → \"Bet 1bb\"; amounts are the chips the action puts in. */\nfunction display(label: string): string {\n  const [k, amt] = label.split(\" \");\n  const name = k === \"AllIn\" ? \"All-in\" : k;\n  return amt ? `${name} ${amt}bb` : name;\n}\n\n/**\n * \"Bet 3\" with the street's pot 6 → \"Bet 50%\": bets and raises read as a\n * percentage of the pot, GTO Wizard style (`@/lib/explorer/bet-size`). Falls\n * back to the chip amount when the pot isn't known yet. `prior` is the\n * street's actions before this one.\n */\nfunction sizeLabel(label: string, prior: string[], pot: number | undefined): string {\n  const pct = pot === undefined ? null : streetBetPotPct(pot, prior, label);\n  return pct === null ? display(label) : `${label.split(\" \")[0]} ${pct}%`;\n}\n\nfunction cardsOf(s: string): string[] {\n  const out: string[] = [];\n  for (let i = 0; i + 1 < s.length; i += 2) out.push(s.slice(i, i + 2));\n  return out;\n}\n\nasync function json<T>(res: Response): Promise<T> {\n  const body = await res.json().catch(() => ({}));\n  if (!res.ok) throw new Error((body as { error?: string }).error ?? `request failed (${res.status})`);\n  return body as T;\n}\n\n/** Poll a street until it is solved (or fails); solved streets land in `onDone`. */\nfunction useStreet(id: string | null, onDone: (s: Street) => void): Street | null {\n  const [street, setStreet] = useState<Street | null>(null);\n  const doneRef = useRef(onDone);\n  useEffect(() => {\n    doneRef.current = onDone;\n  });\n  useEffect(() => {\n    if (!id) return;\n    let cancelled = false;\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const tick = async () => {\n      try {\n        const s = await json<Street>(await fetch(`${api()}/${id}`, { cache: \"no-store\" }));\n        if (cancelled) return;\n        setStreet(s);\n        if (s.status === \"done\") doneRef.current(s);\n        if (s.status === \"queued\" || s.status === \"running\") timer = setTimeout(tick, 2500);\n      } catch (e) {\n        if (cancelled) return;\n        setStreet({ id, status: \"failed\", error: e instanceof Error ? e.message : \"failed\" });\n      }\n    };\n    tick();\n    return () => {\n      cancelled = true;\n      if (timer) clearTimeout(timer);\n    };\n  }, [id]);\n  // A street that hasn't answered yet reads as queued.\n  if (!id) return null;\n  return street?.id === id ? street : { id, status: \"queued\" };\n}\n\nconst RAIL_CARD = \"flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border p-2\";\n\nexport function Plo4HuPostflop({\n  stack,\n  line,\n  flop,\n  pot,\n  effStack,\n  stripPrefix,\n  stripLead,\n  onRepickFlop,\n}: {\n  stack: number;\n  /** The closed preflop line, e.g. \"SB_Limp_BB_Check\". */\n  line: string;\n  flop: string[];\n  pot: number;\n  effStack: number;\n  /** The preflop seat cards, so the rail reads as one continuous line. */\n  stripPrefix?: ReactNode;\n  /** The game card, pinned left of the rail (above it on phones). */\n  stripLead?: ReactNode;\n  onRepickFlop: () => void;\n}) {\n  // One entry per street: its solve id and the actions taken on it. Keyed by\n  // the spot, so a different flop or line starts over.\n  const spotKey = `${stack}|${line}|${flop.join(\"\")}|${pot}|${effStack}`;\n  const [state, setState] = useState<{ key: string; streets: { id: string; path: string[] }[]; error: string | null }>({\n    key: \"\",\n    streets: [],\n    error: null,\n  });\n  const fresh = state.key === spotKey;\n  const streets = useMemo(() => (fresh ? state.streets : []), [fresh, state.streets]);\n  const startError = fresh ? state.error : null;\n  const setStreets = (f: (ss: { id: string; path: string[] }[]) => { id: string; path: string[] }[]) =>\n    setState((st) => ({ ...st, streets: f(st.streets) }));\n  const setStartError = (error: string | null) => setState((st) => ({ ...st, error }));\n  const [picker, setPicker] = useState(false);\n  const [dealing, setDealing] = useState(false);\n\n  useEffect(() => {\n    let cancelled = false;\n    (async () => {\n      try {\n        const r = await json<{ id: string }>(\n          await fetch(api(), {\n            method: \"POST\",\n            headers: { \"Content-Type\": \"application/json\" },\n            body: JSON.stringify({ stack, line, board: flop.join(\"\"), pot, effStack }),\n          }),\n        );\n        if (!cancelled) setState({ key: spotKey, streets: [{ id: r.id, path: [] }], error: null });\n      } catch (e) {\n        if (!cancelled)\n          setState({ key: spotKey, streets: [], error: e instanceof Error ? e.message : \"Could not start the solve.\" });\n      }\n    })();\n    return () => {\n      cancelled = true;\n    };\n  }, [spotKey, stack, line, flop, pot, effStack]);\n\n  const last = streets.length - 1;\n  // Earlier streets are done by construction; keep their summaries.\n  const [done, setDone] = useState<Record<string, Street>>({});\n  const current = useStreet(streets[last]?.id ?? null, (s) => setDone((d) => ({ ...d, [s.id]: s })));\n  const streetData = (i: number): Street | null =>\n    done[streets[i]?.id] ?? (i === last ? current : null);\n\n  const choose = (si: number, depth: number, label: string) => {\n    setStreets((ss) => {\n      const next = ss.slice(0, si + 1);\n      next[si] = { ...next[si], path: [...next[si].path.slice(0, depth), label] };\n      return next;\n    });\n  };\n  const rewind = (si: number, depth: number) => {\n    setStreets((ss) => {\n      const next = ss.slice(0, si + 1);\n      next[si] = { ...next[si], path: next[si].path.slice(0, depth) };\n      return next;\n    });\n  };\n\n  // Where the line stands: the live node, or what the last action led to.\n  const lastStreet = streetData(last);\n  const lastPath = streets[last]?.path ?? [];\n  const nodeMap = useMemo(() => {\n    const m = new Map<string, NodeSummary>();\n    for (const n of lastStreet?.nodes ?? []) m.set(n.path.join(\"|\"), n);\n    return m;\n  }, [lastStreet]);\n  const liveNode = lastStreet?.status === \"done\" ? nodeMap.get(lastPath.join(\"|\")) : undefined;\n  const parentNode =\n    lastPath.length > 0 ? nodeMap.get(lastPath.slice(0, -1).join(\"|\")) : undefined;\n  const lastNext = parentNode?.actions.find((a) => a.label === lastPath[lastPath.length - 1])?.next;\n  const boardNow = lastStreet?.board ? cardsOf(lastStreet.board) : flop;\n\n  const deal = async (card: string) => {\n    const s = streets[last];\n    setPicker(false);\n    setDealing(true);\n    try {\n      const r = await json<{ id: string }>(\n        await fetch(`${api()}/${s.id}/deal`, {\n          method: \"POST\",\n          headers: { \"Content-Type\": \"application/json\" },\n          body: JSON.stringify({ path: s.path, card }),\n        }),\n      );\n      setStreets((ss) => [...ss, { id: r.id, path: [] }]);\n    } catch (e) {\n      setStartError(e instanceof Error ? e.message : \"Could not deal that card.\");\n    } finally {\n      setDealing(false);\n    }\n  };\n\n  const railRef = useRef<HTMLDivElement>(null);\n  useEffect(() => {\n    const el = railRef.current;\n    if (el) el.scrollLeft = el.scrollWidth;\n  }, [streets, current?.status]);\n\n  const rail: ReactNode[] = [];\n  streets.forEach((s, si) => {\n    const data = streetData(si);\n    const board = data?.board ? cardsOf(data.board) : si === 0 ? flop : [];\n    rail.push(\n      <StreetCard\n        key={`street-${si}`}\n        name={STREET_NAME[si] ?? \"Street\"}\n        cards={si === 0 ? board : board.slice(-1)}\n        pot={data?.pot}\n        onClick={si === 0 ? onRepickFlop : () => rewind(si - 1, streets[si - 1].path.length)}\n        title={si === 0 ? \"Re-pick the flop\" : \"Re-pick this card\"}\n      />,\n    );\n    if (!data || data.status !== \"done\") return;\n    const map = new Map((data.nodes ?? []).map((n) => [n.path.join(\"|\"), n]));\n    for (let d = 0; d <= s.path.length; d++) {\n      const n = map.get(s.path.slice(0, d).join(\"|\"));\n      if (!n) break;\n      const chosen = s.path[d];\n      rail.push(\n        <DecisionCard\n          key={`n-${si}-${d}`}\n          node={n}\n          pot={data.pot}\n          chosen={chosen}\n          live={chosen === undefined && si === last}\n          onPick={(label) => choose(si, d, label)}\n          onRewind={() => rewind(si, d)}\n        />,\n      );\n    }\n  });\n  const solving =\n    dealing || (current && (current.status === \"queued\" || current.status === \"running\"));\n  if (solving) {\n    rail.push(\n      <div key=\"solving\" className={`${RAIL_CARD} items-center justify-center border-border bg-card/40 text-center`}>\n        <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n        <span className=\"text-[11px] text-muted-foreground\">\n          {current?.status === \"running\" ? `Solving… ${Math.round(current.elapsed ?? 0)}s` : \"Queued…\"}\n        </span>\n      </div>,\n    );\n  } else if (lastNext === \"deal\" && boardNow.length < 5) {\n    rail.push(\n      // ui-exception: the next-street card is a rail card like the preflop strip's FLOP card\n      <button\n        key=\"pick\"\n        type=\"button\"\n        onClick={() => setPicker(true)}\n        className={`${RAIL_CARD} items-center justify-center border-dashed border-foreground/40 bg-accent/30 text-center`}\n      >\n        <span className=\"text-[10px] uppercase tracking-wide text-zinc-500\">\n          {STREET_NAME[streets.length] ?? \"Card\"}\n        </span>\n        <span className=\"text-xs text-muted-foreground\">pick a card ↓</span>\n      </button>,\n    );\n  }\n\n  const endText =\n    lastNext === \"fold\"\n      ? \"Hand over: a fold ends it.\"\n      : lastNext === \"allin\"\n        ? \"All-in and called: no more decisions.\"\n        : lastNext === \"showdown\"\n          ? \"River closed: showdown.\"\n          : null;\n\n  return (\n    <div className=\"flex flex-col gap-4\">\n      <RailRow lead={stripLead} scrollerRef={railRef}>\n        {stripPrefix}\n        {rail}\n      </RailRow>\n\n      {startError ? <p className=\"text-xs text-destructive\">{startError}</p> : null}\n      {current?.status === \"failed\" || current?.status === \"lost\" ? (\n        <p className=\"text-xs text-destructive\">\n          {current.error ?? \"The solve stopped. Pick the card again to retry.\"}\n        </p>\n      ) : null}\n      {endText ? (\n        <div className=\"rounded-xl border border-border bg-card/40 px-4 py-3 text-sm text-muted-foreground\">\n          {endText}\n        </div>\n      ) : null}\n      {solving && streets.length <= 1 ? (\n        <p className=\"text-xs text-muted-foreground\">\n          Loading the blueprint&apos;s flop strategy for this line.\n        </p>\n      ) : null}\n\n      {liveNode && streets[last] ? (\n        <NodePanel\n          key={`${streets[last].id}:${lastPath.join(\"|\")}`}\n          id={streets[last].id}\n          path={lastPath}\n          summary={liveNode}\n          street={lastStreet}\n          streetName={STREET_NAME[last] ?? \"\"}\n          board={boardNow}\n        />\n      ) : null}\n\n      {picker ? (\n        <BottomSheet title={`Pick the ${(STREET_NAME[streets.length] ?? \"card\").toLowerCase()}`} onClose={() => setPicker(false)}>\n          <CardGridPicker value={[]} max={1} dead={boardNow} onChange={(next) => next[0] && deal(next[0])} />\n          <span className=\"pb-2 text-[11px] text-muted-foreground/70\">\n            {streets.length >= 2\n              ? \"The river is solved exactly, hand by hand, from the ranges the turn reaches here. It takes about half a minute.\"\n              : \"The turn is re-solved from the ranges the blueprint reaches here. It takes about half a minute.\"}\n          </span>\n        </BottomSheet>\n      ) : null}\n    </div>\n  );\n}\n\nfunction StreetCard({\n  name,\n  cards,\n  pot,\n  onClick,\n  title,\n}: {\n  name: string;\n  cards: string[];\n  pot?: number;\n  onClick: () => void;\n  title: string;\n}) {\n  return (\n    // ui-exception: street card in the decision rail, matching the preflop strip's FLOP card\n    <button\n      type=\"button\"\n      onClick={onClick}\n      title={title}\n      className={`${RAIL_CARD} border-border bg-card/40 text-left transition-colors hover:border-foreground/30`}\n    >\n      <span className=\"text-[10px] uppercase tracking-wide text-zinc-500\">{name}</span>\n      <div className=\"mt-auto flex flex-wrap items-center gap-1\">\n        {cards.map((c) => (\n          <MiniCard key={c} card={c} className=\"h-8 w-6 text-xl\" />\n        ))}\n      </div>\n      {pot !== undefined ? (\n        <span className=\"text-[11px] text-muted-foreground tabular-nums\">pot {pot.toFixed(1)}bb</span>\n      ) : null}\n    </button>\n  );\n}\n\nfunction DecisionCard({\n  node,\n  pot,\n  chosen,\n  live,\n  onPick,\n  onRewind,\n}: {\n  node: NodeSummary;\n  /** The street's starting pot, for sizes as % of pot. */\n  pot?: number;\n  chosen?: string;\n  live: boolean;\n  onPick: (label: string) => void;\n  onRewind: () => void;\n}) {\n  return (\n    // ui-exception: like the preflop rail, the card is \"go back here\" and\n    // holds its own option buttons, so it is a keyboard-operable div.\n    <div\n      role=\"button\"\n      tabIndex={0}\n      onClick={onRewind}\n      onKeyDown={(e) => {\n        if (e.target !== e.currentTarget) return;\n        if (e.key === \"Enter\" || e.key === \" \") {\n          e.preventDefault();\n          onRewind();\n        }\n      }}\n      title={`Back to ${SEAT[node.player]}'s decision`}\n      className={`${RAIL_CARD} cursor-pointer ${live ? \"border-foreground/50 bg-accent/50\" : \"border-border bg-card/40\"}`}\n    >\n      <span className={`text-sm font-semibold ${live ? \"text-foreground\" : \"text-muted-foreground\"}`}>\n        {SEAT[node.player]}\n      </span>\n      <div className=\"flex flex-col\">\n        {node.actions.map((a) => {\n          const isChosen = a.label === chosen;\n          const text = sizeLabel(a.label, node.path, pot);\n          const chips = display(a.label);\n          return (\n            // ui-exception: an option row inside a rail card, as on the preflop rail\n            <button\n              key={a.label}\n              type=\"button\"\n              onClick={(e) => {\n                e.stopPropagation();\n                onPick(a.label);\n              }}\n              aria-pressed={isChosen || undefined}\n              title={text === chips ? undefined : chips}\n              className={`flex items-center justify-between gap-1 rounded px-1 py-0.5 text-left transition-colors ${\n                isChosen\n                  ? \"bg-foreground/15 ring-1 ring-foreground/25\"\n                  : chosen !== undefined\n                    ? \"opacity-45 hover:bg-accent hover:opacity-100\"\n                    : \"hover:bg-accent\"\n              }`}\n            >\n              <span className=\"flex min-w-0 items-center gap-1 truncate text-xs text-foreground\">\n                <span className=\"size-2 shrink-0 rounded-[2px]\" style={{ backgroundColor: colorOf(a.label) }} />\n                <span className={`truncate ${isChosen ? \"font-semibold\" : \"\"}`}>{text}</span>\n              </span>\n              <span className=\"shrink-0 text-[11px] font-semibold text-foreground tabular-nums\">\n                {(a.freq * 100).toFixed(0)}%\n              </span>\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\n/** The acting range's sample as per-action columns, the preflop Explorer's layout. */\nfunction breakdownOf(detail: NodeDetail, summary: NodeSummary, pot: number | undefined): BreakdownSection[] {\n  const labels = summary.actions.map((a) => a.label);\n  const hands = detail.hands.map((h) => {\n    const cards = cardsOf(h.combo);\n    return { h, cards, props: handProps(cardsToPloString(cards as [Card, Card, Card, Card])) };\n  });\n  return labels.map((label, i) => {\n    const rows: (BreakdownRow & { reach: number })[] = [];\n    for (const { h, cards, props } of hands) {\n      const freq = h.freqs[i] ?? 0;\n      if (freq <= 0.0005) continue;\n      const ev = h.evs ? h.evs[i] : null;\n      let bestOther: number | null = null;\n      if (h.evs) {\n        h.evs.forEach((e, j) => {\n          if (j !== i && (bestOther === null || e > bestOther)) bestOther = e;\n        });\n      }\n      rows.push({\n        key: h.combo,\n        cards,\n        freq,\n        evBb: ev,\n        evDiffBb: ev === null || bestOther === null ? null : ev - bestOther,\n        props,\n        reach: h.reach,\n        weight: freq * h.reach,\n      });\n    }\n    rows.sort(\n      (a, b) => (b.evBb ?? -Infinity) - (a.evBb ?? -Infinity) || b.freq - a.freq || b.reach - a.reach,\n    );\n    // Size as % of pot, with the chips alongside: \"Bet 50% · 3bb\".\n    const text = sizeLabel(label, summary.path, pot);\n    const chips = display(label);\n    const header = text === chips ? chips : `${text} · ${chips.split(\" \")[1]}`;\n    return { key: label, label: header, color: colorOf(label), pct: summary.actions[i].freq * 100, rows };\n  });\n}\n\nfunction NodePanel({\n  id,\n  path,\n  summary,\n  street,\n  streetName,\n  board,\n}: {\n  id: string;\n  path: string[];\n  summary: NodeSummary;\n  street: Street | null;\n  streetName: string;\n  board: string[];\n}) {\n  const [detail, setDetail] = useState<NodeDetail | null>(null);\n  const [error, setError] = useState<string | null>(null);\n\n  useEffect(() => {\n    let cancelled = false;\n    const qs = encodeURIComponent(path.join(\",\"));\n    fetch(`${api()}/${id}/node?path=${qs}`)\n      .then((r) => json<NodeDetail>(r))\n      .then((d) => {\n        if (!cancelled) setDetail(d);\n      })\n      .catch((e: unknown) => {\n        if (!cancelled) setError(e instanceof Error ? e.message : \"Could not load the hands.\");\n      });\n    return () => {\n      cancelled = true;\n    };\n  }, [id, path]);\n\n  const sections = useMemo(() => (detail ? breakdownOf(detail, summary, street?.pot) : null), [detail, summary, street?.pot]);\n\n  return (\n    <div className=\"flex flex-col gap-3 rounded-xl border border-border bg-card/40 p-4\">\n      <div className=\"flex flex-wrap items-baseline justify-between gap-2\">\n        <h3 className=\"text-sm font-semibold text-foreground\">\n          {SEAT[summary.player]} to act · {streetName}\n          {street?.pot !== undefined ? ` · pot ${street.pot.toFixed(1)}bb` : \"\"}\n        </h3>\n      </div>\n\n      {error ? <p className=\"text-xs text-destructive\">{error}</p> : null}\n      {!detail && !error ? (\n        <div className=\"flex h-24 items-center justify-center\">\n          <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n        </div>\n      ) : null}\n      {detail && sections ? (\n        <PloActionBreakdown sections={sections} board={board} sampleOf={detail.hands.length} />\n      ) : null}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/plo4hu-postflop.tsx"
    },
    {
      "path": "src/components/explorer/plo5-range-panel.tsx",
      "content": "\"use client\";\n\n// PLO5 Explorer body. Pool % on the headers; the hand list is a top-by-EV\n// slice of each action's HDV CSV (204k classes — never dumped whole).\n\nimport { useEffect, useMemo, useState, type ReactNode } from \"react\";\nimport { Loader2 } from \"lucide-react\";\n\nimport { MiniCard } from \"@/components/trainer/cards\";\nimport {\n  canonicalPlo5Hand,\n  encodePlo5RankFilter,\n  parsePlo5RankFilter,\n} from \"@/lib/plo5-ranges/canonical\";\nimport {\n  canonicalPlo6Hand,\n  encodePlo6RankFilter,\n  parsePlo6RankFilter,\n} from \"@/lib/plo6-ranges/canonical\";\nimport {\n  getPlo5HandStrategy,\n  getPlo5NodeList,\n  getPlo6HuHandStrategy,\n  getPlo6HuNodeList,\n  labelForAction,\n  sortActionsForDisplay,\n  type NodeAction,\n  type Plo5ActionList,\n  type Plo5HandStrategy,\n  type Plo5ListedHand,\n} from \"@/lib/solver/preflop\";\n\nimport { colorActions, type PreflopActionItem } from \"./preflop-strategy-grid\";\nimport { ExplorerTabs } from \"./explorer-tabs\";\nimport { useExplorerUrl } from \"./explorer-url\";\nimport { PloRangeList } from \"./plo-range-list\";\nimport { Plo6BucketBars } from \"./plo6-bucket-bars\";\n\nconst LIST_PAGE = 200;\n\n/** Seat-card aggregates from pool % (0–100), not per-hand weights. */\nexport function plo5ActionItems(actions: NodeAction[], stack: number): PreflopActionItem[] {\n  const colored = colorActions(sortActionsForDisplay(actions));\n  const denom = colored.reduce((s, { action }) => s + (action.poolPct ?? 0), 0) || 1;\n  return colored.map(({ action, color }) => ({\n    action,\n    label: labelForAction(action, stack),\n    color,\n    freq: (action.poolPct ?? 0) / denom,\n    combos: action.combos ?? 0,\n  }));\n}\n\nexport function cardsOf(hand: string): string[] {\n  const compact = hand.replace(/[\\s,]+/g, \"\");\n  const out: string[] = [];\n  for (let i = 0; i + 1 < compact.length; i += 2) {\n    out.push(compact[i].toUpperCase() + compact[i + 1].toLowerCase());\n  }\n  // High rank first (aces on the left), ties by suit.\n  return out.sort(\n    (a, b) => RANKS.indexOf(b[0]) - RANKS.indexOf(a[0]) || SUITS.indexOf(a[1]) - SUITS.indexOf(b[1]),\n  );\n}\n\nconst RANKS = \"23456789TJQKA\";\nconst SUITS = \"shdc\";\n\nexport function HandCards({ hand }: { hand: string }) {\n  return (\n    <div className=\"flex items-center gap-[3px]\">\n      {cardsOf(hand).map((card, i) => (\n        <MiniCard key={`${hand}-${i}`} card={card} className=\"h-[26px] w-5 text-base\" />\n      ))}\n    </div>\n  );\n}\n\ntype HdvVariant = {\n  parseFilter: (q: string) => Record<string, number> | null;\n  encodeFilter: (f: Record<string, number>) => string;\n  canonical: (q: string) => string | null;\n  fetchList: (\n    stack: number,\n    history: string,\n    limit: number,\n    ranks?: string,\n  ) => Promise<Plo5ActionList[]>;\n  fetchStrategy: (\n    stack: number,\n    history: string,\n    hand: string,\n  ) => Promise<Plo5HandStrategy>;\n  placeholder: string;\n  help: ReactNode;\n  lookupError: string;\n};\n\nconst PLO5_VARIANT: HdvVariant = {\n  parseFilter: parsePlo5RankFilter,\n  encodeFilter: encodePlo5RankFilter,\n  canonical: canonicalPlo5Hand,\n  fetchList: getPlo5NodeList,\n  fetchStrategy: getPlo5HandStrategy,\n  placeholder: \"AK222 or AsAhKdKcQs\",\n  help: (\n    <>\n      Filter by ranks (<span className=\"font-mono text-foreground\">AK222</span>\n      ) or look up a combo (\n      <span className=\"font-mono text-foreground\">AsAhKdKcQs</span>\n      ). Five ranks match that bag exactly; fewer ranks mean “at least these.”\n    </>\n  ),\n  lookupError: \"Use ranks (AK222) or five suited cards (AsAhKdKcQs).\",\n};\n\nconst PLO6HU_VARIANT: HdvVariant = {\n  parseFilter: parsePlo6RankFilter,\n  encodeFilter: encodePlo6RankFilter,\n  canonical: canonicalPlo6Hand,\n  fetchList: getPlo6HuNodeList,\n  fetchStrategy: getPlo6HuHandStrategy,\n  placeholder: \"AAKKQJ or AsAhKdKcQsQh\",\n  help: (\n    <>\n      Filter by ranks (<span className=\"font-mono text-foreground\">AAKKQJ</span>\n      ) or look up a six-card combo (\n      <span className=\"font-mono text-foreground\">AsAhKdKcQsQh</span>\n      ). Six ranks match that bag exactly; fewer ranks mean “at least these.”\n    </>\n  ),\n  lookupError: \"Use ranks (AAKKQJ) or six suited cards (AsAhKdKcQsQh).\",\n};\n\nconst HDV_BY_GAME = {\n  plo5: PLO5_VARIANT,\n  plo6hu: PLO6HU_VARIANT,\n} as const;\n\n/** One explorer for 4-, 5-, and 6-card Omaha. Buckets render when that game\n *  has a stored category tree; otherwise the Buckets tab says coming soon. */\nexport function PloExplorer({\n  game,\n  actions,\n  stack,\n  history,\n}: {\n  game: \"plo\" | \"plo5\" | \"plo6hu\";\n  actions: NodeAction[];\n  stack: number;\n  history: string;\n}) {\n  const variant = game === \"plo\" ? null : HDV_BY_GAME[game];\n  const colored = colorActions(sortActionsForDisplay(actions));\n  return (\n    <ExplorerTabs\n      buckets={\n        game === \"plo6hu\" ? (\n          <Plo6BucketBars history={history} stack={stack} actions={colored} />\n        ) : undefined\n      }\n      explorer={\n        variant ? (\n          <HdvRangePanel actions={actions} stack={stack} history={history} variant={variant} />\n        ) : (\n          <PloRangeList actions={actions} stack={stack} />\n        )\n      }\n    />\n  );\n}\n\nfunction HdvRangePanel({\n  actions,\n  stack,\n  history,\n  variant,\n}: {\n  actions: NodeAction[];\n  stack: number;\n  history: string;\n  variant: HdvVariant;\n}) {\n  const colored = colorActions(sortActionsForDisplay(actions));\n  const denom = colored.reduce((s, { action }) => s + (action.poolPct ?? 0), 0) || 1;\n  // A rank filter is part of the shareable URL (?q=AK222); a single-hand\n  // lookup isn't, since it only runs on submit.\n  const url = useExplorerUrl();\n  const [query, setQuery] = useState(() => url.get(\"q\") ?? \"\");\n  const [lookup, setLookup] = useState<Plo5HandStrategy | null>(null);\n  const [busy, setBusy] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n  const [listed, setListed] = useState<Plo5ActionList[] | null>(null);\n  const [listLimit, setListLimit] = useState(LIST_PAGE);\n  const [listBusy, setListBusy] = useState(false);\n  const [listError, setListError] = useState<string | null>(null);\n\n  const rankKey = useMemo(() => {\n    const f = variant.parseFilter(query);\n    return f ? variant.encodeFilter(f) : \"\";\n  }, [query, variant]);\n  const [debouncedRanks, setDebouncedRanks] = useState(rankKey);\n  useEffect(() => {\n    const t = window.setTimeout(() => setDebouncedRanks(rankKey), 250);\n    return () => window.clearTimeout(t);\n  }, [rankKey]);\n  useEffect(() => {\n    url.set({ q: debouncedRanks || null });\n  }, [debouncedRanks, url]);\n\n  useEffect(() => {\n    let cancelled = false;\n    setListed(null);\n    setListLimit(LIST_PAGE);\n    setListError(null);\n    setListBusy(true);\n    variant.fetchList(stack, history, LIST_PAGE, debouncedRanks || undefined)\n      .then((rows) => {\n        if (!cancelled) setListed(rows);\n      })\n      .catch((err) => {\n        if (!cancelled) setListError(err instanceof Error ? err.message : \"Could not load hands.\");\n      })\n      .finally(() => {\n        if (!cancelled) setListBusy(false);\n      });\n    return () => {\n      cancelled = true;\n    };\n  }, [stack, history, debouncedRanks, variant]);\n\n  const loadMore = async () => {\n    const next = Math.min(listLimit + LIST_PAGE, 2000);\n    setListBusy(true);\n    setListError(null);\n    try {\n      setListed(await variant.fetchList(stack, history, next, debouncedRanks || undefined));\n      setListLimit(next);\n    } catch (err) {\n      setListError(err instanceof Error ? err.message : \"Could not load more hands.\");\n    } finally {\n      setListBusy(false);\n    }\n  };\n\n  const runLookup = async () => {\n    const hand = query.trim();\n    if (!hand) return;\n    if (!variant.canonical(hand)) {\n      setLookup(null);\n      if (variant.parseFilter(hand)) {\n        setError(null);\n        return;\n      }\n      setError(variant.lookupError);\n      return;\n    }\n    setBusy(true);\n    setError(null);\n    try {\n      setLookup(await variant.fetchStrategy(stack, history, hand));\n    } catch (err) {\n      setLookup(null);\n      setError(err instanceof Error ? err.message : \"Lookup failed.\");\n    } finally {\n      setBusy(false);\n    }\n  };\n\n  const queryBar = (\n    <>\n      <p className=\"text-xs text-muted-foreground\">{variant.help}</p>\n\n      <form\n        className=\"flex flex-wrap items-center gap-2\"\n        onSubmit={(e) => {\n          e.preventDefault();\n          void runLookup();\n        }}\n      >\n        <input\n          value={query}\n          onChange={(e) => setQuery(e.target.value)}\n          placeholder={variant.placeholder}\n          spellCheck={false}\n          className=\"h-8 min-w-[180px] flex-1 rounded-md border border-border bg-background px-2.5 font-mono text-xs text-foreground\"\n        />\n        <button\n          type=\"submit\"\n          disabled={busy || !query.trim()}\n          className=\"inline-flex h-8 items-center gap-1.5 rounded-md border border-border bg-card px-3 text-xs font-medium text-foreground hover:bg-accent disabled:opacity-50\"\n        >\n          {busy ? <Loader2 className=\"size-3 animate-spin\" /> : null}\n          Look up\n        </button>\n      </form>\n      {error ? <p className=\"text-xs text-destructive\">{error}</p> : null}\n    </>\n  );\n\n  const rangeBody = (\n    <>\n      {lookup ? (\n        <div className=\"flex flex-col gap-2 rounded-xl border border-border bg-card/40 px-3 py-2.5\">\n          <div className=\"flex flex-wrap items-center gap-2\">\n            <HandCards hand={lookup.hdvHand} />\n            {lookup.isoMapped ? (\n              <span className=\"text-[11px] text-muted-foreground\">\n                suit-mapped from {lookup.hand}\n              </span>\n            ) : null}\n          </div>\n          <div className=\"flex flex-col\">\n            {lookup.actions.map((a) => (\n              <div\n                key={a.action}\n                className=\"flex items-center justify-between gap-3 py-0.5 text-xs\"\n              >\n                <span>{a.action.replace(/^Raise-([\\d.]+)x$/, \"Raise $1bb\")}</span>\n                <span className=\"tabular-nums text-muted-foreground\">\n                  {(a.freq * 100).toFixed(1)}%\n                  {a.ev_sb != null ? ` · ${(a.ev_sb / 2).toFixed(2)} bb` : \"\"}\n                </span>\n              </div>\n            ))}\n          </div>\n        </div>\n      ) : null}\n\n      {debouncedRanks ? (\n        <p className=\"text-xs text-muted-foreground\">\n          Filtering ranks{\" \"}\n          <span className=\"font-mono text-foreground\">{debouncedRanks}</span>\n        </p>\n      ) : null}\n      {listError ? <p className=\"text-xs text-destructive\">{listError}</p> : null}\n\n      <div className=\"grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(280px,1fr))]\">\n        {colored.map(({ action, color }) => {\n          const pct = ((action.poolPct ?? 0) / denom) * 100;\n          const block = listed?.find((a) => a.action === action.action);\n          return (\n            <HdvActionSection\n              key={action.action}\n              label={labelForAction(action, stack)}\n              color={color}\n              pct={pct}\n              rows={block?.listed ?? []}\n              total={block?.listedTotal ?? action.combos ?? 0}\n              busy={listBusy}\n              onMore={() => void loadMore()}\n            />\n          );\n        })}\n      </div>\n    </>\n  );\n\n  return (\n    <div className=\"flex flex-col gap-4\">\n      {queryBar}\n      {rangeBody}\n    </div>\n  );\n}\n\n/**\n * One action's slice of a PLO5/PLO6 range: its pool share, then the hands\n * that take it (top by EV) with each hand's frequency and EV. The Explorer\n * lays these out side by side; the replayer's Ranges column tabs between them.\n */\n/** Whole percents, but a sliver of a mix (0.3%) isn't shown as 0. */\nfunction formatFreq(freq: number): string {\n  const pct = freq * 100;\n  return pct > 0 && pct < 0.95 ? pct.toFixed(1) : String(Math.round(pct));\n}\n\nexport function HdvActionSection({\n  label,\n  color,\n  pct,\n  rows,\n  total,\n  busy,\n  onMore,\n  maxHeight = \"max-h-[560px]\",\n}: {\n  label: string;\n  color: string;\n  /** Pool share of this action, 0–100. */\n  pct: number;\n  rows: Plo5ListedHand[];\n  /** Hands that take this action at all (rows is the top slice). */\n  total: number;\n  busy: boolean;\n  onMore?: () => void;\n  /** Height cap on the hand list (Tailwind class). */\n  maxHeight?: string;\n}) {\n  const hasEv = rows.some((r) => r.ev != null);\n  const cols = hasEv\n    ? \"grid-cols-[minmax(0,1fr)_44px_52px]\"\n    : \"grid-cols-[minmax(0,1fr)_44px]\";\n  return (\n    <section className=\"flex flex-col overflow-hidden rounded-xl border border-border bg-card/40\">\n      <div\n        className=\"flex flex-col gap-1.5 px-3 py-2.5\"\n        style={{ backgroundColor: `${color}26` }}\n      >\n        <div className=\"flex items-baseline justify-between gap-2\">\n          <span className=\"text-sm font-medium text-foreground\">{label}</span>\n          <span className=\"text-[11px] tabular-nums text-muted-foreground\">\n            {total.toLocaleString(\"en-US\")} {total === 1 ? \"hand\" : \"hands\"}\n          </span>\n        </div>\n        <div className=\"flex items-center gap-2\">\n          <span className=\"text-base font-semibold tabular-nums text-foreground\">\n            {pct.toFixed(1)}%\n          </span>\n          <div className=\"flex h-1.5 flex-1 overflow-hidden rounded-full bg-foreground/10\">\n            <div style={{ width: `${pct}%`, backgroundColor: color }} />\n          </div>\n        </div>\n      </div>\n      <div className={`flex ${maxHeight} flex-col overflow-y-auto px-2 pb-2`}>\n        <div\n          className={`sticky top-0 z-10 grid items-center gap-2 bg-card px-1 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70 ${cols}`}\n        >\n          <span>Hand</span>\n          <span className=\"text-right\">Freq %</span>\n          {hasEv ? <span className=\"text-right\">EV bb</span> : null}\n        </div>\n        {busy && rows.length === 0 ? (\n          <div className=\"flex items-center gap-2 px-1 py-6 text-xs text-muted-foreground\">\n            <Loader2 className=\"size-3 animate-spin\" /> Loading hands…\n          </div>\n        ) : rows.length === 0 ? (\n          <p className=\"py-6 text-center text-xs text-muted-foreground\">\n            No hands listed for this action.\n          </p>\n        ) : (\n          rows.map((r) => (\n            <div\n              key={r.hand}\n              className={`grid items-center gap-2 rounded px-1 py-[3px] hover:bg-accent/40 ${cols}`}\n              style={{ contentVisibility: \"auto\", containIntrinsicSize: \"auto 30px\" }}\n            >\n              <HandCards hand={r.hand} />\n              <span className=\"text-right text-[11px] tabular-nums text-foreground\">\n                {formatFreq(r.freq)}\n              </span>\n              {hasEv ? (\n                <span className=\"text-right text-[11px] tabular-nums text-foreground\">\n                  {r.ev == null ? \"—\" : (r.ev / 2).toFixed(2)}\n                </span>\n              ) : null}\n            </div>\n          ))\n        )}\n        {onMore && rows.length > 0 && rows.length < total ? (\n          <button\n            type=\"button\"\n            onClick={onMore}\n            disabled={busy}\n            className=\"mx-1 my-1 self-start rounded-full border border-border px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50\"\n          >\n            {busy\n              ? \"Loading…\"\n              : `Show more (${rows.length.toLocaleString(\"en-US\")} of ${total.toLocaleString(\"en-US\")})`}\n          </button>\n        ) : null}\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/plo5-range-panel.tsx"
    },
    {
      "path": "src/components/explorer/plo6-bucket-bars.tsx",
      "content": "\"use client\";\n\n// Suit-bucket mixes for the PLO6 HU explorer. Frequencies come from the\n// stored Hydra category tree, not a live scan of the 1.8M-hand range.\n\nimport { rangesUrl } from \"@/lib/explorer/host\";\nimport { useEffect, useState } from \"react\";\nimport { ChevronRight, Loader2 } from \"lucide-react\";\n\nimport type { NodeAction } from \"@/lib/solver/preflop\";\nimport { notifyPlanRequired } from \"@/lib/access/plan-required\";\n\ntype BucketNode = {\n  label: string;\n  weight_pct: number;\n  actions: Record<string, number>;\n  children?: BucketNode[];\n};\n\ntype HeuristicsResponse = {\n  nodes?: { history: string; tree: BucketNode[] }[];\n};\n\nexport function Plo6BucketBars({\n  history,\n  stack,\n  actions,\n}: {\n  history: string;\n  stack: number;\n  actions: { action: NodeAction; color: string }[];\n}) {\n  const [tree, setTree] = useState<BucketNode[] | null>(null);\n  const [open, setOpen] = useState<Set<string>>(new Set());\n  const [error, setError] = useState<string | null>(null);\n\n  useEffect(() => {\n    let cancelled = false;\n    setTree(null);\n    setError(null);\n    setOpen(new Set());\n    const params = new URLSearchParams({\n      stack: String(stack),\n      history,\n      detail: \"full\",\n      minWeight: \"0.5\",\n    });\n    fetch(`${rangesUrl(\"plo6hu/heuristics\")}?${params}`)\n      .then(async (res) => {\n        notifyPlanRequired(res.status);\n        if (!res.ok) throw new Error(`buckets ${res.status}`);\n        return (await res.json()) as HeuristicsResponse;\n      })\n      .then((data) => {\n        if (cancelled) return;\n        setTree(data.nodes?.[0]?.tree ?? []);\n      })\n      .catch(() => {\n        if (!cancelled) setError(\"Bucket frequencies are not stored for this node.\");\n      });\n    return () => {\n      cancelled = true;\n    };\n  }, [history, stack]);\n\n  if (error) return null;\n  if (!tree) {\n    return (\n      <div className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n        <Loader2 className=\"size-3 animate-spin\" /> Loading buckets…\n      </div>\n    );\n  }\n  if (tree.length === 0) return null;\n\n  const toggle = (key: string) => {\n    setOpen((prev) => {\n      const next = new Set(prev);\n      if (next.has(key)) next.delete(key);\n      else next.add(key);\n      return next;\n    });\n  };\n\n  return (\n    <div className=\"flex flex-col gap-1\">\n      <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 pb-1 text-[10px] text-muted-foreground\">\n        {actions.map(({ action, color }) => (\n          <span key={action.action} className=\"inline-flex items-center gap-1\">\n            <span className=\"size-2 rounded-full\" style={{ backgroundColor: color }} />\n            {action.action.replace(/^Raise-([\\d.]+)x$/, \"Raise $1bb\")}\n          </span>\n        ))}\n        <span>Top row is share of the range. Nested rows are share of the group above.</span>\n      </div>\n      {tree.map((node) => (\n        <BucketRow\n          key={node.label}\n          node={node}\n          path={node.label}\n          depth={0}\n          open={open}\n          onToggle={toggle}\n          actions={actions}\n        />\n      ))}\n    </div>\n  );\n}\n\nfunction BucketRow({\n  node,\n  path,\n  depth,\n  open,\n  onToggle,\n  actions,\n}: {\n  node: BucketNode;\n  path: string;\n  depth: number;\n  open: Set<string>;\n  onToggle: (key: string) => void;\n  actions: { action: NodeAction; color: string }[];\n}) {\n  const kids = node.children?.filter((child) => child.weight_pct > 0) ?? [];\n  const expanded = open.has(path);\n  const segments = actions\n    .map(({ action, color }) => ({\n      key: action.action,\n      label: action.action.replace(/^Raise-([\\d.]+)x$/, \"Raise $1bb\"),\n      pct: node.actions[action.action] ?? 0,\n      color,\n    }))\n    .filter((segment) => segment.pct > 0);\n\n  return (\n    <div>\n      <button\n        type=\"button\"\n        onClick={() => kids.length > 0 && onToggle(path)}\n        className=\"grid w-full grid-cols-[16px_minmax(0,1.2fr)_48px_minmax(140px,1fr)] items-center gap-2 rounded px-1 py-1 text-left hover:bg-accent/40\"\n        style={{ paddingLeft: 4 + depth * 14 }}\n      >\n        <ChevronRight\n          className={`size-3.5 text-muted-foreground transition-transform ${\n            kids.length === 0 ? \"invisible\" : expanded ? \"rotate-90\" : \"\"\n          }`}\n        />\n        <span className=\"truncate text-xs text-foreground\">{node.label}</span>\n        <span className=\"text-right text-[11px] tabular-nums text-muted-foreground\">\n          {node.weight_pct.toFixed(1)}%\n        </span>\n        <span className=\"flex min-w-0 flex-col gap-0.5\">\n          <span className=\"flex h-2 overflow-hidden rounded-full bg-foreground/10\">\n            {segments.map((segment) => (\n              <span\n                key={segment.key}\n                style={{ width: `${segment.pct}%`, backgroundColor: segment.color }}\n              />\n            ))}\n          </span>\n          <span className=\"truncate text-[10px] tabular-nums text-muted-foreground\">\n            {segments.map((segment) => `${segment.label} ${segment.pct.toFixed(0)}`).join(\" · \")}\n          </span>\n        </span>\n      </button>\n      {expanded\n        ? kids.map((child) => (\n            <BucketRow\n              key={`${path}/${child.label}`}\n              node={child}\n              path={`${path}/${child.label}`}\n              depth={depth + 1}\n              open={open}\n              onToggle={onToggle}\n              actions={actions}\n            />\n          ))\n        : null}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/plo6-bucket-bars.tsx"
    },
    {
      "path": "src/components/explorer/postflop-hand-summary.tsx",
      "content": "\"use client\";\n\n// GTO-Wizard-style hand summary for a postflop decision node: one row per\n// combo the acting player can hold — the combo (suit-colored), a mini strategy\n// bar (its action split), its EV in bb when the node carries EV (solve roots\n// do; interior nodes don't), and its share of the reach-weighted range.\n// Sorted by EV when present, else by range share.\n\nimport { useMemo } from \"react\";\nimport { ACTION_COLORS } from \"@/components/solver/strategy-grid\";\nimport type { SolverActionInfo, SolverHandStrategy } from \"@/lib/solver/types\";\nimport type { ComboWeights } from \"@/lib/explorer/subgame\";\nimport { MiniCard } from \"@/components/trainer/cards\";\n\n\nfunction ComboLabel({ combo }: { combo: string }) {\n  const cards = [combo.slice(0, 2), combo.slice(2, 4)];\n  return (\n    <span className=\"inline-flex gap-0.5 text-xs font-semibold tabular-nums\">\n      {cards.map((c, i) => (\n        <MiniCard key={i} card={c} className=\"h-5 w-4 text-[13px]\" />\n      ))}\n    </span>\n  );\n}\n\ninterface Row {\n  combo: string;\n  freqs: number[];\n  weight: number;\n  ev?: number;\n}\n\nexport function PostflopHandSummary({\n  actions,\n  hands,\n  reach,\n  evByCombo,\n}: {\n  actions: SolverActionInfo[];\n  hands: SolverHandStrategy[];\n  /** Reach-weighted range of the acting player (drops folded-out combos). */\n  reach: ComboWeights | null;\n  /** Per-combo EV in bb, when this node is a solve root with `dump_ev`. */\n  evByCombo?: Map<string, number> | null;\n}) {\n  const { rows, totalWeight, hasEv } = useMemo(() => {\n    const out: Row[] = [];\n    let totalWeight = 0;\n    let hasEv = false;\n    for (const hand of hands) {\n      const weight = reach ? (reach.get(hand.combo) ?? 0) : 1;\n      if (weight <= 0.0005) continue;\n      const ev = evByCombo?.get(hand.combo);\n      if (ev !== undefined) hasEv = true;\n      totalWeight += weight;\n      out.push({ combo: hand.combo, freqs: hand.freqs, weight, ev });\n    }\n    out.sort((a, b) => {\n      if (a.ev !== undefined && b.ev !== undefined) return b.ev - a.ev || b.weight - a.weight;\n      if (a.ev !== undefined) return -1;\n      if (b.ev !== undefined) return 1;\n      return b.weight - a.weight;\n    });\n    return { rows: out, totalWeight, hasEv };\n  }, [hands, reach, evByCombo]);\n\n  const cols = hasEv ? \"52px minmax(0,1fr) 58px 56px\" : \"52px minmax(0,1fr) 62px\";\n\n  return (\n    <div className=\"flex flex-col gap-2\">\n      <span className=\"text-[10px] uppercase tracking-wide text-muted-foreground\">\n        Hand summary\n      </span>\n      <div\n        className=\"grid gap-2 px-1 text-[10px] uppercase tracking-wide text-muted-foreground/70\"\n        style={{ gridTemplateColumns: cols }}\n      >\n        <span>Hand</span>\n        <span>Strategy</span>\n        {hasEv ? <span className=\"text-right\">EV bb</span> : null}\n        <span className=\"text-right\">Range</span>\n      </div>\n      <div className=\"flex max-h-[420px] flex-col overflow-y-auto pr-0.5\">\n        {rows.map((r) => {\n          const rangePct = totalWeight > 0 ? (r.weight / totalWeight) * 100 : 0;\n          return (\n            <div\n              key={r.combo}\n              className=\"grid items-center gap-2 rounded px-1 py-1 hover:bg-accent/30\"\n              style={{ gridTemplateColumns: cols }}\n            >\n              <ComboLabel combo={r.combo} />\n              <div className=\"flex h-2 overflow-hidden rounded-full bg-white/[0.06]\">\n                {r.freqs.map((f, a) =>\n                  f <= 0.001 ? null : (\n                    <div\n                      key={a}\n                      style={{ flexGrow: f, backgroundColor: ACTION_COLORS[actions[a].label] }}\n                    />\n                  ),\n                )}\n              </div>\n              {hasEv ? (\n                <span\n                  className={`text-right text-[11px] tabular-nums ${\n                    r.ev === undefined\n                      ? \"text-muted-foreground/40\"\n                      : r.ev >= 0\n                        ? \"text-emerald-400\"\n                        : \"text-rose-400\"\n                  }`}\n                >\n                  {r.ev === undefined ? \"—\" : `${r.ev >= 0 ? \"+\" : \"\"}${r.ev.toFixed(2)}`}\n                </span>\n              ) : null}\n              <span className=\"text-right text-[11px] text-muted-foreground tabular-nums\">\n                {rangePct.toFixed(1)}%\n              </span>\n            </div>\n          );\n        })}\n        {rows.length === 0 ? (\n          <p className=\"px-1 py-3 text-xs text-muted-foreground/70\">No hands reach this node.</p>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/postflop-hand-summary.tsx"
    },
    {
      "path": "src/components/explorer/preflop-browser.tsx",
      "content": "\"use client\";\n\n// Multiway preflop solution browser — the GTO-Wizard \"Study\" experience over\n// our precomputed NLHE ranges (`/api/ranges/nl/v2`). The user picks a stack and\n// walks the full 6-max tree one seat at a time; each acting seat's 13×13\n// strategy renders with an aggregate action bar and a hand summary.\n//\n// The walk follows the dataset: after each action we advance to the next live\n// seat clockwise and ask the dataset for its node. When the dataset has no node\n// (404), the betting round has closed. Seats further round the table aren't\n// dead space: each one shows its own actions greyed out (read from the\n// fold-through node), and picking one skips there, folding everyone in between\n// — so reaching a BTN-vs-BB spot is one click, not four folds.\n//\n// A heads-up close flows straight into\n// postflop with no separate setup screen: the bar compacts to the navigator's\n// scrolling shape, a FLOP card appears, a bottom drawer picks the three cards\n// (same UI as picking a turn in the viewer), and the solve starts on its own —\n// the acting card renders as a loading placeholder until the tree is ready.\n\nimport { useEffect, useMemo, useRef, useState, type ReactNode, type Ref } from \"react\";\nimport { Loader2 } from \"lucide-react\";\nimport {\n  assignOopIp,\n  clampWeights,\n  formatBb,\n  getIcmTables,\n  getManifestForGame,\n  getNodeForGameOrNull,\n  getNodeForGameOrNullCached,\n  SEAT_ORDER,\n  type ExplorerGame,\n  lastPreflopAggressor,\n  nextActorAfter,\n  parseHistory,\n  ICM_ANTE_PER_SEAT_BB,\n  isIcmGame,\n  PLAY_ORDER,\n  raiseContextAt,\n  raiseSizesFor,\n  type IcmTable,\n  NLMTT8_ANTE_BB,\n  PLO5_ANTE_BB,\n  PLO6HU_ANTE_BB,\n  rootHistory,\n  type NodeAction,\n  type NodeResponse,\n  type Position,\n  type SeatState,\n} from \"@/lib/solver/preflop\";\nimport { fullRange, type RangeWeights } from \"@/lib/solver/range-model\";\nimport {\n  PreflopStrategyGrid,\n  preflopActionItems,\n  type PreflopActionItem,\n} from \"./preflop-strategy-grid\";\nimport { SolutionSelectorCard } from \"./solution-selector\";\nimport { PreflopHandSummary } from \"./hand-summary\";\nimport { defaultTable, groupForGame, gameForGroup } from \"@/lib/explorer/solution-catalog\";\nimport { ExplorerTabs } from \"./explorer-tabs\";\nimport { ploActionItems } from \"./plo-range-list\";\nimport { PloExplorer, plo5ActionItems } from \"./plo5-range-panel\";\nimport { Builder, type BuilderSeed } from \"./builder\";\nimport { BottomSheet } from \"./bottom-sheet\";\nimport { CardGridPicker } from \"./card-picker\";\nimport type { CustomSolutionBundle } from \"@/lib/explorer/types\";\nimport { MiniCard } from \"@/components/trainer/cards\";\nimport { PLO4HU_POSTFLOP_STACKS } from \"@/lib/explorer/plo4hu-postflop-stacks\";\nimport { Plo4HuPostflop } from \"./plo4hu-postflop\";\nimport { RailRow } from \"./rail-row\";\nimport { useExplorerUrl } from \"./explorer-url\";\nimport { explorerHost } from \"@/lib/explorer/host\";\nimport { buttonVariants } from \"@/components/ui/button\";\nimport {\n  parseAction,\n  parseGame,\n  parseLine,\n  parseStack,\n  parseTable,\n} from \"@/lib/explorer/share-url\";\n\n\nfunction CardText({ card }: { card: string }) {\n  return <MiniCard card={card} className=\"h-8 w-6 text-xl\" />;\n}\n\ninterface EndState {\n  /** \"won\" = folded to one player; \"flop\" = ≥2 players see a flop. */\n  reason: \"won\" | \"flop\";\n  survivors: Position[];\n  oop?: Position;\n  ip?: Position;\n  potBb: number;\n  effStackBb: number;\n  /** OOP called the last preflop raise rather than making it — so OOP has no\n   *  donk range on the flop and the solve can prune that lead (see Builder). */\n  oopIsPreflopCaller?: boolean;\n}\n\nfunction endFromWalk(\n  walk: { seats: Record<Position, SeatState>; pot: number },\n  history: string,\n  order: Position[] = PLAY_ORDER,\n): EndState {\n  const seats = walk.seats;\n  const survivors = order.filter((p) => !seats[p].folded);\n  const potBb = walk.pot;\n  const effStackBb = survivors.length\n    ? Math.min(...survivors.map((p) => seats[p].remaining))\n    : 0;\n  if (survivors.length <= 1) return { reason: \"won\", survivors, potBb, effStackBb };\n  const out: EndState = { reason: \"flop\", survivors, potBb, effStackBb };\n  if (survivors.length === 2) {\n    const { oop, ip } = assignOopIp(survivors[0], survivors[1]);\n    out.oop = oop;\n    out.ip = ip;\n    const aggressor = lastPreflopAggressor(history, order);\n    out.oopIsPreflopCaller = aggressor !== null && aggressor !== oop;\n  }\n  return out;\n}\n\nexport function PreflopBrowser({\n  onSaved,\n  game: lockedGame,\n}: {\n  /** Fired after a custom solution is saved from the inline solve panel, so the\n   *  page can refresh its saved-solutions library. */\n  onSaved?: (bundle: CustomSolutionBundle) => void;\n  /** Keep the walk on this dataset. Stack changes inside it still apply. */\n  game?: ExplorerGame;\n}) {\n  // The view opens where the URL points (a shared link), and every change is\n  // written back, so the address bar is always a link to this exact spot.\n  const url = useExplorerUrl();\n  const [boot] = useState(() => {\n    const g = lockedGame ?? parseGame(url.get(\"game\")) ?? \"nl\";\n    const line = parseLine(url.get(\"line\"), g);\n    return {\n      game: g,\n      stack: parseStack(url.get(\"stack\")) ?? 100,\n      // ICM sets: the stack table at that depth.\n      table: parseTable(url.get(\"table\")),\n      history: line ?? rootHistory(g),\n      // The round-closing action only means something on a walked line.\n      close: line ? parseAction(url.get(\"close\")) : null,\n    };\n  });\n  // A linked line past the root needs its seats' continue ranges (and any\n  // closing action) rebuilt from the dataset before the flop solve can seed.\n  const [restoring, setRestoring] = useState(\n    () => boot.history !== rootHistory(boot.game) || boot.close !== null,\n  );\n  const [stack, setStack] = useState(boot.stack);\n  const [stacks, setStacks] = useState<number[]>([boot.stack]);\n  // ICM sets: the stack table picked at this depth (a scenario id). The catalog\n  // resolves it, so a missing or stale id falls back to the depth's first table.\n  const [tablePick, setTablePick] = useState<string | null>(boot.table);\n  const [history, setHistory] = useState(boot.history);\n  const [node, setNode] = useState<NodeResponse | null>(null);\n  const [loading, setLoading] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n  const [fetchedEnd, setFetchedEnd] = useState<EndState | null>(null);\n  const [selectorOpen, setSelectorOpen] = useState(false);\n  // Once a postflop solve is showing, the seat strip moves into the postflop\n  // navigator (as its leading cards) so the whole line is one continuous bar;\n  // we stop rendering the standalone strip here.\n  const [viewerActive, setViewerActive] = useState(false);\n  // Which dataset the browser walks. PLO renders a hand-class list instead of\n  // the 169-cell grid, and the postflop solve flow is NL-only.\n  const [game, setGame] = useState<ExplorerGame>(boot.game);\n  const order = SEAT_ORDER[game];\n  const icm = isIcmGame(game);\n  const scenario = icm ? (defaultTable(groupForGame(game), stack, tablePick)?.scenario ?? null) : null;\n  // The ICM tables' seat stacks and payouts, from the ranges discovery.\n  const [icmTables, setIcmTables] = useState<IcmTable[]>([]);\n  const icmTable = icm ? (icmTables.find((t) => t.scenario === scenario) ?? null) : null;\n  // The flop being assembled in the picker drawer (0–3 cards). At 3 the solve\n  // starts on its own — there is no setup form in this flow.\n  const [flop, setFlop] = useState<string[]>([]);\n  const [pickerOpen, setPickerOpen] = useState(false);\n  // The postflop solve's lifecycle as seen from the strip: the acting card is\n  // a loading placeholder while \"running\"; \"failed\" (error/cancel) turns it\n  // into a re-pick affordance. Distinguished from success via solvedRef,\n  // because the solved and running callbacks land in the same commit.\n  const [postflopRun, setPostflopRun] = useState<\"idle\" | \"running\" | \"failed\">(\"idle\");\n  const solvedRef = useRef(false);\n  // A skip-ahead whose action closed the round: the fold-through history has to\n  // land in `history` (so the strip shows the folds), but the fetch effect that\n  // history change fires would find a live node there and undo the close. Set\n  // in the same commit as the history, it tells that effect to derive the end\n  // state instead of fetching. See `advanceFrom`.\n  const [pendingClose, setPendingClose] = useState<{\n    history: string;\n    action: NodeAction;\n  } | null>(null);\n\n  useEffect(() => {\n    let cancelled = false;\n    getManifestForGame(game)\n      .then((m) => {\n        if (cancelled) return;\n        setStacks(m.stacks);\n        setStack((s) => (m.stacks.includes(s) ? s : (m.stacks[0] ?? s)));\n      })\n      .catch(() => {});\n    return () => {\n      cancelled = true;\n    };\n  }, [game]);\n\n  useEffect(() => {\n    if (!isIcmGame(game)) return;\n    let cancelled = false;\n    getIcmTables(game)\n      .then((t) => {\n        if (!cancelled) setIcmTables(t);\n      })\n      .catch(() => {});\n    return () => {\n      cancelled = true;\n    };\n  }, [game]);\n\n  // ICM tables: every seat posts a 0.125bb ante (1bb in the pot) and starts\n  // from its own stack; raises are priced from the feed's sizes, since the\n  // `Open` / `3B` tokens don't say how big they are.\n  const seatStacks = useMemo(() => {\n    if (!icmTable) return undefined;\n    const out: Partial<Record<Position, number>> = {};\n    for (const [p, bb] of Object.entries(icmTable.stacksBb) as [Position, number][]) {\n      out[p] = Math.max(0, bb - ICM_ANTE_PER_SEAT_BB);\n    }\n    return out;\n  }, [icmTable]);\n  const sizes = icm ? raiseSizesFor(game, scenario) : undefined;\n  // The sizes record grows as nodes load; its size re-runs the walks below.\n  const sizesSeen = sizes ? Object.keys(sizes).length : 0;\n  const walkAt = (h: string) => parseHistory(h, stack, order, anteBb, sizes, seatStacks);\n\n  const anteBb =\n    game === \"plo5\"\n      ? PLO5_ANTE_BB\n      : game === \"plo6hu\"\n        ? PLO6HU_ANTE_BB\n        : game === \"nlmtt8\"\n          ? NLMTT8_ANTE_BB\n          : icm\n            ? ICM_ANTE_PER_SEAT_BB * order.length\n            : 0;\n  const walk = useMemo(\n    () => walkAt(history),\n    // `walkAt` reads sizes/seatStacks; `sizesSeen` stands in for the record.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [history, stack, order, anteBb, seatStacks, sizesSeen, scenario],\n  );\n\n  // A skip-ahead's closing action isn't in `history` (the string stops at the\n  // seat that acted), so the end state it produces is derived here rather than\n  // fetched — the dataset would still answer with a live node at that history.\n  const closedEnd = useMemo(() => {\n    if (!pendingClose || pendingClose.history !== history) return null;\n    const seat = history.split(\"_\").pop() as Position;\n    const w = walkAt(history);\n    const seats = {\n      ...w.seats,\n      [seat]: { ...w.seats[seat], folded: pendingClose.action.kind === \"fold\" },\n    };\n    return endFromWalk(\n      { seats, pot: w.pot },\n      `${history}_${pendingClose.action.action}`,\n      order,\n    );\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [pendingClose, history, stack, order, anteBb, seatStacks, sizesSeen, scenario]);\n  const end = closedEnd ?? fetchedEnd;\n\n  // Fetch the decision at the current history. A 404 means the betting round has\n  // closed on this line → derive the end state from who's still in.\n  useEffect(() => {\n    let cancelled = false;\n    // A skip-ahead already closed the round at this history (`closedEnd`) — the\n    // dataset has a live node there, so asking would undo the close.\n    if (closedEnd) return;\n    // A linked closed line: wait for the restore to set the close, rather than\n    // flashing the live node that sits at this history.\n    if (restoring && boot.close) return;\n    // An ICM set waits for a depth it has (the manifest corrects the stack).\n    if (icm && !scenario) return;\n    (async () => {\n      setLoading(true);\n      setError(null);\n      // Clear a stale end state up front: after a rewind out of a closed line\n      // the old `end` would otherwise keep the flop-drawer flow alive (and\n      // flash the picker open) until this fetch lands. A line closed by\n      // `advance` doesn't change the history, so it never hits this path.\n      setFetchedEnd(null);\n      try {\n        const n = await getNodeForGameOrNull(game, stack, history, scenario);\n        if (cancelled) return;\n        if (n) {\n          setNode(n);\n          setFetchedEnd(null);\n        } else {\n          setNode(null);\n          setFetchedEnd(\n            endFromWalk(walkAt(history), history, order),\n          );\n        }\n      } catch (err) {\n        if (!cancelled) {\n          setNode(null);\n          setError(err instanceof Error ? err.message : \"No range here.\");\n        }\n      } finally {\n        if (!cancelled) setLoading(false);\n      }\n    })();\n    return () => {\n      cancelled = true;\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [game, stack, scenario, history, order, anteBb, closedEnd, restoring, boot.close]);\n\n  // Rebuild a linked line: re-apply its closing action.\n  // A link to a stack or line the dataset no longer has falls back to the root.\n  useEffect(() => {\n    if (!restoring) return;\n    let cancelled = false;\n    (async () => {\n      const g = boot.game;\n      const fallback = () => {\n        setHistory(rootHistory(g));\n        setPendingClose(null);\n      };\n      try {\n        const m = await getManifestForGame(g);\n        if (!m.stacks.includes(boot.stack)) {\n          if (!cancelled) fallback();\n          return;\n        }\n        // The seats' continue ranges come from the line's past nodes (see\n        // `captured`), so only the closing action needs resolving here.\n        let close: { history: string; action: NodeAction } | null = null;\n        if (boot.close) {\n          const bootScenario = isIcmGame(g)\n            ? (defaultTable(groupForGame(g), boot.stack, boot.table)?.scenario ?? null)\n            : null;\n          const n = await getNodeForGameOrNullCached(g, boot.stack, boot.history, bootScenario);\n          const a = n?.actions.find((x) => x.action === boot.close) ?? null;\n          if (a) close = { history: boot.history, action: a };\n        }\n        if (cancelled) return;\n        setPendingClose(close);\n      } catch {\n        if (!cancelled) fallback();\n      } finally {\n        if (!cancelled) setRestoring(false);\n      }\n    })();\n    return () => {\n      cancelled = true;\n    };\n    // Runs once for the linked view; `boot` never changes.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  // Mirror the walk into the URL.\n  const closeAction =\n    pendingClose && pendingClose.history === history ? pendingClose.action.action : null;\n  useEffect(() => {\n    if (restoring) return;\n    url.set({\n      game,\n      stack: String(stack),\n      table: scenario,\n      line: history === rootHistory(game) ? null : history,\n      close: closeAction,\n    });\n  }, [url, restoring, game, stack, scenario, history, closeAction]);\n\n  /** Switch dataset and/or stack. History always restarts at this dataset's\n   *  first actor — a leftover UTG string on the PLO5 LJ ring crashes the walk. */\n  const applyWalk = (nextGame: ExplorerGame, nextStack: number, nextTable: string | null = null) => {\n    // Filters and the open tab belong to the dataset being left.\n    if (nextGame !== game) url.set({ tab: null, f: null, q: null, s: null });\n    if (nextGame !== game) setIcmTables([]);\n    setGame(nextGame);\n    setStack(nextStack);\n    setTablePick(nextTable);\n    setHistory(rootHistory(nextGame));\n    setPendingClose(null);\n    setFetchedEnd(null);\n    setNode(null);\n    setError(null);\n    setViewerActive(false);\n    setFlop([]);\n  };\n\n  const changeGame = (next: ExplorerGame) => {\n    if (next === game) return;\n    applyWalk(next, stack);\n  };\n\n  const changeStack = (next: number) => {\n    applyWalk(game, next);\n  };\n\n  const actor = end ? null : walk.hero;\n\n  // Take `action` for `seat` at `base` (a history ending in that seat) and\n  // advance to the next live seat clockwise, capturing the seat's continue\n  // range; the effect then asks the dataset for the next node (or detects\n  // close). `base` is the current history for the acting card, and a\n  // fold-through history for a skip-ahead.\n  const advanceFrom = (base: string, action: NodeAction) => {\n    setViewerActive(false);\n    setPendingClose(null);\n    setError(null);\n\n    const next = nextActorAfter(base, action.action, stack, order);\n    if (!next) {\n      // This action closed the round. A history string stops at the seat that\n      // acts, so the action itself can't live there — `closedEnd` derives the\n      // end state from this instead. On a skip-ahead the folds still have to\n      // land in `history`.\n      setPendingClose({ history: base, action });\n      if (base !== history) setHistory(base);\n      return;\n    }\n    setHistory(`${base}_${action.action}_${next}`);\n  };\n\n  const advance = (action: NodeAction) => {\n    if (!node || actor == null) return;\n    advanceFrom(history, action);\n  };\n\n  // Rewind the line to one of its past decisions: `base` is the history at\n  // that decision (a prefix of the line, ending in the seat that acted there).\n  // Also fired from inside the postflop navigator, whose leading cards are\n  // this same rail.\n  const rewindTo = (base: string) => {\n    setViewerActive(false);\n    setPendingClose(null);\n    setHistory(base);\n    setError(null);\n  };\n\n  /** A node's action rows; `at` is the history the node sits at (its actor's\n   *  spot prices the ICM raises as pot percentages). */\n  const itemsFor = (n: NodeResponse | null | undefined, at: string) => {\n    if (!n) return [];\n    if (icm) return preflopActionItems(n.actions, stack, raiseContextAt(walkAt(at)));\n    if (game === \"nl\" || game === \"nlmtt8\") return preflopActionItems(n.actions, stack);\n    if (game === \"plo5\" || game === \"plo6hu\") return plo5ActionItems(n.actions, stack);\n    return ploActionItems(n.actions, stack);\n  };\n  // While the next node loads, `node` still holds the previous decision —\n  // its rows must not appear (or be clickable) on the new actor's card.\n  const items = loading ? [] : itemsFor(node, history);\n\n  // The line so far, one entry per decision taken: the history at that\n  // decision (ending in the seat that acted) and the action chosen there. A\n  // round-closing action isn't in `history`, so it's appended from the close.\n  const decisions = useMemo(() => {\n    const tokens = history.split(\"_\");\n    const out: { base: string; seat: Position; chosen: string }[] = [];\n    for (let i = 0; i + 1 < tokens.length; i += 2) {\n      out.push({\n        base: tokens.slice(0, i + 1).join(\"_\"),\n        seat: tokens[i] as Position,\n        chosen: tokens[i + 1],\n      });\n    }\n    if (closeAction) {\n      out.push({ base: history, seat: tokens[tokens.length - 1] as Position, chosen: closeAction });\n    }\n    return out;\n  }, [history, closeAction]);\n\n  // Each past decision's node, so its card can list every option with the\n  // chosen one highlighted (GTO Wizard's rail) and seed the postflop ranges.\n  // Node reads are memoized, so walking back and forth doesn't re-fetch.\n  const pastKey = `${game}:${scenario}:${stack}:${decisions.map((d) => d.base).join(\"|\")}`;\n  const [pastNodes, setPastNodes] = useState<{ key: string; nodes: (NodeResponse | null)[] }>({\n    key: \"\",\n    nodes: [],\n  });\n  useEffect(() => {\n    let cancelled = false;\n    if (decisions.length === 0) return;\n    Promise.all(\n      decisions.map((d) =>\n        getNodeForGameOrNullCached(game, stack, d.base, scenario).catch(() => null),\n      ),\n    ).then((nodes) => {\n      if (!cancelled) setPastNodes({ key: pastKey, nodes });\n    });\n    return () => {\n      cancelled = true;\n    };\n  }, [decisions, pastKey, game, stack, scenario]);\n  const readyPastNodes = pastNodes.key === pastKey ? pastNodes.nodes : null;\n\n  // Each seat's continue range on this line: the weights of the last\n  // non-fold action it took. Derived from the line itself, so a rewind or an\n  // opened link can never leave a stale range behind. Seeds the postflop solve.\n  const captured = useMemo(() => {\n    const out: Partial<Record<Position, RangeWeights>> = {};\n    if (!readyPastNodes) return null;\n    decisions.forEach((d, i) => {\n      const a = readyPastNodes[i]?.actions.find((x) => x.action === d.chosen);\n      if (a && a.kind !== \"fold\") out[d.seat] = clampWeights(a.weights);\n    });\n    return out;\n  }, [decisions, readyPastNodes]);\n\n  // Skip-ahead: every seat that hasn't acted yet on this line can be acted for\n  // directly — folding the actor and everyone between them and that seat. The\n  // value is the fold-through history ending at that seat, which is both what\n  // we fetch its (greyed-out) actions from and the base we advance from.\n  const skipTargets = useMemo(() => {\n    const out: Partial<Record<Position, string>> = {};\n    if (!node || actor == null) return out;\n    const actorIdx = order.indexOf(actor);\n    if (actorIdx === -1) return out;\n    const parts = [history, \"Fold\"];\n    for (let i = 1; i < order.length; i++) {\n      const p = order[(actorIdx + i) % order.length];\n      const seat = walk.seats[p];\n      if (seat.folded) continue;\n      // Wrapped around to a seat that already acted — a second orbit isn't\n      // reachable by folding, so the skip range stops here.\n      if (seat.action !== null) break;\n      out[p] = [...parts, p].join(\"_\");\n      parts.push(p, \"Fold\");\n    }\n    return out;\n  }, [node, actor, order, history, walk]);\n\n  // Prefetch each skip target's node so its actions render in the strip. The\n  // result is stamped with the target set it belongs to, so a stale batch is\n  // ignored rather than cleared (no extra render on every step).\n  const skipKey = `${game}:${scenario}:${stack}:${Object.values(skipTargets).join(\"|\")}`;\n  const [skipNodes, setSkipNodes] = useState<{\n    key: string;\n    nodes: Partial<Record<Position, NodeResponse | null>>;\n  }>({ key: \"\", nodes: {} });\n  useEffect(() => {\n    let cancelled = false;\n    const entries = Object.entries(skipTargets) as [Position, string][];\n    if (entries.length === 0) return;\n    Promise.all(\n      entries.map(async ([p, h]) => {\n        const n = await getNodeForGameOrNullCached(game, stack, h, scenario).catch(() => null);\n        return [p, n] as const;\n      }),\n    ).then((pairs) => {\n      if (!cancelled) setSkipNodes({ key: skipKey, nodes: Object.fromEntries(pairs) });\n    });\n    return () => {\n      cancelled = true;\n    };\n  }, [skipTargets, skipKey, game, stack, scenario]);\n  const readySkipNodes = skipNodes.key === skipKey ? skipNodes.nodes : null;\n\n  // The rail, GTO Wizard style: one card per decision already taken on the\n  // line (every option listed, the chosen one highlighted; click the card to\n  // go back to that decision, or another option to branch from it), then the\n  // acting seat, then the seats still to act this orbit (greyed — picking one\n  // folds everyone in between). Rendered standalone and as the leading cards\n  // of the postflop navigator, so the whole hand reads as one bar.\n  const renderRail = () => {\n    const cards: ReactNode[] = decisions.map((d, i) => {\n      const at = walkAt(d.base);\n      return (\n        <PastDecisionCard\n          key={`past:${i}`}\n          position={d.seat}\n          isDealer={at.seats[d.seat]?.isDealer ?? false}\n          remaining={at.seats[d.seat]?.remaining ?? 0}\n          pot={at.pot}\n          chosen={d.chosen}\n          items={readyPastNodes ? itemsFor(readyPastNodes[i], d.base) : undefined}\n          onRewind={() => rewindTo(d.base)}\n          onPick={(a) => {\n            if (a.action === d.chosen) rewindTo(d.base);\n            else advanceFrom(d.base, a);\n          }}\n        />\n      );\n    });\n    if (actor != null) {\n      cards.push(\n        <SeatStripCard\n          key={`actor:${decisions.length}`}\n          position={actor}\n          seat={walk.seats[actor]}\n          isActor\n          items={items}\n          pot={walk.pot}\n          loading={loading}\n          onAdvance={advance}\n          cardRef={actorCardRef}\n        />,\n      );\n      for (const [p, skipHistory] of Object.entries(skipTargets) as [Position, string][]) {\n        cards.push(\n          <SeatStripCard\n            key={`skip:${p}`}\n            position={p}\n            seat={walk.seats[p]}\n            isActor={false}\n            skipItems={readySkipNodes ? itemsFor(readySkipNodes[p], skipHistory) : undefined}\n            skipLoading={!readySkipNodes}\n            pot={walk.pot}\n            loading={loading}\n            onAdvance={advance}\n            onSkip={(a) => advanceFrom(skipHistory, a)}\n          />,\n        );\n      }\n    }\n    return cards;\n  };\n\n  // When the line closes 2-way we solve the postflop spot inline, seeded with\n  // each survivor's continue range. The board comes from the picker drawer.\n  // Hold'em only: the inline solver takes 169-class ranges, and a PLO node's\n  // weights are keyed by four-card classes, which `clampWeights` drops — the\n  // seed came out empty and the strip spun \"solving…\" forever (6-max PLO).\n  const solveSeed: BuilderSeed | null =\n    !restoring &&\n    captured !== null &&\n    INLINE_SOLVE_GAMES.has(game) &&\n    explorerHost().solver !== null &&\n    end?.reason === \"flop\" &&\n    end.survivors.length === 2 &&\n    end.oop &&\n    end.ip\n      ? {\n          oopWeights: captured[end.oop] ?? fullRange(),\n          ipWeights: captured[end.ip] ?? fullRange(),\n          potBb: end.potBb,\n          effStackBb: end.effStackBb,\n          oopLabel: end.oop,\n          ipLabel: end.ip,\n          board: flop.length === 3 ? flop.join(\" \") : \"\",\n          oopIsPreflopCaller: end.oopIsPreflopCaller,\n        }\n      : null;\n  // Heads-up PLO4 has its own postflop engine (blueprint flop solve, then\n  // turn/river re-solves), at the stacks it serves.\n  const ploHuPostflop =\n    !restoring &&\n    game === \"plo4hu\" &&\n    explorerHost().plo4huPostflop !== null &&\n    end?.reason === \"flop\" &&\n    end.survivors.length === 2 &&\n    PLO4HU_POSTFLOP_STACKS.includes(stack);\n  const twoWayFlop = solveSeed !== null || ploHuPostflop;\n  const flopDone = flop.length === 3;\n\n  // A different line (or stack) voids the flop pick and the solve lifecycle.\n  useEffect(() => {\n    setFlop([]);\n    setPostflopRun(\"idle\");\n    solvedRef.current = false;\n  }, [game, stack, scenario, history, order]);\n\n  // The drawer opens on its own the moment a 2-way flop line closes — the pick\n  // IS the next step, no intermediate screen. Closing it leaves the dashed\n  // FLOP card in the strip as the way back in.\n  useEffect(() => {\n    if (twoWayFlop) setPickerOpen(true);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [twoWayFlop, stack, history]);\n\n  // Keep the decision in view as the rail grows: the acting card, with the\n  // last decision before it still showing, so a deep line doesn't push the\n  // choice off-screen (phones fit one or two cards). Once the line closes,\n  // the newest card (flop / loading actor) is the one to show. Instant, not\n  // smooth — smooth scrollTo is dropped in some embedded-Chromium contexts.\n  const stripRef = useRef<HTMLDivElement>(null);\n  const actorCardRef = useRef<HTMLDivElement>(null);\n  useEffect(() => {\n    const el = stripRef.current;\n    if (!el) return;\n    const card = actorCardRef.current;\n    if (card && !end) {\n      const prev = card.previousElementSibling as HTMLElement | null;\n      const left = prev ? prev.offsetLeft : card.offsetLeft;\n      const right = card.offsetLeft + card.offsetWidth;\n      // Show the previous card too when it fits; never hide the actor.\n      el.scrollLeft = right - left <= el.clientWidth ? left : card.offsetLeft;\n    } else {\n      el.scrollLeft = el.scrollWidth;\n    }\n  }, [history, end, flop.length, postflopRun, twoWayFlop, loading]);\n\n  const repick = () => {\n    setFlop([]);\n    setPostflopRun(\"idle\");\n    solvedRef.current = false;\n    setPickerOpen(true);\n  };\n\n  const selectSolution = (groupId: string, nextStack: number, nextTable?: string | null) => {\n    const next = gameForGroup(groupId) ?? game;\n    if (lockedGame && next !== lockedGame) return;\n    applyWalk(lockedGame ?? next, nextStack, nextTable ?? null);\n  };\n  const lockedGroupId = lockedGame ? groupForGame(lockedGame).id : undefined;\n  // The game card leads the bar on every street: preflop here, then pinned\n  // beside the postflop navigator's rail once a flop is showing.\n  const gameCard = (\n    <SolutionSelectorCard\n      group={groupForGame(game)}\n      stack={stack}\n      table={scenario}\n      availableStacks={stacks}\n      open={selectorOpen}\n      onOpenChange={setSelectorOpen}\n      onSelect={selectSolution}\n      onlyGroupId={lockedGroupId}\n      shareable\n    />\n  );\n\n  return (\n    <div className=\"flex flex-col gap-4\">\n      {/* The preflop bar is one row that scrolls horizontally: the solution\n          selector, then a fixed-width card per seat. It used to wrap onto\n          several rows because the solutions library hung off the selector as an\n          anchored popover a scroller would clip — the library is a side drawer\n          now, so the bar can stay the single line it reads best as, at any\n          width and any seat count.\n\n          The moment a 2-way flop line closes, the bar compacts to the postflop\n          navigator's shape — fixed-width cards in a scroller — and grows a FLOP\n          card (then the loading acting card), so reaching the flop reads as the\n          same bar extending rather than a screen change.\n\n          Once the solve lands, the seat cards move into the navigator (as its\n          leading fixed-width cards) and this row disappears. The game card\n          moves with them: the navigator pins it in the same spot (RailRow),\n          so it stays visible on the flop, turn and river. */}\n      {!viewerActive && !(ploHuPostflop && flopDone) ? (\n        twoWayFlop ? (\n          <RailRow lead={gameCard} scrollerRef={stripRef}>\n              {renderRail()}\n              <FlopStripCard flop={flop} onClick={flopDone ? repick : () => setPickerOpen(true)} />\n              {flopDone ? (\n                postflopRun === \"failed\" ? (\n                  <button\n                    type=\"button\"\n                    onClick={repick}\n                    className=\"flex min-h-[104px] w-[136px] shrink-0 flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-destructive/50 bg-destructive/[0.06] p-2 text-center\"\n                  >\n                    <span className=\"text-xs font-medium text-destructive\">solve stopped</span>\n                    <span className=\"text-[11px] text-muted-foreground\">re-pick flop ↓</span>\n                  </button>\n                ) : (\n                  // The next decision, loading: the OOP seat acts first postflop.\n                  <div className=\"flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border border-foreground/50 bg-accent/50 p-2\">\n                    <div className=\"flex items-center justify-between\">\n                      <span className=\"text-xs font-semibold text-foreground\">{end?.oop}</span>\n                      <span className=\"text-[10px] text-muted-foreground tabular-nums\">\n                        pot {end?.potBb.toFixed(1)}\n                      </span>\n                    </div>\n                    <div className=\"flex flex-1 items-center gap-2 text-xs text-muted-foreground\">\n                      <Loader2 className=\"size-3.5 shrink-0 animate-spin\" /> solving…\n                    </div>\n                  </div>\n                )\n              ) : null}\n          </RailRow>\n        ) : (\n          <RailRow lead={gameCard} scrollerRef={stripRef}>\n              {renderRail()}\n          </RailRow>\n        )\n      ) : null}\n\n      {error ? <p className=\"text-xs text-destructive\">{error}</p> : null}\n\n      {/* Line closed: solve the postflop inline (2-way, board picked), or\n          explain why not. Mounted only once the flop is complete — mounting IS\n          what starts the solve. */}\n      {end ? (\n        solveSeed && flopDone ? (\n          <InlineSolve\n            key={`${stack}:${history}:${flop.join(\"\")}`}\n            seed={solveSeed}\n            stripPrefix={renderRail()}\n            stripLead={gameCard}\n            onSolvedChange={(s) => {\n              solvedRef.current = s;\n              setViewerActive(s);\n            }}\n            onSetupError={() => setPostflopRun(\"failed\")}\n            onRunningChange={(r) =>\n              // `false` only means failure when a run was actually underway —\n              // the mirror also emits false on mount (e.g. while a pending\n              // previous-session solve holds the auto-solve).\n              setPostflopRun((prev) =>\n                r ? \"running\" : solvedRef.current ? \"idle\" : prev === \"running\" ? \"failed\" : prev,\n              )\n            }\n            onSaved={onSaved}\n          />\n        ) : ploHuPostflop && flopDone ? (\n          <Plo4HuPostflop\n            stack={stack}\n            line={decisions.map((d) => `${d.seat}_${d.chosen}`).join(\"_\")}\n            flop={flop}\n            pot={end.potBb}\n            effStack={end.effStackBb}\n            stripPrefix={renderRail()}\n            stripLead={gameCard}\n            onRepickFlop={repick}\n          />\n        ) : twoWayFlop ? null : (\n          <EndCard end={end} />\n        )\n      ) : loading && !node ? (\n        <div className=\"flex min-h-[200px] items-center justify-center text-sm text-muted-foreground\">\n          <Loader2 className=\"size-4 animate-spin\" />\n        </div>\n      ) : node ? (\n        game === \"nl\" || game === \"nlmtt8\" || icm ? (\n          <ExplorerTabs\n            explorer={\n              <div className=\"grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,320px)]\">\n                <PreflopStrategyGrid\n                  actions={node.actions}\n                  stack={stack}\n                  raiseContext={icm ? raiseContextAt(walk) : undefined}\n                />\n                <PreflopHandSummary actions={node.actions} evUnit={node.evUnit ?? \"sb\"} />\n              </div>\n            }\n          />\n        ) : (\n          <PloExplorer\n            game={game === \"plo5\" || game === \"plo6hu\" ? game : \"plo\"}\n            actions={node.actions}\n            stack={stack}\n            history={history}\n          />\n        )\n      ) : null}\n\n      {/* The flop picker — the same drawer + card UI as picking a turn card in\n          the viewer. Three cards complete the flop; the drawer closes itself\n          and the solve starts. */}\n      {pickerOpen && twoWayFlop && !viewerActive ? (\n        <BottomSheet title=\"Pick the flop\" onClose={() => setPickerOpen(false)}>\n          <CardGridPicker\n            value={flop}\n            max={3}\n            onChange={(next) => {\n              setFlop(next);\n              setPostflopRun(\"idle\");\n              solvedRef.current = false;\n              if (next.length === 3) setPickerOpen(false);\n            }}\n          />\n          <span className=\"pb-2 text-[11px] text-muted-foreground/70\">\n            Three cards — the solve starts the moment the flop is complete.\n          </span>\n        </BottomSheet>\n      ) : null}\n    </div>\n  );\n}\n\n/** The FLOP card in the strip: dashed \"pick cards ↓\" while the drawer flow is\n *  open-ended, a street card once the three cards are in. Clicking either form\n *  reopens the drawer (a completed pick resets and re-picks). */\nfunction FlopStripCard({ flop, onClick }: { flop: string[]; onClick: () => void }) {\n  if (flop.length === 3) {\n    return (\n      <button\n        type=\"button\"\n        onClick={onClick}\n        title=\"Re-pick the flop\"\n        className=\"flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border border-border bg-card/40 p-2 text-left transition-colors hover:border-foreground/30\"\n      >\n        <span className=\"text-[10px] uppercase tracking-wide text-zinc-500\">Flop</span>\n        <div className=\"mt-auto flex flex-wrap items-center gap-1 text-lg font-bold tabular-nums\">\n          {flop.map((c, i) => (\n            <CardText key={i} card={c} />\n          ))}\n        </div>\n      </button>\n    );\n  }\n  return (\n    <button\n      type=\"button\"\n      onClick={onClick}\n      className=\"flex min-h-[104px] w-[136px] shrink-0 flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-foreground/40 bg-accent/30 p-2 text-center\"\n    >\n      <span className=\"text-[10px] uppercase tracking-wide text-zinc-500\">Flop</span>\n      {flop.length > 0 ? (\n        <div className=\"flex items-center gap-1 text-lg font-bold tabular-nums\">\n          {flop.map((c, i) => (\n            <CardText key={i} card={c} />\n          ))}\n        </div>\n      ) : null}\n      <span className=\"text-xs text-muted-foreground\">pick cards ↓</span>\n    </button>\n  );\n}\n\n/** The inline postflop solve engine, mounted once the drawer has fixed the\n *  flop. No setup form up front (setupless — \"Edit spot\" still reopens it\n *  post-solve) and the solve starts on its own; the parent's strip renders the\n *  loading acting card off `onRunningChange` in the meantime. */\nfunction InlineSolve({\n  seed,\n  stripPrefix,\n  stripLead,\n  onSolvedChange,\n  onRunningChange,\n  onSetupError,\n  onSaved,\n}: {\n  seed: BuilderSeed;\n  /** The preflop seat cards, rendered as the leading cards of the postflop\n   *  navigator's strip so the whole line is one continuous action bar. */\n  stripPrefix?: ReactNode;\n  /** The game card, pinned left of the navigator's strip. */\n  stripLead?: ReactNode;\n  /** Fired when the postflop result appears/clears — the parent hides its own\n   *  seat strip while the navigator (with the prefix) is showing. */\n  onSolvedChange?: (solved: boolean) => void;\n  /** Mirrors the solve's running state into the parent's strip. */\n  onRunningChange?: (running: boolean) => void;\n  /** The solve was refused before it started (bad seed or input). */\n  onSetupError?: (message: string) => void;\n  onSaved?: (bundle: CustomSolutionBundle) => void;\n}) {\n  // No header here: the postflop navigator continues straight off the preflop\n  // seat strip above, so the setup/flow reads as one continuous action bar.\n  return (\n    <Builder\n      layout=\"inline\"\n      setupless\n      autoSolve\n      seed={seed}\n      stripPrefix={stripPrefix}\n      stripLead={stripLead}\n      onSolvedChange={onSolvedChange}\n      onRunningChange={onRunningChange}\n      onSetupError={onSetupError}\n      onSaved={(_summary, bundle) => onSaved?.(bundle)}\n    />\n  );\n}\n\n/** One row per action: colour dot, label, frequency. Shared by every rail\n *  card so the acting, past and skip-ahead cards line up row for row. */\nfunction ActionRow({\n  item,\n  onClick,\n  title,\n  tone = \"live\",\n}: {\n  item: PreflopActionItem;\n  onClick: () => void;\n  title?: string;\n  /** live = acting seat; dim = skip-ahead or an option not taken on this\n   *  line; chosen = the action taken at a past decision. */\n  tone?: \"live\" | \"dim\" | \"chosen\";\n}) {\n  return (\n    <button\n      type=\"button\"\n      onClick={(e) => {\n        // Rows sit inside a clickable past-decision card.\n        e.stopPropagation();\n        onClick();\n      }}\n      title={title}\n      aria-pressed={tone === \"chosen\" ? true : undefined}\n      className={`flex items-center justify-between gap-1 rounded px-1 py-0.5 text-left transition-colors ${\n        tone === \"chosen\"\n          ? \"bg-foreground/15 ring-1 ring-foreground/25\"\n          : tone === \"dim\"\n            ? \"opacity-45 hover:bg-accent hover:opacity-100\"\n            : \"hover:bg-accent\"\n      }`}\n    >\n      <span className=\"flex min-w-0 items-center gap-1 truncate text-xs text-foreground\">\n        <span className=\"size-2 shrink-0 rounded-[2px]\" style={{ backgroundColor: item.color }} />\n        <span className={`truncate ${tone === \"chosen\" ? \"font-semibold\" : \"\"}`}>{item.label}</span>\n      </span>\n      <span className=\"shrink-0 text-[11px] font-semibold text-foreground tabular-nums\">\n        {(item.freq * 100).toFixed(0)}%\n      </span>\n    </button>\n  );\n}\n\nfunction SeatHeader({\n  position,\n  isDealer,\n  muted,\n  right,\n}: {\n  position: Position;\n  isDealer: boolean;\n  muted?: boolean;\n  right: ReactNode;\n}) {\n  return (\n    <div className=\"flex items-center justify-between\">\n      <div className=\"flex items-center gap-1.5\">\n        <span\n          className={`text-sm font-semibold ${muted ? \"text-muted-foreground\" : \"text-foreground\"}`}\n        >\n          {position}\n        </span>\n        {isDealer ? (\n          <span className=\"flex size-3.5 items-center justify-center rounded-full bg-foreground text-[8px] font-bold text-background\">\n            D\n          </span>\n        ) : null}\n      </div>\n      {right}\n    </div>\n  );\n}\n\n/** Datasets whose ranges the inline postflop solve can take (169-class Hold'em\n *  weights). Heads-up PLO4 has its own engine (`Plo4HuPostflop`); the other PLO\n *  datasets end on an explanation card instead of a solve. */\nconst INLINE_SOLVE_GAMES: ReadonlySet<ExplorerGame> = new Set<ExplorerGame>([\"nl\", \"nlmtt8\"]);\n\nconst RAIL_CARD = \"flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border p-2\";\n\n/** A decision already taken on the line. Lists every option that seat had,\n *  with the one taken highlighted. Clicking the card goes back to that\n *  decision; clicking another option branches the line from there. */\nfunction PastDecisionCard({\n  position,\n  isDealer,\n  remaining,\n  pot,\n  chosen,\n  items,\n  onRewind,\n  onPick,\n}: {\n  position: Position;\n  isDealer: boolean;\n  /** The seat's stack when it acted. */\n  remaining: number;\n  pot: number;\n  /** The action token taken here (e.g. \"Fold\", \"R2.5\", \"AI\"). */\n  chosen: string;\n  /** That decision's options; undefined while its node loads. */\n  items?: PreflopActionItem[];\n  onRewind: () => void;\n  onPick: (a: NodeAction) => void;\n}) {\n  const chosenItem = items?.find((it) => it.action.action === chosen);\n  return (\n    // ui-exception: the rail card holds its own option buttons (a past\n    // decision is both \"go back here\" and \"take another option here\"), so the\n    // card itself can't be a <button>; it is keyboard-operable instead.\n    <div\n      role=\"button\"\n      tabIndex={0}\n      onClick={onRewind}\n      onKeyDown={(e) => {\n        if (e.target !== e.currentTarget) return;\n        if (e.key === \"Enter\" || e.key === \" \") {\n          e.preventDefault();\n          onRewind();\n        }\n      }}\n      title={`Back to ${position}'s decision`}\n      aria-label={`${position}: ${chosenItem?.label ?? chosen}. Go back to this decision`}\n      className={`${RAIL_CARD} cursor-pointer border-border bg-card/40 text-left transition-colors hover:border-foreground/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`}\n    >\n      <SeatHeader\n        position={position}\n        isDealer={isDealer}\n        muted\n        right={\n          <span className=\"text-[11px] font-medium text-muted-foreground tabular-nums\">\n            {formatBb(remaining)}\n          </span>\n        }\n      />\n      {items && items.length > 0 ? (\n        <div className=\"flex flex-col\">\n          {items.map((it) => (\n            <ActionRow\n              key={it.action.action}\n              item={it}\n              tone={it.action.action === chosen ? \"chosen\" : \"dim\"}\n              title={\n                it.action.action === chosen\n                  ? `Back to ${position}'s decision`\n                  : `${position} ${it.label} instead (pot ${pot.toFixed(1)})`\n              }\n              onClick={() => onPick(it.action)}\n            />\n          ))}\n        </div>\n      ) : (\n        <div className=\"flex flex-1 items-center py-1\">\n          <span className=\"inline-block max-w-full truncate rounded bg-accent px-2 py-0.5 text-xs font-semibold text-foreground\">\n            {chosen}\n          </span>\n        </div>\n      )}\n    </div>\n  );\n}\n\n/** The acting seat (live action rows) or a seat still to act this orbit\n *  (the same rows greyed; picking one folds everyone in between). */\nfunction SeatStripCard({\n  position,\n  seat,\n  isActor,\n  items,\n  skipItems,\n  skipLoading = false,\n  pot,\n  loading,\n  onAdvance,\n  onSkip,\n  cardRef,\n}: {\n  position: Position;\n  seat: SeatState;\n  isActor: boolean;\n  /** Aggregate action rows for the acting seat (dot · label · freq %). */\n  items?: PreflopActionItem[];\n  /** Same rows, greyed, for a seat the user can skip ahead to. */\n  skipItems?: PreflopActionItem[];\n  /** That seat's node is still loading. */\n  skipLoading?: boolean;\n  /** Pot at the decision, shown on the acting card like postflop's navigator. */\n  pot: number;\n  loading: boolean;\n  onAdvance: (a: NodeAction) => void;\n  /** Take this action here, folding the actor and everyone in between. */\n  onSkip?: (a: NodeAction) => void;\n  cardRef?: Ref<HTMLDivElement>;\n}) {\n  const header = (\n    <SeatHeader\n      position={position}\n      isDealer={seat.isDealer}\n      right={\n        isActor ? (\n          <span className=\"text-[10px] text-muted-foreground tabular-nums\">\n            pot {pot.toFixed(1)}\n          </span>\n        ) : (\n          <span className=\"text-[11px] font-medium text-muted-foreground tabular-nums\">\n            {formatBb(seat.remaining)}\n          </span>\n        )\n      }\n    />\n  );\n\n  let body: ReactNode;\n  if (isActor) {\n    body =\n      !items || items.length === 0 ? (\n        <span className=\"flex items-center gap-1.5 py-1 text-xs text-muted-foreground\">\n          {loading ? <Loader2 className=\"size-3.5 animate-spin\" /> : \"—\"}\n        </span>\n      ) : (\n        <div className=\"flex flex-col\">\n          {items.map((it) => (\n            <ActionRow key={it.action.action} item={it} onClick={() => onAdvance(it.action)} />\n          ))}\n        </div>\n      );\n  } else if (onSkip && !skipLoading && skipItems && skipItems.length > 0) {\n    body = (\n      <div className=\"flex flex-col\">\n        {skipItems.map((it) => (\n          <ActionRow\n            key={it.action.action}\n            item={it}\n            tone=\"dim\"\n            title={`Skip ahead — folds everyone before ${position}`}\n            onClick={() => onSkip(it.action)}\n          />\n        ))}\n      </div>\n    );\n  } else {\n    body = (\n      <span className=\"py-1 text-xs text-muted-foreground/50\">{skipLoading ? \"…\" : \"—\"}</span>\n    );\n  }\n\n  return (\n    <div\n      ref={cardRef}\n      className={`${RAIL_CARD} ${isActor ? \"border-foreground/50 bg-accent/50\" : \"border-border bg-card/40\"}`}\n    >\n      {header}\n      {body}\n    </div>\n  );\n}\n\nfunction EndCard({ end }: { end: EndState }) {\n  if (end.reason === \"won\") {\n    const winner = end.survivors[0];\n    return (\n      <div className=\"rounded-xl border border-border bg-card/40 px-4 py-3 text-sm text-muted-foreground\">\n        Hand ends preflop — {winner ? `${winner} wins uncontested` : \"everyone folded\"}. No\n        postflop play on this line.\n      </div>\n    );\n  }\n\n  const summary = `${end.survivors.join(\" / \")} — ${end.survivors.length}-way`;\n  const multiway = end.survivors.length >= 3;\n  // A host without the solver points heads-up lines to where they can be solved.\n  const elsewhere = multiway ? null : explorerHost().solveElsewhere;\n\n  return (\n    <div className=\"flex flex-col items-center gap-3 rounded-xl border border-dashed border-border bg-card/40 px-6 py-7 text-center\">\n      <span className=\"text-sm font-medium text-foreground\">\n        {multiway ? \"This line goes multiway postflop\" : \"This line goes heads-up to the flop\"}\n      </span>\n      <span className=\"text-xs text-muted-foreground\">\n        {summary} · pot {end.potBb.toFixed(1)}bb · {end.effStackBb.toFixed(1)}bb behind.\n      </span>\n      {elsewhere ? (\n        <a href={elsewhere.href} className={buttonVariants({ variant: \"outline\", size: \"sm\" })}>\n          {elsewhere.label}\n        </a>\n      ) : (\n        <span className=\"rounded-full border border-border px-3 py-1.5 text-xs text-muted-foreground/70\">\n          {multiway\n            ? \"Multiway postflop solving isn’t available yet\"\n            : \"Postflop solving for this game isn’t in the Explorer yet. The preflop ranges above are complete.\"}\n        </span>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/preflop-browser.tsx"
    },
    {
      "path": "src/components/explorer/preflop-strategy-grid.tsx",
      "content": "\"use client\";\n\n// The 13×13 preflop strategy grid for the Explorer. Unlike the postflop\n// `StrategyGrid` (which aggregates per-combo data), the preflop ranges API\n// hands us each action's per-class frequency directly (`NodeAction.weights`),\n// so a cell is just the stacked action split for that hand class.\n\nimport { useMemo } from \"react\";\nimport { ALL_HANDS, comboCountOf } from \"@/lib/solver/range-model\";\nimport {\n  sizedRaiseLabel,\n  sortActionsForDisplay,\n  type NodeAction,\n  type RaiseContext,\n} from \"@/lib/solver/preflop\";\nimport { ACTION_COLORS, HandMatrix, type MatrixCell } from \"@/components/solver/strategy-grid\";\nimport { actionPalette } from \"@/lib/pokerstudy/poker\";\n\n// Preflop reuses the postflop palette (ACTION_COLORS) so a color means the same\n// thing on both sides of the flop. The one addition: preflop nodes can offer\n// several raise sizes at once, so raises darken by size from the base Bet tone\n// to stay distinguishable when stacked in a single cell.\nconst RAISE_PALETTE = actionPalette().raises;\n\n/** Stable per-action colors for a node, ordered fold → call → raises → all-in. */\nexport function colorActions(actions: NodeAction[]): { action: NodeAction; color: string }[] {\n  const sorted = sortActionsForDisplay(actions);\n  let raiseIdx = 0;\n  return sorted.map((action) => {\n    let color: string;\n    if (action.kind === \"fold\") color = ACTION_COLORS.Fold;\n    else if (action.kind === \"call\") color = ACTION_COLORS.Call;\n    else if (action.kind === \"allin\") color = ACTION_COLORS.AllIn;\n    else color = RAISE_PALETTE[Math.min(raiseIdx++, RAISE_PALETTE.length - 1)];\n    return { action, color };\n  });\n}\n\nfunction labelFor(action: NodeAction, stack: number, ctx?: RaiseContext): string {\n  // A raise the feed sized (ICM sets) reads as a pot percentage.\n  const sized = ctx ? sizedRaiseLabel(action, ctx) : null;\n  if (sized) return sized;\n  if (action.kind === \"fold\") return \"Fold\";\n  if (action.action === \"Limp\") return \"Limp\";\n  if (action.kind === \"call\") return \"Call\";\n  if (action.kind === \"allin\" || action.action === \"AI\") return `All-in ${stack}`;\n  if (action.action === \"Open\") return \"Open\";\n  if (action.kind === \"raise\") return `Raise ${action.action}`;\n  return action.action;\n}\n\n/** One aggregate action row for the acting seat card: the action itself plus\n *  its display label, color, and combo-weighted frequency across the range —\n *  the same shape the postflop navigator's acting card renders. */\nexport interface PreflopActionItem {\n  action: NodeAction;\n  label: string;\n  color: string;\n  /** Aggregate frequency across the range, in [0, 1]. */\n  freq: number;\n  /** Combo-weighted count taking this action. */\n  combos: number;\n}\n\n/** Combo-weighted aggregate action frequencies, in display order. */\nexport function preflopActionItems(\n  actions: NodeAction[],\n  stack: number,\n  /** Where the actor stands; when given, sized raises read as pot percentages. */\n  ctx?: RaiseContext,\n): PreflopActionItem[] {\n  const colored = colorActions(actions);\n  // Total combos in the range = combos that take any action on the highest-\n  // weight basis; use the sum over the fold action's domain as the denominator\n  // proxy is unreliable, so weight every class by its combo count once.\n  let rangeCombos = 0;\n  for (const hand of ALL_HANDS) {\n    const any = colored.some(({ action }) => (action.weights[hand] ?? 0) > 0);\n    if (any) rangeCombos += comboCountOf(hand);\n  }\n  const denom = rangeCombos || 1;\n  return colored.map(({ action, color }) => {\n    let combos = 0;\n    for (const hand of ALL_HANDS) {\n      const w = action.weights[hand] ?? 0;\n      if (w > 0) combos += w * comboCountOf(hand);\n    }\n    return { action, label: labelFor(action, stack, ctx), color, freq: combos / denom, combos };\n  });\n}\n\nexport function PreflopStrategyGrid({\n  actions,\n  stack,\n  raiseContext,\n}: {\n  actions: NodeAction[];\n  /** Effective stack in bb — only used for the legend's all-in label. */\n  stack: number;\n  /** Where the actor stands; when given, sized raises read as pot percentages. */\n  raiseContext?: RaiseContext;\n}) {\n  const colored = useMemo(() => colorActions(actions), [actions]);\n\n  // Renders through the shared HandMatrix (the postflop grid's cells + legend),\n  // so preflop and postflop are literally the same grid. A class whose action\n  // frequencies sum to ~0 is out of range → the empty dark cell, like postflop.\n  const cells = useMemo<(MatrixCell | null)[]>(() => {\n    return ALL_HANDS.map((hand) => {\n      const freqs = colored.map(({ action }) => action.weights[hand] ?? 0);\n      const sum = freqs.reduce((s, f) => s + f, 0);\n      return sum > 0.001 ? { label: hand, freqs } : null;\n    });\n  }, [colored]);\n\n  const colors = useMemo(() => colored.map(({ color }) => color), [colored]);\n  const legend = useMemo(\n    () =>\n      colored.map(({ action, color }) => ({ label: labelFor(action, stack, raiseContext), color })),\n    [colored, stack, raiseContext],\n  );\n\n  const foldIndex = colored.findIndex(({ action }) => action.kind === \"fold\");\n  return (\n    <HandMatrix\n      cells={cells}\n      colors={colors}\n      legend={legend}\n      foldIndex={foldIndex < 0 ? undefined : foldIndex}\n      aggressiveFirst\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/preflop-strategy-grid.tsx"
    },
    {
      "path": "src/components/explorer/rail-row.tsx",
      "content": "\"use client\";\n\nimport type { ReactNode, Ref } from \"react\";\n\n/** The Explorer's action bar: an optional fixed lead card (the game/solution\n *  card) and the horizontally scrolling rail of decision cards beside it.\n *  Shared by the preflop strip and both postflop navigators, so the game card\n *  stays put on every street instead of scrolling away with the line. On\n *  phones the lead stacks above the rail; from `sm` up it sits to its left. */\nexport function RailRow({\n  lead,\n  scrollerRef,\n  children,\n}: {\n  lead?: ReactNode;\n  scrollerRef?: Ref<HTMLDivElement>;\n  children: ReactNode;\n}) {\n  const rail = (\n    <div\n      ref={scrollerRef}\n      className=\"relative flex min-w-0 flex-1 items-stretch gap-2 overflow-x-auto pb-1\"\n    >\n      {children}\n    </div>\n  );\n  if (!lead) return rail;\n  return (\n    <div className=\"flex flex-col gap-2 sm:flex-row sm:items-stretch\">\n      <div className=\"w-full shrink-0 sm:w-[196px]\">{lead}</div>\n      {rail}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/rail-row.tsx"
    },
    {
      "path": "src/components/explorer/range-grid-editor.tsx",
      "content": "\"use client\";\n\n// An editable 13×13 range grid. Seeded from a walked preflop line but fully\n// paintable: press and drag to set cells to full (1) or clear (0) — the drag\n// target is decided by the first cell you touch (GTO-Wizard-style). Rendered\n// inline in the Explorer's continuous solve panel so a player can tweak either\n// survivor's continue range before solving the flop.\n\nimport { useCallback, useEffect, useRef } from \"react\";\nimport { RotateCcw } from \"lucide-react\";\nimport {\n  ALL_HANDS,\n  fullRange,\n  totalCombos,\n  type RangePlayer,\n  type RangeWeights,\n} from \"@/lib/solver/range-model\";\nimport type { Position } from \"@/lib/solver/preflop\";\n\nconst FULL_COMBOS = 1326;\n\n/** True for the suited/pair upper triangle+diagonal — used only for a faint tint. */\nfunction isSuitedOrPair(index: number): boolean {\n  const r = Math.floor(index / 13);\n  const c = index % 13;\n  return r <= c;\n}\n\nexport function RangeGridEditor({\n  pos,\n  role,\n  weights,\n  onChange,\n  seed,\n}: {\n  pos: Position | string;\n  role: RangePlayer;\n  weights: RangeWeights;\n  onChange: (next: RangeWeights) => void;\n  /** The range as it came off the preflop line, for \"reset to line\". */\n  seed?: RangeWeights;\n}) {\n  // Paint state: which value we're stamping while the pointer is down.\n  const painting = useRef<number | null>(null);\n\n  const paint = useCallback(\n    (hand: string, value: number) => {\n      if ((weights[hand] ?? 0) === value) return;\n      onChange({ ...weights, [hand]: value });\n    },\n    [weights, onChange],\n  );\n\n  const onCellDown = (hand: string) => {\n    const target = (weights[hand] ?? 0) >= 0.5 ? 0 : 1;\n    painting.current = target;\n    paint(hand, target);\n  };\n\n  const onCellEnter = (hand: string) => {\n    if (painting.current === null) return;\n    paint(hand, painting.current);\n  };\n\n  // Release the paint stroke anywhere on the document, not just over a cell.\n  useEffect(() => {\n    const stop = () => {\n      painting.current = null;\n    };\n    window.addEventListener(\"pointerup\", stop);\n    window.addEventListener(\"pointercancel\", stop);\n    return () => {\n      window.removeEventListener(\"pointerup\", stop);\n      window.removeEventListener(\"pointercancel\", stop);\n    };\n  }, []);\n\n  const combos = totalCombos(weights);\n  const pct = (combos / FULL_COMBOS) * 100;\n\n  const setAll = (mode: \"full\" | \"clear\" | \"seed\") => {\n    if (mode === \"seed\" && seed) onChange({ ...seed });\n    else if (mode === \"full\") onChange(fullRange());\n    else if (mode === \"clear\") onChange({});\n  };\n\n  return (\n    <div className=\"flex flex-col gap-2 rounded-xl border border-border bg-card/40 p-3\">\n      <div className=\"flex items-center justify-between gap-2\">\n        <div className=\"flex items-center gap-1.5\">\n          <span className=\"text-sm font-semibold text-foreground\">{pos}</span>\n          <span\n            className={`rounded px-1 py-px text-[8px] font-bold tracking-wide ${\n              role === \"oop\"\n                ? \"bg-foreground text-background\"\n                : \"border border-foreground/50 text-foreground\"\n            }`}\n          >\n            {role.toUpperCase()}\n          </span>\n        </div>\n        <span className=\"text-[11px] tabular-nums text-muted-foreground\">\n          {combos.toFixed(1)} combos · {pct.toFixed(1)}%\n        </span>\n      </div>\n\n      {/* The grid. touch-none so a drag paints instead of scrolling on mobile. */}\n      <div className=\"grid touch-none select-none grid-cols-[repeat(13,minmax(0,1fr))] gap-px\">\n        {ALL_HANDS.map((hand, i) => {\n          const w = weights[hand] ?? 0;\n          const on = w > 0;\n          return (\n            <button\n              key={hand}\n              type=\"button\"\n              onPointerDown={(e) => {\n                e.preventDefault();\n                onCellDown(hand);\n              }}\n              onPointerEnter={() => onCellEnter(hand)}\n              title={hand}\n              className={`flex aspect-square items-center justify-center rounded-[2px] text-[6px] font-medium leading-none transition-colors ${\n                on\n                  ? \"bg-foreground text-background\"\n                  : isSuitedOrPair(i)\n                    ? \"bg-foreground/10 text-muted-foreground/50\"\n                    : \"bg-foreground/[0.04] text-muted-foreground/40\"\n              }`}\n              style={on ? { opacity: 0.4 + 0.6 * Math.min(w, 1) } : undefined}\n            >\n              {hand}\n            </button>\n          );\n        })}\n      </div>\n\n      <div className=\"flex items-center gap-1.5\">\n        <GridBtn onClick={() => setAll(\"full\")}>Full</GridBtn>\n        <GridBtn onClick={() => setAll(\"clear\")}>Clear</GridBtn>\n        {seed ? (\n          <GridBtn onClick={() => setAll(\"seed\")}>\n            <RotateCcw className=\"size-3\" /> Reset to line\n          </GridBtn>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\nfunction GridBtn({ onClick, children }: { onClick: () => void; children: React.ReactNode }) {\n  return (\n    <button\n      type=\"button\"\n      onClick={onClick}\n      className=\"flex items-center gap-1 rounded-md border border-border bg-card px-2 py-1 text-[11px] text-foreground transition-colors hover:bg-accent\"\n    >\n      {children}\n    </button>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/range-grid-editor.tsx"
    },
    {
      "path": "src/components/explorer/solution-selector.tsx",
      "content": "\"use client\";\n\n// Solution selector. A compact card shows the current solution (format · stack\n// · raises) with a \"Change\" button; clicking it opens the solutions drawer:\n// the shared SidePanel in its wide size (a bottom drawer on phones, a wide\n// right-hand panel on desktop) with game / format / players / rake facets\n// (React Bits Pro App UI `filtering-1`) in a left rail beside one frame per\n// solution set listing its stacks. Picking a browsable stack switches the\n// Explorer. Solutions we can't walk yet are listed but inert: this is a picker,\n// not a storefront: the one Download button hands the pack on screen to the\n// download gate (`/api/downloads/[id]`). Downloads are Studio only: the gate\n// sends everyone else to /pricing, and once the ranges session says the plan\n// isn't Studio the button shows a lock pointing there instead.\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport Link from \"next/link\";\nimport { Download, Link2, Lock, Settings2, ShoppingBag } from \"lucide-react\";\nimport { explorerHost } from \"@/lib/explorer/host\";\nimport { toast } from \"sonner\";\nimport type { Plan } from \"@/lib/access/policy\";\nimport { ensureRangesSession } from \"@/lib/access/session-client\";\nimport { SidePanel } from \"@/components/ui/side-panel\";\nimport {\n  ActiveFilterChips,\n  EmptyResults,\n  FacetGroup,\n  FacetRadioList,\n  FacetRail,\n  FilterToggleButton,\n  ResultChoice,\n  ResultFrame,\n  filteringTokens,\n} from \"@/components/blocks/filtering-1\";\nimport {\n  defaultTable,\n  packIdFor,\n  raisesFor,\n  RAKE_TIER_LABEL,\n  solveCount,\n  SOLUTION_GROUPS,\n  type FormatKind,\n  type GameKind,\n  type PlayersKind,\n  type RakeTier,\n  type SolutionGroup,\n} from \"@/lib/explorer/solution-catalog\";\n\ninterface Props {\n  group: SolutionGroup;\n  stack: number;\n  /** ICM sets: the stack table on screen (a scenario id). */\n  table?: string | null;\n  /** Stacks present in the ranges manifest (browsable rows gate on this). */\n  availableStacks: number[];\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  onSelect: (groupId: string, stack: number, table?: string | null) => void;\n  /** When set, the drawer only lists stacks in this catalog group. */\n  onlyGroupId?: string;\n  /** Show a \"Copy link\" button for the current address (the explorer keeps\n   *  its view in the URL, so the address is a link to this exact spot). */\n  shareable?: boolean;\n}\n\n/** Copy the page's address. The URL already carries the view, so this is the\n *  share link. Falls back to a prompt where the clipboard is blocked. */\nasync function copyCurrentLink() {\n  const href = window.location.href;\n  try {\n    await navigator.clipboard.writeText(href);\n    toast.success(\"Link copied\", { description: \"Anyone with the link opens this exact view.\" });\n  } catch {\n    window.prompt(\"Copy this link\", href);\n  }\n}\n\nexport function SolutionSelectorCard({\n  group,\n  stack,\n  table = null,\n  availableStacks,\n  open,\n  onOpenChange,\n  onSelect,\n  onlyGroupId,\n  shareable = false,\n}: Props) {\n  const raises = raisesFor(group, stack);\n  const tableInfo = defaultTable(group, stack, table);\n  const packId = packIdFor(group.id, stack);\n  // Hosts that sell packs on a page (pokerdata.io) link there; pokerstudy.ai\n  // hands the pack to its download gate.\n  const host = explorerHost();\n  const downloadHref = packId && host.downloadHref ? host.downloadHref(packId) : null;\n  const packHref = packId && !downloadHref && host.packHref ? host.packHref(packId) : null;\n  // Null until the session read lands; the gate checks again on click.\n  const [plan, setPlan] = useState<Plan | null>(null);\n  useEffect(() => {\n    let live = true;\n    void ensureRangesSession().then((s) => {\n      if (live && s) setPlan(s.plan);\n    });\n    return () => {\n      live = false;\n    };\n  }, []);\n  const locked = plan !== null && plan !== \"studio\";\n  return (\n    <div className=\"relative w-full\">\n      {/* Same frame as a strip card (min-h-[104px]) — it sits inline with them. */}\n      <div className=\"flex min-h-[104px] flex-col gap-1 rounded-xl border border-border bg-card/40 p-2.5\">\n        <div className=\"flex items-start justify-between gap-1\">\n          <span className=\"text-sm font-semibold leading-tight text-foreground\">\n            {group.format.split(\" · \")[0]}{\" \"}\n            <span className=\"whitespace-nowrap text-muted-foreground\">\n              {stack}\n              <span className=\"align-super text-[9px]\">bb</span>\n            </span>\n          </span>\n          <div className=\"flex shrink-0 items-center gap-1\">\n          {packHref ? (\n            <Link\n              href={packHref}\n              title=\"Get this pack\"\n              aria-label=\"Get this pack\"\n              className=\"flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n            >\n              <ShoppingBag className=\"size-4\" />\n            </Link>\n          ) : downloadHref && locked ? (\n            <Link\n              href=\"/pricing?from=downloads\"\n              title=\"Downloads are part of Studio\"\n              aria-label=\"Downloads are part of Studio\"\n              className=\"flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n            >\n              <Lock className=\"size-4\" />\n            </Link>\n          ) : downloadHref ? (\n            <a\n              href={downloadHref}\n              title=\"Download this pack\"\n              aria-label=\"Download this pack\"\n              className=\"flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n            >\n              <Download className=\"size-4\" />\n            </a>\n          ) : null}\n          {shareable ? (\n            // ui-exception: same icon button as Download / Change beside it, so the card's action row stays one set\n            <button\n              type=\"button\"\n              onClick={() => void copyCurrentLink()}\n              title=\"Copy link to this view\"\n              aria-label=\"Copy link to this view\"\n              className=\"flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n            >\n              <Link2 className=\"size-4\" />\n            </button>\n          ) : null}\n          <button\n            type=\"button\"\n            onClick={() => onOpenChange(!open)}\n            title=\"Change solution\"\n            aria-label=\"Change solution\"\n            className={`flex size-7 shrink-0 items-center justify-center rounded-md border transition-colors ${\n              open\n                ? \"border-foreground/50 bg-accent text-foreground\"\n                : \"border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground\"\n            }`}\n          >\n            <Settings2 className=\"size-4\" />\n          </button>\n          </div>\n        </div>\n        <ul className=\"flex flex-col gap-0.5 text-[11px] text-muted-foreground\">\n          <li>• {group.format.split(\" · \")[1] ?? group.format}</li>\n          {tableInfo ? (\n            <li className=\"truncate\" title={`${tableInfo.label} table, ${stack}bb average`}>\n              • {tableInfo.label}, {stack}bb avg\n            </li>\n          ) : (\n            <li className=\"truncate\" title={raises ?? group.rake}>\n              • {raises ?? group.rake}\n            </li>\n          )}\n        </ul>\n      </div>\n\n      {open ? (\n        <SolutionsLibrary\n          group={group}\n          stack={stack}\n          table={tableInfo?.scenario ?? null}\n          availableStacks={availableStacks}\n          onlyGroupId={onlyGroupId}\n          onClose={() => onOpenChange(false)}\n          onSelect={(g, s, t) => {\n            onSelect(g, s, t);\n            onOpenChange(false);\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\ntype Any = \"any\";\ntype Facets = {\n  game: Any | GameKind;\n  format: Any | FormatKind;\n  players: Any | PlayersKind;\n  rake: Any | RakeTier;\n};\nconst NO_FILTERS: Facets = { game: \"any\", format: \"any\", players: \"any\", rake: \"any\" };\n\nconst GAME_FILTERS: { value: Any | GameKind; label: string }[] = [\n  { value: \"any\", label: \"All games\" },\n  { value: \"holdem\", label: \"Hold'em\" },\n  { value: \"omaha\", label: \"Omaha (PLO 4)\" },\n  { value: \"plo5\", label: \"PLO 5\" },\n  { value: \"plo6\", label: \"PLO 6\" },\n];\nconst FORMAT_FILTERS: { value: Any | FormatKind; label: string }[] = [\n  { value: \"any\", label: \"Any\" },\n  { value: \"cash\", label: \"Cash\" },\n  { value: \"tournament\", label: \"Tournaments\" },\n];\nconst PLAYER_FILTERS: { value: Any | PlayersKind; label: string }[] = [\n  { value: \"any\", label: \"Any\" },\n  { value: \"hu\", label: \"Heads-up\" },\n  { value: \"6max\", label: \"6-max\" },\n  { value: \"8max\", label: \"8-max\" },\n  { value: \"9max\", label: \"9-max\" },\n];\nconst RAKE_FILTERS: { value: Any | RakeTier; label: string }[] = [\n  { value: \"any\", label: \"Any\" },\n  { value: \"low\", label: RAKE_TIER_LABEL.low },\n  { value: \"mid\", label: RAKE_TIER_LABEL.mid },\n  { value: \"high\", label: RAKE_TIER_LABEL.high },\n  { value: \"chipev\", label: RAKE_TIER_LABEL.chipev },\n  { value: \"icm\", label: RAKE_TIER_LABEL.icm },\n];\n\nconst PLAYERS_LABEL: Record<PlayersKind, string> = {\n  hu: \"Heads-up\",\n  \"6max\": \"6-max\",\n  \"8max\": \"8-max\",\n  \"9max\": \"9-max\",\n};\n\n/** Does a group pass every facet, optionally ignoring one (for its counts)? */\nfunction matches(g: SolutionGroup, f: Facets, skip?: keyof Facets): boolean {\n  return (\n    (skip === \"game\" || f.game === \"any\" || g.game === f.game) &&\n    (skip === \"format\" || f.format === \"any\" || g.formatKind === f.format) &&\n    (skip === \"players\" || f.players === \"any\" || g.players === f.players) &&\n    (skip === \"rake\" || f.rake === \"any\" || g.rakeTier === f.rake)\n  );\n}\n\nfunction SolutionsLibrary({\n  group,\n  stack,\n  table,\n  availableStacks: _availableStacks,\n  onlyGroupId,\n  onClose,\n  onSelect,\n}: {\n  group: SolutionGroup;\n  stack: number;\n  table: string | null;\n  availableStacks: number[];\n  onlyGroupId?: string;\n  onClose: () => void;\n  onSelect: (groupId: string, stack: number, table?: string | null) => void;\n}) {\n  const [facets, setFacets] = useState<Facets>(NO_FILTERS);\n  // Phones show the rail on demand (it would push every solution below the fold).\n  const [railOpen, setRailOpen] = useState(false);\n  const set = <K extends keyof Facets>(key: K, value: Facets[K]) =>\n    setFacets((f) => ({ ...f, [key]: value }));\n\n  const groups = useMemo(\n    () =>\n      onlyGroupId\n        ? SOLUTION_GROUPS.filter((g) => g.id === onlyGroupId)\n        : SOLUTION_GROUPS,\n    [onlyGroupId],\n  );\n  const shown = groups.filter((g) => matches(g, facets));\n  const solutionCount = (list: SolutionGroup[]) =>\n    list.reduce((n, g) => n + g.stacks.reduce((m, s) => m + solveCount(s), 0), 0);\n  const total = solutionCount(shown);\n\n  /** Facet options with the count each would show, given the other facets. */\n  const withCounts = <T extends string>(\n    key: keyof Facets,\n    options: { value: T; label: string }[],\n    field: (g: SolutionGroup) => string,\n  ) =>\n    options.map((o) => ({\n      ...o,\n      count: solutionCount(\n        groups.filter(\n          (g) => matches(g, facets, key) && (o.value === \"any\" || field(g) === o.value),\n        ),\n      ),\n    }));\n\n  const chips = (\n    [\n      [\"game\", GAME_FILTERS],\n      [\"format\", FORMAT_FILTERS],\n      [\"players\", PLAYER_FILTERS],\n      [\"rake\", RAKE_FILTERS],\n    ] as const\n  ).flatMap(([key, options]) =>\n    facets[key] === \"any\"\n      ? []\n      : [\n          {\n            key,\n            label: (options as readonly { value: string; label: string }[]).find(\n              (o) => o.value === facets[key],\n            )!.label,\n            onRemove: () => set(key, \"any\"),\n          },\n        ],\n  );\n\n  const filterable = !onlyGroupId;\n  const rail = (\n    <FacetRail>\n      <FacetGroup label=\"Game\">\n        <FacetRadioList\n          name=\"solutions-game\"\n          options={withCounts(\"game\", GAME_FILTERS, (g) => g.game)}\n          value={facets.game}\n          onChange={(v) => set(\"game\", v)}\n        />\n      </FacetGroup>\n      <FacetGroup label=\"Format\">\n        <FacetRadioList\n          name=\"solutions-format\"\n          options={withCounts(\"format\", FORMAT_FILTERS, (g) => g.formatKind)}\n          value={facets.format}\n          onChange={(v) => set(\"format\", v)}\n        />\n      </FacetGroup>\n      <FacetGroup label=\"Players\">\n        <FacetRadioList\n          name=\"solutions-players\"\n          options={withCounts(\"players\", PLAYER_FILTERS, (g) => g.players)}\n          value={facets.players}\n          onChange={(v) => set(\"players\", v)}\n        />\n      </FacetGroup>\n      <FacetGroup label=\"Rake\">\n        <FacetRadioList\n          name=\"solutions-rake\"\n          options={withCounts(\"rake\", RAKE_FILTERS, (g) => g.rakeTier)}\n          value={facets.rake}\n          onChange={(v) => set(\"rake\", v)}\n        />\n      </FacetGroup>\n    </FacetRail>\n  );\n\n  return (\n    <SidePanel\n      title=\"Solutions\"\n      onClose={onClose}\n      size=\"wide\"\n      bodyClassName=\"flex flex-col gap-5 px-5 py-5 md:flex-row md:gap-8\"\n    >\n      {filterable ? (\n        // Facet rail on the left from md up; phones open it under \"Filters\" below.\n        <aside className=\"hidden w-56 shrink-0 self-start md:block\">\n          {rail}\n        </aside>\n      ) : null}\n\n      <div className=\"flex min-w-0 flex-1 flex-col gap-4\">\n        <div className=\"flex flex-wrap items-center justify-between gap-3\">\n          <p className={filteringTokens.metaText}>\n            <span className={`tabular-nums ${filteringTokens.text1}`}>{total}</span>{\" \"}\n            {total === 1 ? \"solution\" : \"solutions\"} in{\" \"}\n            <span className=\"tabular-nums\">{shown.length}</span>{\" \"}\n            {shown.length === 1 ? \"set\" : \"sets\"}\n          </p>\n          {filterable ? (\n            <FilterToggleButton\n              className=\"md:hidden\"\n              open={railOpen}\n              count={chips.length}\n              onClick={() => setRailOpen((v) => !v)}\n            />\n          ) : null}\n        </div>\n\n        {filterable && railOpen ? (\n          <div className=\"border-b border-border pb-5 md:hidden\">{rail}</div>\n        ) : null}\n\n        <ActiveFilterChips chips={chips} onClearAll={() => setFacets(NO_FILTERS)} />\n\n        {shown.length === 0 ? (\n          <EmptyResults\n            title=\"No solutions match these filters\"\n            description=\"Clear a filter to see the rest of the library. Tournament solves are chip EV or ICM, so they don't show under a stakes filter.\"\n            onClear={() => setFacets(NO_FILTERS)}\n          />\n        ) : (\n          <div className=\"flex flex-col gap-3\">\n            {shown.map((g) => (\n              <ResultFrame\n                key={g.id}\n                title={g.format}\n                meta={`Rake: ${g.rake.replace(/^rake /, \"\")}`}\n                tags={[\n                  g.formatKind === \"tournament\" ? \"Tournament\" : \"Cash\",\n                  RAKE_TIER_LABEL[g.rakeTier],\n                  PLAYERS_LABEL[g.players],\n                ]}\n                // Listed so the catalog reads honestly, but not walkable yet.\n                aside={g.browsable ? null : \"Download only\"}\n                muted={!g.browsable}\n              >\n                {g.stacks.some((s) => s.tables?.length) ? (\n                  // ICM: one row per average depth, one choice per stack table\n                  // (even stacks, a short or big stack in one seat, mixed).\n                  <div className=\"flex flex-col gap-3\">\n                    {g.stacks.map((s) => (\n                      <div key={s.stack} className=\"flex flex-col gap-1.5\">\n                        <span className={filteringTokens.captionText}>\n                          {s.stack}bb average · {s.tables?.length ?? 0} tables\n                        </span>\n                        <div className=\"flex flex-wrap gap-2\">\n                          {(s.tables ?? []).map((t) => (\n                            <ResultChoice\n                              key={t.scenario}\n                              label={t.label}\n                              title={`${t.label}, ${s.stack}bb average · ${s.raises}`}\n                              current={\n                                g.id === group.id && s.stack === stack && t.scenario === table\n                              }\n                              disabled={!g.browsable}\n                              onClick={() => onSelect(g.id, s.stack, t.scenario)}\n                            />\n                          ))}\n                        </div>\n                      </div>\n                    ))}\n                  </div>\n                ) : (\n                  <div className=\"flex flex-wrap gap-2\">\n                    {g.stacks.map((s) => (\n                      <ResultChoice\n                        key={s.stack}\n                        label={`${s.stack}bb`}\n                        title={s.raises}\n                        current={g.id === group.id && s.stack === stack}\n                        disabled={!g.browsable}\n                        onClick={() => onSelect(g.id, s.stack)}\n                      />\n                    ))}\n                  </div>\n                )}\n              </ResultFrame>\n            ))}\n          </div>\n        )}\n      </div>\n    </SidePanel>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/solution-selector.tsx"
    },
    {
      "path": "src/components/explorer/solution-viewer.tsx",
      "content": "\"use client\";\n\n// The postflop solution viewer (#231) — GTO-Wizard-style study view over a\n// solved `CustomSolutionBundle`:\n//\n//   • top bar: the action-sequence breadcrumb (street cards + each taken\n//     action, actor-labelled), clickable to jump back;\n//   • center: the 13×13 strategy matrix (stacked action-frequency cells);\n//   • right: the acting position + pot, an action summary (one wide bar per\n//     action: label, size, % of range, combos — click to advance), and the\n//     per-combo hand summary (strategy bar, EV, range share);\n//   • at chance nodes: a card picker over the live deck.\n//\n// The bundle only carries strategies to `dump_max_deals` chance deals past its\n// start street. Picking a runout past that horizon solves the subgame on\n// demand: the reach-weighted ranges at the chance node are derived by walking\n// the bundle's own per-node strategies (lib/explorer/subgame.ts), the child\n// request goes through the normal `/api/solver/jobs` flow, and the result is\n// spliced in as a navigable sub-solution, cached client-side by path.\n\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport Link from \"next/link\";\nimport { ArrowLeft, Dumbbell, Loader2, Lock, Pencil, X } from \"lucide-react\";\nimport { StrategyGrid, ACTION_COLORS } from \"@/components/solver/strategy-grid\";\nimport { PostflopHandSummary } from \"./postflop-hand-summary\";\nimport { LockEditor } from \"./lock-editor\";\nimport { NodeEditModal } from \"./node-edit-modal\";\nimport { BottomSheet } from \"./bottom-sheet\";\nimport { startSolve, type SolveHandle } from \"@/lib/solver/client\";\nimport type {\n  LockedNode,\n  SolveRequest,\n  SolverProgress,\n  SolverResult,\n} from \"@/lib/solver/types\";\nimport type { CustomSolutionBundle } from \"@/lib/explorer/types\";\nimport { buildAggregateLock, MAX_LOCKED_NODES } from \"@/lib/explorer/locks\";\nimport { carryForChild } from \"@/lib/explorer/resolve-carry\";\nimport {\n  actionSegment,\n  boardCards,\n  buildChildRequest,\n  dealCard,\n  isDealSegment,\n  isPathPrefix,\n  nextSegments,\n  nodeAtPath,\n  walkReach,\n  type ReachState,\n} from \"@/lib/explorer/subgame\";\nimport { MiniCard } from \"@/components/trainer/cards\";\nimport { suitTile } from \"@/components/trainer/theme\";\nimport { RailRow } from \"./rail-row\";\n\n// ---------------------------------------------------------------------------\n// Card rendering (matches the Explorer's 4-color deck)\n// ---------------------------------------------------------------------------\n\nconst SUIT_GLYPH: Record<string, string> = { s: \"♠\", h: \"♥\", d: \"♦\", c: \"♣\" };\n\nfunction CardText({ card, className = \"h-5 w-4 text-[13px]\" }: { card: string; className?: string }) {\n  return <MiniCard card={card} className={className} />;\n}\n\n// ---------------------------------------------------------------------------\n// Navigation model\n// ---------------------------------------------------------------------------\n\ninterface SubSolve {\n  config: SolveRequest;\n  result: SolverResult;\n  /** How the child was rooted (#233): \"gadget\" = CFR-D safe re-solve with\n   *  carried opponent-CFV promises (runout-averaged today, see\n   *  resolve-carry.ts); \"reach\" = legacy reach-range bootstrap. */\n  resolveMode: \"gadget\" | \"reach\";\n}\n\n/** One node in the walked line — a street (board cards) or a taken action. */\ninterface Crumb {\n  index: number; // path.slice(0, index) jumps here\n  kind: \"street\" | \"action\";\n  text: string;\n  card?: string;\n  cards?: string[];\n  actor?: string;\n  /** The node this action was taken at is locked (#268) — either in the\n   *  solve's dump (`locked: true`) or as a pending edit in this session. */\n  locked?: boolean;\n}\n\n/** Strategy-edit wiring (#268), passed by the builder when the bundle has a\n *  warm-startable base job. Absent (saved/sample solutions, AI solves,\n *  what-if results): the viewer is read-only, badges still render. */\nexport interface ViewerLocking {\n  /** Issue the locked re-solve with the collected edits. */\n  onResolve: (locks: LockedNode[]) => void;\n  /** A locked re-solve is currently running. */\n  busy: boolean;\n}\n\n/** Structural node editing (#390): change the ACTION SET (bet sizes / all-in)\n *  at one node and re-solve the whole tree. Passed by the builder — absent on\n *  saved/sample bundles, where the tree is fixed. Paths use the engine's\n *  node-edit encoding (deal steps as generic \"deal\"). */\nexport interface ViewerNodeEditing {\n  /** Apply one node's new sizes (pot fractions) + all-in flag, then re-solve. */\n  onApply: (path: string[], sizes: number[], allin: boolean) => void;\n  /** Drop every node edit in the tree, then re-solve. */\n  onClearAll: () => void;\n  /** Node-edit paths currently active (keys joined with a space). */\n  editedKeys: string[];\n  /** The re-solve is running. */\n  busy: boolean;\n}\n\n/** Viewer path → engine node-edit path: deal segments become generic \"deal\". */\nconst toEditPath = (path: readonly string[]) =>\n  path.map((s) => (isDealSegment(s) ? \"deal\" : s));\n\n/** Aggregate, reach-weighted action at the acting node (shared strip ↔ panel). */\ninterface StripActionItem {\n  seg: string;\n  label: string;\n  add: number;\n  color: string;\n  freq: number;\n  combos: number;\n}\n\nconst keyOf = (path: readonly string[]) => path.join(\" \");\n\n/** The solution (root bundle or spliced sub-solve) whose dump contains `path`. */\nfunction containingSolution(\n  bundle: CustomSolutionBundle,\n  subs: Record<string, SubSolve>,\n  path: readonly string[],\n): {\n  config: SolveRequest;\n  result: SolverResult;\n  base: string[];\n  resolveMode: SubSolve[\"resolveMode\"] | null;\n} {\n  let best: ReturnType<typeof containingSolution> = {\n    config: bundle.config,\n    result: bundle.result,\n    base: [],\n    resolveMode: null, // the root bundle is the equilibrium itself, not a re-solve\n  };\n  for (const [key, sub] of Object.entries(subs)) {\n    const base = key === \"\" ? [] : key.split(\" \");\n    if (base.length > best.base.length && isPathPrefix(base, path)) {\n      best = { config: sub.config, result: sub.result, base, resolveMode: sub.resolveMode };\n    }\n  }\n  return best;\n}\n\nfunction streetNameForBoardLen(len: number): string {\n  if (len <= 3) return \"Flop\";\n  return len === 4 ? \"Turn\" : \"River\";\n}\n\n// ---------------------------------------------------------------------------\n// Viewer\n// ---------------------------------------------------------------------------\n\nexport function SolutionViewer({\n  bundle,\n  onBack,\n  drillHref,\n  embedded = false,\n  stripPrefix,\n  stripLead,\n  locking,\n  nodeEditing,\n}: {\n  bundle: CustomSolutionBundle;\n  onBack?: () => void;\n  /** Link to drill this solution in the trainer. Set only for the user's own\n   *  saved solves — they're the ones that become `custom:` drill packs. */\n  drillHref?: string;\n  /** Rendered as a continuation of another navigator (the Explorer's preflop\n   *  strip): drops the redundant title header, keeps the breadcrumb + action\n   *  selector so it reads as one continuous walk rather than a nested viewer. */\n  embedded?: boolean;\n  /** (embedded) Leading cards for the decision strip — the preflop seat cards,\n   *  so the preflop line + postflop tree render as one continuous action bar. */\n  stripPrefix?: ReactNode;\n  /** (embedded) The game card, pinned left of the strip (above it on phones). */\n  stripLead?: ReactNode;\n  /** Enables \"Edit strategy\" node locking (#268) — see `ViewerLocking`. */\n  locking?: ViewerLocking;\n  /** Enables structural node edits (#390) — see `ViewerNodeEditing`. */\n  nodeEditing?: ViewerNodeEditing;\n}) {\n  const [path, setPath] = useState<string[]>([]);\n  const [subs, setSubs] = useState<Record<string, SubSolve>>({});\n  const [solving, setSolving] = useState<{ card: string; street: string } | null>(null);\n  const [progress, setProgress] = useState<SolverProgress | null>(null);\n  const [solveError, setSolveError] = useState<string | null>(null);\n  // Pending strategy edits (#268), keyed by the absolute path — sent as\n  // aggregate locks on \"Re-solve with edits\". Kept even while browsing away\n  // so several nodes can be edited before one re-solve.\n  const [locks, setLocks] = useState<Record<string, { path: string[]; freqs: number[] }>>({});\n  // Path key the lock editor is open at — navigating elsewhere implicitly\n  // closes it (no effect needed: the key no longer matches).\n  const [editorAt, setEditorAt] = useState<string | null>(null);\n  // Same pattern for the structural Edit Node modal (#390).\n  const [nodeEditorAt, setNodeEditorAt] = useState<string | null>(null);\n  // (embedded) Chance-node card picking happens in a bottom drawer — the same\n  // fluid gesture as picking the flop in the Explorer. Auto-opens on arriving\n  // at a chance node; the strip's dashed card reopens it if dismissed.\n  const [chancePickerOpen, setChancePickerOpen] = useState(false);\n  const handleRef = useRef<SolveHandle | null>(null);\n  const solveSeq = useRef(0);\n\n  const { meta } = bundle;\n  const ctx = useMemo(() => containingSolution(bundle, subs, path), [bundle, subs, path]);\n  const rel = useMemo(() => path.slice(ctx.base.length), [path, ctx]);\n  const ctxNodes = useMemo(() => ctx.result.nodes ?? [], [ctx]);\n  const node = useMemo(() => nodeAtPath(ctxNodes, rel), [ctxNodes, rel]);\n  const segs = useMemo(() => nextSegments(ctxNodes, rel), [ctxNodes, rel]);\n\n  // ---- node locking (#268) ----------------------------------------------------\n\n  const pathKey = keyOf(path);\n  const pendingLock = locks[pathKey];\n  const lockCount = Object.keys(locks).length;\n  // Edits are scoped to the base solution's own dump: a spliced sub-solve is a\n  // different engine job whose action encoding (re-rooted pot → re-derived bet\n  // amounts) can drift from the base tree's path labels, and the base job's\n  // snapshot is what the locked re-solve warm-starts from.\n  const canEditHere = Boolean(locking) && !!node && ctx.base.length === 0;\n  const editingLock = editorAt === pathKey;\n  const setEditingLock = (open: boolean) => setEditorAt(open ? pathKey : null);\n  // Structural node edits share the same base-solution-only scope.\n  const canEditNodeHere = Boolean(nodeEditing) && !!node && ctx.base.length === 0;\n  const nodeEditOpen = nodeEditorAt === pathKey;\n  const nodeEdited =\n    canEditNodeHere && (nodeEditing?.editedKeys.includes(toEditPath(path).join(\" \")) ?? false);\n\n  // The node as displayed: a pending aggregate lock overrides every combo's\n  // strategy, so the grid + summaries show exactly what the lock will play.\n  const displayNode = useMemo(() => {\n    if (!node || !pendingLock) return node;\n    return { ...node, hands: node.hands.map((h) => ({ ...h, freqs: pendingLock.freqs })) };\n  }, [node, pendingLock]);\n\n  const applyLock = (freqs: number[]) => {\n    setLocks((m) => ({ ...m, [pathKey]: { path: [...path], freqs } }));\n    setEditingLock(false);\n  };\n\n  const removeLock = () => {\n    setLocks((m) => {\n      const next = { ...m };\n      delete next[pathKey];\n      return next;\n    });\n    setEditingLock(false);\n  };\n\n  const resolveWithLocks = () => {\n    if (!locking || locking.busy) return;\n    try {\n      const lockedNodes = Object.values(locks).map((l) => {\n        const n = nodeAtPath(bundle.result.nodes ?? [], l.path);\n        if (!n) {\n          throw new Error(`locked node at \"${l.path.join(\" › \")}\" is not in this solution`);\n        }\n        return buildAggregateLock(l.path, n, l.freqs);\n      });\n      locking.onResolve(lockedNodes);\n    } catch (e) {\n      setSolveError(e instanceof Error ? e.message : String(e));\n    }\n  };\n\n  // Full board = root board + every dealt card along the (absolute) path.\n  const baseBoard = useMemo(() => boardCards(bundle.config.board), [bundle]);\n  const runout = useMemo(\n    () => path.filter(isDealSegment).map(dealCard),\n    [path],\n  );\n  const fullBoard = useMemo(() => [...baseBoard, ...runout], [baseBoard, runout]);\n\n  // Reach state at the current point, inside the containing solution (whose\n  // config ranges already encode reach up to its root).\n  const reach: ReachState | null = useMemo(() => {\n    try {\n      return walkReach(ctx.config, ctx.result, rel);\n    } catch {\n      return null;\n    }\n  }, [ctx, rel]);\n\n  // Per-combo EV is only dumped at solve roots (the bundle's start node and\n  // each spliced sub-solve's start node).\n  const evByCombo = useMemo(() => {\n    if (rel.length !== 0) return null;\n    const m = new Map<string, number>();\n    for (const h of ctx.result.root.hands) if (h.ev !== undefined) m.set(h.combo, h.ev);\n    return m.size > 0 ? m : null;\n  }, [ctx, rel]);\n\n  const actorReach = node ? (node.player === 0 ? reach?.oop : reach?.ip) ?? null : null;\n\n  // Aggregate, reach-weighted action items for the summary panel — computed\n  // over the DISPLAYED strategy, so a pending lock's split shows everywhere.\n  const actionItems = useMemo(() => {\n    if (!displayNode) return [];\n    const n = displayNode.actions.length;\n    const sums = new Array<number>(n).fill(0);\n    let denom = 0;\n    for (const hand of displayNode.hands) {\n      const w = actorReach ? (actorReach.get(hand.combo) ?? 0) : 1;\n      if (w <= 0) continue;\n      denom += w;\n      for (let a = 0; a < n; a++) sums[a] += w * (hand.freqs[a] ?? 0);\n    }\n    return displayNode.actions.map((action, a) => ({\n      seg: actionSegment(action),\n      label: action.label,\n      add: action.add,\n      color: ACTION_COLORS[action.label],\n      freq: denom > 0 ? sums[a] / denom : 0,\n      combos: sums[a],\n    }));\n  }, [displayNode, actorReach]);\n\n  // ---- chance-node handling -------------------------------------------------\n\n  const isChance = !node && (segs.length > 0 ? segs.every(isDealSegment) : chanceHeuristic());\n\n  function chanceHeuristic(): boolean {\n    if (path.length === 0) return false;\n    const last = path[path.length - 1];\n    if (isDealSegment(last) || last === \"Fold\") return false;\n    if (fullBoard.length >= 5) return false;\n    if (reach && reach.effStack <= 0.01) return false;\n    return true;\n  }\n\n  const availableCards = useMemo(() => {\n    const set = new Set(segs.filter(isDealSegment).map(dealCard));\n    // Sub-solves rooted directly below this point are also instantly viewable.\n    for (const key of Object.keys(subs)) {\n      const base = key.split(\" \");\n      if (base.length === path.length + 1 && isPathPrefix(path, base)) {\n        const seg = base[base.length - 1];\n        if (isDealSegment(seg)) set.add(dealCard(seg));\n      }\n    }\n    return set;\n  }, [segs, subs, path]);\n\n  const nextStreet = streetNameForBoardLen(fullBoard.length + 1);\n\n  // Open the drawer the moment an embedded walk lands on a chance node — the\n  // pick is the next decision, same gesture as the Explorer's flop drawer.\n  useEffect(() => {\n    if (embedded && isChance) setChancePickerOpen(true);\n  }, [embedded, isChance, pathKey]);\n\n  const pickCard = async (card: string) => {\n    if (solving) return;\n    const seg = `deal:${card}`;\n    const nextPath = [...path, seg];\n    if (availableCards.has(card)) {\n      setSolveError(null);\n      setPath(nextPath);\n      return;\n    }\n    // Solve the subgame rooted after this card, on demand. When the containing\n    // solution emitted CFR-D carry that is valid at this boundary, the child is\n    // a *safe* re-solve (gadget); otherwise it falls back to the reach-range\n    // bootstrap (#233, resolve-carry.ts).\n    let request: SolveRequest;\n    let resolveMode: SubSolve[\"resolveMode\"] = \"reach\";\n    try {\n      const carry = carryForChild(ctx.config, ctx.result, rel, card);\n      request = buildChildRequest(\n        ctx.config,\n        ctx.result,\n        rel,\n        card,\n        carry ? { resolve: carry.resolve } : undefined,\n      );\n      if (carry) resolveMode = \"gadget\";\n    } catch (e) {\n      setSolveError(e instanceof Error ? e.message : String(e));\n      return;\n    }\n    const seq = ++solveSeq.current;\n    setSolving({ card, street: nextStreet.toLowerCase() });\n    setProgress(null);\n    setSolveError(null);\n    const handle = startSolve(request, (p) => {\n      if (solveSeq.current === seq) setProgress(p);\n    });\n    handleRef.current = handle;\n    try {\n      const outcome = await handle.promise;\n      setSubs((s) => ({\n        ...s,\n        [keyOf(nextPath)]: { config: request, result: outcome.result, resolveMode },\n      }));\n      if (solveSeq.current === seq) setPath(nextPath);\n    } catch (e) {\n      if (solveSeq.current === seq) {\n        setSolveError(e instanceof Error ? e.message : String(e));\n      }\n    } finally {\n      if (solveSeq.current === seq) {\n        setSolving(null);\n        setProgress(null);\n      }\n      handleRef.current = null;\n    }\n  };\n\n  const cancelSolve = () => {\n    solveSeq.current++;\n    handleRef.current?.cancel().catch(() => {});\n    setSolving(null);\n    setProgress(null);\n  };\n\n  const jumpTo = (i: number) => {\n    if (solving) cancelSolve();\n    setSolveError(null);\n    setPath(path.slice(0, i));\n  };\n\n  // ---- breadcrumb model -------------------------------------------------------\n\n  const crumbs = useMemo<Crumb[]>(() => {\n    const out: Crumb[] = [\n      {\n        index: 0,\n        kind: \"street\",\n        text: streetNameForBoardLen(baseBoard.length),\n        cards: baseBoard,\n      },\n    ];\n    for (let i = 0; i < path.length; i++) {\n      const seg = path[i];\n      if (isDealSegment(seg)) {\n        out.push({\n          index: i + 1,\n          kind: \"street\",\n          text: streetNameForBoardLen(baseBoard.length + path.slice(0, i + 1).filter(isDealSegment).length),\n          card: dealCard(seg),\n        });\n        continue;\n      }\n      const c = containingSolution(bundle, subs, path.slice(0, i));\n      const n = nodeAtPath(c.result.nodes ?? [], path.slice(c.base.length, i));\n      const actor = n ? (n.player === 0 ? meta.oopLabel : meta.ipLabel) : \"?\";\n      const locked = Boolean(n?.locked) || keyOf(path.slice(0, i)) in locks;\n      out.push({ index: i + 1, kind: \"action\", text: seg, actor, locked });\n    }\n    return out;\n  }, [path, bundle, subs, baseBoard, meta, locks]);\n\n  const actingLabel = node ? (node.player === 0 ? meta.oopLabel : meta.ipLabel) : null;\n  const isSubgame = ctx.base.length > 0;\n\n  // ---------------------------------------------------------------------------\n\n  return (\n    <div className=\"flex flex-col gap-4\">\n      {/* Header: title + board + geometry. Dropped in embedded mode — the\n          Explorer's preflop strip already carries the spot context. */}\n      {embedded ? null : (\n        <div className=\"flex flex-wrap items-center justify-between gap-3\">\n          <div className=\"flex min-w-0 items-center gap-3\">\n            {onBack ? (\n              <button\n                type=\"button\"\n                onClick={onBack}\n                aria-label=\"Back to solutions\"\n                className=\"flex size-8 shrink-0 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n              >\n                <ArrowLeft className=\"size-4\" />\n              </button>\n            ) : null}\n            <div className=\"flex min-w-0 flex-col\">\n              <span className=\"truncate text-sm font-semibold text-foreground\">{bundle.title}</span>\n              <span className=\"text-xs text-muted-foreground\">\n                {meta.oopLabel} (OOP) vs {meta.ipLabel} (IP) · pot {meta.potBb.toFixed(1)}bb ·{\" \"}\n                {meta.effStackBb.toFixed(1)}bb behind · {meta.betSizing}\n              </span>\n            </div>\n          </div>\n          <div className=\"flex items-center gap-3\">\n            {drillHref ? (\n              <Link\n                href={drillHref}\n                className=\"flex shrink-0 items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n              >\n                <Dumbbell className=\"size-3.5\" />\n                Drill this spot\n              </Link>\n            ) : null}\n            <span className=\"text-[11px] text-muted-foreground tabular-nums\">\n            {/* Subgame re-solves are exact even inside an AI bundle, so their\n                exploitability is a real grade; the AI root solve has none. */}\n            {!isSubgame && bundle.config.aiSolve\n              ? \"AI solve · expl n/a\"\n              : `expl ${ctx.result.exploitability.percent.toFixed(2)}%${\n                  isSubgame\n                    ? ctx.resolveMode === \"gadget\"\n                      ? \" (safe re-solve · CFR-D)\"\n                      : \" (re-solved subgame · approx ranges)\"\n                    : \"\"\n                }`}\n            </span>\n          </div>\n        </div>\n      )}\n\n      {/* Embedded: a horizontal decision strip that extends the preflop action\n          bar (flop → postflop decisions), the action selector as navigator.\n          Standalone: the compact breadcrumb. */}\n      {embedded ? (\n        <DecisionStrip\n          prefix={stripPrefix}\n          lead={stripLead}\n          crumbs={crumbs}\n          actingLabel={actingLabel}\n          actingLocked={Boolean(node?.locked) || Boolean(pendingLock)}\n          pot={node ? node.pot : null}\n          actionItems={actionItems}\n          isChance={isChance}\n          nextStreet={nextStreet}\n          onChanceClick={() => setChancePickerOpen(true)}\n          onJump={jumpTo}\n          onPick={(seg) => {\n            setSolveError(null);\n            setPath([...path, seg]);\n          }}\n          editing={\n            canEditHere || canEditNodeHere\n              ? {\n                  pendingLock: Boolean(pendingLock),\n                  dumpLocked: Boolean(node?.locked),\n                  atCap: !pendingLock && lockCount >= MAX_LOCKED_NODES,\n                  canEditNode: canEditNodeHere,\n                  nodeEdited,\n                  canLock: canEditHere,\n                  onEditNode: () => setNodeEditorAt(pathKey),\n                  onEditFreqs: () => setEditingLock(true),\n                }\n              : undefined\n          }\n        />\n      ) : (\n      <div className=\"flex flex-wrap items-center gap-1.5 rounded-xl border border-border bg-card/40 px-3 py-2 text-xs\">\n        {crumbs.map((c, i) => {\n          const isCurrent = i === crumbs.length - 1;\n          return (\n            <span key={i} className=\"flex items-center gap-1.5\">\n              {i > 0 ? <span className=\"text-zinc-600\">›</span> : null}\n              <button\n                type=\"button\"\n                onClick={() => jumpTo(c.index)}\n                className={`flex items-center gap-1 rounded-md px-1.5 py-0.5 transition-colors ${\n                  isCurrent\n                    ? \"bg-accent text-foreground\"\n                    : \"text-muted-foreground hover:bg-accent/60 hover:text-foreground\"\n                }`}\n              >\n                {c.kind === \"street\" ? (\n                  <>\n                    <span className=\"text-[10px] uppercase tracking-wide text-zinc-500\">\n                      {c.text}\n                    </span>\n                    {c.cards?.map((card, j) => <CardText key={j} card={card} />)}\n                    {c.card ? <CardText card={c.card} /> : null}\n                  </>\n                ) : (\n                  <>\n                    <span className=\"font-medium text-zinc-500\">{c.actor}</span>\n                    <span>{c.text}</span>\n                    {c.locked ? <Lock className=\"size-3 text-amber-400\" /> : null}\n                  </>\n                )}\n              </button>\n            </span>\n          );\n        })}\n        {node && actingLabel ? (\n          <span className=\"ml-auto flex items-center gap-2 pl-2 text-[11px]\">\n            {node.locked || pendingLock ? (\n              <span className=\"flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 font-semibold text-amber-400\">\n                <Lock className=\"size-3\" /> Locked\n              </span>\n            ) : null}\n            <span className=\"rounded-full bg-foreground px-2 py-0.5 font-semibold text-background\">\n              {actingLabel} to act\n            </span>\n            <span className=\"text-muted-foreground tabular-nums\">\n              pot {node.pot.toFixed(1)}bb\n            </span>\n          </span>\n        ) : null}\n      </div>\n      )}\n\n      {solveError ? (\n        <div className=\"rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-2.5 text-sm text-destructive\">\n          {solveError}\n        </div>\n      ) : null}\n\n      {node && displayNode ? (\n        <>\n        {/* ---- locked-node re-solve bar (#268) ----\n            The \"Edit strategy\" entry point lives on the node card itself\n            (DecisionStrip's lock icon), so this bar stays out of the way until\n            at least one node is actually locked and there is a re-solve to fire. */}\n        {locking && canEditHere && lockCount > 0 ? (\n          <div className=\"flex flex-wrap items-center gap-2 rounded-xl border border-border bg-card/40 px-3 py-2\">\n            {node.locked ? (\n              <span className=\"flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] font-medium text-amber-400\">\n                <Lock className=\"size-3\" /> Locked in this solve\n              </span>\n            ) : null}\n            {pendingLock ? (\n              <span className=\"flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] font-medium text-amber-400\">\n                <Lock className=\"size-3\" /> Locked — pending re-solve\n              </span>\n            ) : null}\n            {pendingLock && !editingLock ? (\n              <button\n                type=\"button\"\n                onClick={removeLock}\n                className=\"rounded-md border border-border bg-card px-2.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n              >\n                Remove lock\n              </button>\n            ) : null}\n            <span className=\"ml-auto flex items-center gap-2\">\n              <span className=\"text-[11px] text-muted-foreground tabular-nums\">\n                {lockCount} node{lockCount === 1 ? \"\" : \"s\"} locked\n              </span>\n              <button\n                type=\"button\"\n                onClick={resolveWithLocks}\n                disabled={locking.busy}\n                className=\"flex items-center gap-1.5 rounded-md bg-foreground px-2.5 py-1 text-[11px] font-semibold text-background transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50\"\n              >\n                {locking.busy ? (\n                  <>\n                    <Loader2 className=\"size-3 animate-spin\" /> Re-solving…\n                  </>\n                ) : (\n                  <>\n                    <Lock className=\"size-3\" /> Re-solve with edits\n                  </>\n                )}\n              </button>\n            </span>\n          </div>\n        ) : locking && isSubgame ? (\n          <p className=\"text-[11px] text-muted-foreground/70\">\n            Strategy edits are available in the base solution only — this node is inside an\n            on-demand subgame re-solve.\n          </p>\n        ) : null}\n\n        {editingLock ? (\n          <LockEditor\n            key={pathKey}\n            actions={node.actions}\n            pot={node.pot}\n            initial={pendingLock ? pendingLock.freqs : actionItems.map((it) => it.freq)}\n            hasLock={Boolean(pendingLock)}\n            onApply={applyLock}\n            onRemove={removeLock}\n            onCancel={() => setEditingLock(false)}\n          />\n        ) : null}\n\n        {nodeEditing && nodeEditOpen && canEditNodeHere ? (\n          <NodeEditModal\n            key={`ne-${pathKey}`}\n            actorLabel={actingLabel ?? \"\"}\n            pot={node.pot}\n            actions={node.actions}\n            hasEdits={nodeEditing.editedKeys.length > 0}\n            busy={nodeEditing.busy}\n            onConfirm={(sizes, allin) => {\n              setNodeEditorAt(null);\n              nodeEditing.onApply(toEditPath(path), sizes, allin);\n            }}\n            onClearAll={() => {\n              setNodeEditorAt(null);\n              nodeEditing.onClearAll();\n            }}\n            onClose={() => setNodeEditorAt(null)}\n          />\n        ) : null}\n\n        {embedded ? (\n        <div className=\"grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,320px)]\">\n          <StrategyGrid\n            actions={displayNode.actions}\n            hands={displayNode.hands}\n            reach={actorReach}\n          />\n          <PostflopHandSummary\n            actions={displayNode.actions}\n            hands={displayNode.hands}\n            reach={actorReach}\n            evByCombo={evByCombo}\n          />\n        </div>\n        ) : (\n        <div className=\"grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,340px)]\">\n          <StrategyGrid\n            actions={displayNode.actions}\n            hands={displayNode.hands}\n            reach={actorReach}\n          />\n          <div className=\"flex flex-col gap-5\">\n            {/* Action summary — one wide bar per action; click to advance */}\n            <div className=\"flex flex-col gap-2\">\n              <span className=\"text-[10px] uppercase tracking-wide text-muted-foreground\">\n                Actions\n              </span>\n              <div className=\"flex flex-col gap-1.5\">\n                {actionItems.map((it) => (\n                  <button\n                    key={it.seg}\n                    type=\"button\"\n                    onClick={() => {\n                      setSolveError(null);\n                      setPath([...path, it.seg]);\n                    }}\n                    className=\"group flex flex-col gap-1.5 rounded-lg border border-border bg-card/40 px-3 py-2 text-left transition-colors hover:border-foreground/30 hover:bg-accent/40\"\n                  >\n                    <div className=\"flex items-center justify-between gap-2\">\n                      <span className=\"flex items-center gap-2 text-sm font-medium text-foreground\">\n                        <span\n                          className=\"size-3 shrink-0 rounded-[3px]\"\n                          style={{ backgroundColor: it.color }}\n                        />\n                        {it.label}\n                        {it.add > 0 ? (\n                          <span className=\"text-xs text-muted-foreground tabular-nums\">\n                            {Math.round(it.add * 10) / 10}bb\n                            {node.pot > 0 && (it.label === \"Bet\" || it.label === \"Raise\")\n                              ? ` · ${Math.round((it.add / node.pot) * 100)}% pot`\n                              : \"\"}\n                          </span>\n                        ) : null}\n                      </span>\n                      <span className=\"flex flex-col items-end leading-tight\">\n                        <span className=\"text-sm font-semibold text-foreground tabular-nums\">\n                          {(it.freq * 100).toFixed(1)}%\n                        </span>\n                        <span className=\"text-[10px] text-muted-foreground tabular-nums\">\n                          {it.combos.toFixed(1)} combos\n                        </span>\n                      </span>\n                    </div>\n                    <div className=\"h-1.5 w-full overflow-hidden rounded-full bg-white/[0.06]\">\n                      <div\n                        className=\"h-full rounded-full\"\n                        style={{\n                          width: `${Math.max(it.freq * 100, it.freq > 0 ? 1 : 0)}%`,\n                          backgroundColor: it.color,\n                        }}\n                      />\n                    </div>\n                  </button>\n                ))}\n              </div>\n            </div>\n            <PostflopHandSummary\n              actions={displayNode.actions}\n              hands={displayNode.hands}\n              reach={actorReach}\n              evByCombo={evByCombo}\n            />\n          </div>\n        </div>\n        )}\n        </>\n      ) : isChance ? (\n        // Embedded: the picker lives in a bottom drawer (the strip's dashed\n        // card reopens it); a solve in flight keeps its progress visible even\n        // with the drawer dismissed. Standalone keeps the inline picker.\n        embedded ? (\n          <>\n            {chancePickerOpen ? (\n              <BottomSheet\n                title={`Pick the ${nextStreet.toLowerCase()} card`}\n                onClose={() => setChancePickerOpen(false)}\n              >\n                <ChanceCardPicker\n                  inSheet\n                  street={nextStreet}\n                  dead={fullBoard}\n                  available={availableCards}\n                  solving={solving}\n                  progress={progress}\n                  onPick={pickCard}\n                  onCancel={cancelSolve}\n                />\n              </BottomSheet>\n            ) : null}\n            {solving && !chancePickerOpen ? (\n              <div className=\"flex items-center gap-3 rounded-lg border border-border bg-card/40 px-4 py-2.5 text-sm text-muted-foreground\">\n                <Loader2 className=\"size-4 shrink-0 animate-spin\" />\n                <span className=\"tabular-nums\">\n                  Solving {solving.street} <CardText card={solving.card} className=\"h-5 w-4 align-middle text-[13px]\" />…{\" \"}\n                  {progress\n                    ? `iter ${progress.iter} · expl ${progress.percent.toFixed(2)}%`\n                    : \"starting\"}\n                </span>\n                <button\n                  type=\"button\"\n                  onClick={cancelSolve}\n                  aria-label=\"Cancel solve\"\n                  className=\"ml-auto rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                >\n                  <X className=\"size-4\" />\n                </button>\n              </div>\n            ) : null}\n          </>\n        ) : (\n          <ChanceCardPicker\n            street={nextStreet}\n            dead={fullBoard}\n            available={availableCards}\n            solving={solving}\n            progress={progress}\n            onPick={pickCard}\n            onCancel={cancelSolve}\n          />\n        )\n      ) : (\n        <TerminalCard path={path} board={fullBoard} reach={reach} />\n      )}\n    </div>\n  );\n}\n\n// ---------------------------------------------------------------------------\n// Decision strip — the horizontal action-bar navigator (embedded mode)\n// ---------------------------------------------------------------------------\n\n/** Edit controls on the acting card — pencil opens the structural Edit Node\n *  modal (#390), lock opens the frequency lock editor (#268). */\ninterface StripEditing {\n  pendingLock: boolean;\n  /** Locked in the solve's own dump — can't be removed from here. */\n  dumpLocked: boolean;\n  /** MAX_LOCKED_NODES reached and this node isn't one of them. */\n  atCap: boolean;\n  /** Structural node edits are available here (pencil shown). */\n  canEditNode: boolean;\n  /** This node has an active node edit (pencil highlighted). */\n  nodeEdited: boolean;\n  /** Frequency locking is available here (lock shown). */\n  canLock: boolean;\n  onEditNode: () => void;\n  onEditFreqs: () => void;\n}\n\n/** Extends the Explorer's preflop seat strip into postflop: a flop card, one\n *  card per taken action (click to rewind), and an active card whose action\n *  rows advance the line — GTO-Wizard's continuous navigator. */\nfunction DecisionStrip({\n  prefix,\n  lead,\n  crumbs,\n  actingLabel,\n  actingLocked = false,\n  pot,\n  actionItems,\n  isChance,\n  nextStreet,\n  onChanceClick,\n  onJump,\n  onPick,\n  editing,\n}: {\n  prefix?: ReactNode;\n  lead?: ReactNode;\n  crumbs: Crumb[];\n  actingLabel: string | null;\n  /** The acting node is locked (#268) — dump flag or pending edit. */\n  actingLocked?: boolean;\n  pot: number | null;\n  actionItems: StripActionItem[];\n  isChance: boolean;\n  nextStreet: string;\n  /** Reopens the chance-card drawer (the dashed card is the affordance). */\n  onChanceClick?: () => void;\n  onJump: (index: number) => void;\n  onPick: (seg: string) => void;\n  /** Present when the acting node is editable (base solution + locking on). */\n  editing?: StripEditing;\n}) {\n  const CARD = \"flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border p-2\";\n  const scrollerRef = useRef<HTMLDivElement>(null);\n\n  // Keep the newest (acting) card in view: the strip grows rightward as the\n  // line advances, and on macOS the overlay scrollbar gives no affordance that\n  // there's more to the right.\n  useEffect(() => {\n    // Instant, not smooth — smooth scrollTo is dropped entirely in some\n    // embedded-Chromium contexts. No rAF: it never fires in hidden tabs.\n    const el = scrollerRef.current;\n    if (el) el.scrollLeft = el.scrollWidth;\n  }, [crumbs.length, actingLabel, isChance]);\n\n  // Plain mouse wheels only scroll vertically — translate that into horizontal\n  // scroll while hovering the strip. Native listener: React's onWheel is\n  // passive, so it can't preventDefault the page scroll.\n  useEffect(() => {\n    const el = scrollerRef.current;\n    if (!el) return;\n    const onWheel = (e: WheelEvent) => {\n      if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return; // trackpad h-swipe works natively\n      if (el.scrollWidth <= el.clientWidth) return;\n      el.scrollLeft += e.deltaY;\n      e.preventDefault();\n    };\n    el.addEventListener(\"wheel\", onWheel, { passive: false });\n    return () => el.removeEventListener(\"wheel\", onWheel);\n  }, []);\n\n  return (\n    <RailRow lead={lead} scrollerRef={scrollerRef}>\n      {prefix}\n      {crumbs.map((c, i) =>\n        c.kind === \"street\" ? (\n          <button\n            key={i}\n            type=\"button\"\n            onClick={() => onJump(c.index)}\n            className={`${CARD} border-border bg-card/40 text-left transition-colors hover:border-foreground/30`}\n          >\n            <span className=\"text-[10px] uppercase tracking-wide text-zinc-500\">{c.text}</span>\n            <div className=\"mt-auto flex flex-wrap items-center gap-1 text-lg font-bold tabular-nums\">\n              {c.cards?.map((card, j) => <CardText key={j} card={card} className=\"h-8 w-6 text-xl\" />)}\n              {c.card ? <CardText card={c.card} className=\"h-8 w-6 text-xl\" /> : null}\n            </div>\n          </button>\n        ) : (\n          <button\n            key={i}\n            type=\"button\"\n            onClick={() => onJump(c.index)}\n            className={`${CARD} border-border bg-card/40 text-left transition-colors hover:border-foreground/30`}\n          >\n            <span className=\"flex items-center gap-1 text-xs font-semibold text-muted-foreground\">\n              {c.actor}\n              {c.locked ? <Lock className=\"size-3 text-amber-400\" /> : null}\n            </span>\n            <span className=\"mt-auto inline-block max-w-full truncate rounded bg-accent px-2 py-0.5 text-xs font-semibold text-foreground\">\n              {c.text}\n            </span>\n          </button>\n        ),\n      )}\n\n      {actingLabel ? (\n        <div\n          className={`flex min-h-[104px] shrink-0 flex-row rounded-xl border ${\n            editing ? \"w-[184px]\" : \"w-[156px]\"\n          } border-foreground/50 bg-accent/50`}\n        >\n          <div className=\"flex min-w-0 flex-1 flex-col gap-1 p-2\">\n            <div className=\"flex items-center justify-between\">\n              <span className=\"flex items-center gap-1 text-xs font-semibold text-foreground\">\n                {actingLabel}\n                {actingLocked ? <Lock className=\"size-3 text-amber-400\" /> : null}\n              </span>\n              {pot != null ? (\n                <span className=\"text-[10px] text-muted-foreground tabular-nums\">\n                  pot {pot.toFixed(1)}\n                </span>\n              ) : null}\n            </div>\n            <div className=\"flex flex-col\">\n              {actionItems.map((it) => (\n                <button\n                  key={it.seg}\n                  type=\"button\"\n                  onClick={() => onPick(it.seg)}\n                  className=\"flex items-center justify-between gap-1 rounded px-1 py-0.5 text-left transition-colors hover:bg-accent\"\n                >\n                  <span className=\"flex min-w-0 items-center gap-1 truncate text-xs text-foreground\">\n                    <span\n                      className=\"size-2 shrink-0 rounded-[2px]\"\n                      style={{ backgroundColor: it.color }}\n                    />\n                    {it.label}\n                  </span>\n                  <span className=\"shrink-0 text-[11px] font-semibold text-foreground tabular-nums\">\n                    {(it.freq * 100).toFixed(0)}%\n                  </span>\n                </button>\n              ))}\n            </div>\n          </div>\n          {editing ? (\n            <div className=\"flex flex-col items-center gap-1 border-l border-foreground/20 p-1.5\">\n              {editing.canEditNode ? (\n                <button\n                  type=\"button\"\n                  onClick={editing.onEditNode}\n                  title={editing.nodeEdited ? \"Edit node (edited)\" : \"Edit node — bet sizes\"}\n                  aria-label=\"Edit node\"\n                  className={`rounded-md p-1 transition-colors ${\n                    editing.nodeEdited\n                      ? \"text-amber-400 hover:bg-amber-500/15\"\n                      : \"text-muted-foreground hover:bg-accent hover:text-foreground\"\n                  }`}\n                >\n                  <Pencil className=\"size-3.5\" />\n                </button>\n              ) : null}\n              {editing.canLock ? (\n                <button\n                  type=\"button\"\n                  onClick={editing.onEditFreqs}\n                  disabled={editing.atCap}\n                  title={\n                    editing.atCap\n                      ? `At most ${MAX_LOCKED_NODES} nodes can be locked per re-solve`\n                      : \"Lock strategy — edit frequencies\"\n                  }\n                  aria-label=\"Lock strategy\"\n                  className={`rounded-md p-1 transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${\n                    editing.pendingLock || editing.dumpLocked\n                      ? \"text-amber-400 hover:bg-amber-500/15\"\n                      : \"text-muted-foreground hover:bg-accent hover:text-foreground\"\n                  }`}\n                >\n                  <Lock className=\"size-3.5\" />\n                </button>\n              ) : null}\n            </div>\n          ) : null}\n        </div>\n      ) : isChance ? (\n        <button\n          type=\"button\"\n          onClick={onChanceClick}\n          disabled={!onChanceClick}\n          className={`${CARD} items-center justify-center border-dashed border-foreground/40 bg-accent/30 text-center`}\n        >\n          <span className=\"text-[10px] uppercase tracking-wide text-zinc-500\">{nextStreet}</span>\n          <span className=\"text-xs text-muted-foreground\">pick a card ↓</span>\n        </button>\n      ) : null}\n    </RailRow>\n  );\n}\n\n// ---------------------------------------------------------------------------\n// Chance node: pick the next card\n// ---------------------------------------------------------------------------\n\nconst RANKS = [\"A\", \"K\", \"Q\", \"J\", \"T\", \"9\", \"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\"];\nconst SUITS = [\"s\", \"h\", \"d\", \"c\"] as const;\n\nfunction ChanceCardPicker({\n  street,\n  dead,\n  available,\n  solving,\n  progress,\n  onPick,\n  onCancel,\n  inSheet = false,\n}: {\n  street: string;\n  dead: string[];\n  available: Set<string>;\n  solving: { card: string; street: string } | null;\n  progress: SolverProgress | null;\n  onPick: (card: string) => void;\n  onCancel: () => void;\n  /** Rendered inside a BottomSheet: the sheet header already carries the title,\n   *  and the sheet provides the frame — keep just the hint + grid. */\n  inSheet?: boolean;\n}) {\n  const deadSet = new Set(dead);\n  const anyOnDemand = RANKS.some((r) =>\n    SUITS.some((s) => !deadSet.has(`${r}${s}`) && !available.has(`${r}${s}`)),\n  );\n\n  return (\n    <div\n      className={\n        inSheet\n          ? \"flex flex-col items-center gap-4 pb-2\"\n          : \"flex flex-col items-center gap-4 rounded-xl border border-border bg-card/40 px-4 py-6\"\n      }\n    >\n      <div className=\"flex flex-col items-center gap-1 text-center\">\n        {inSheet ? null : (\n          <span className=\"text-sm font-medium text-foreground\">\n            Pick the {street.toLowerCase()} card\n          </span>\n        )}\n        <span className=\"text-xs text-muted-foreground\">\n          {anyOnDemand\n            ? \"Dimmed cards aren't in this bundle — picking one solves that runout on demand (~5–15s).\"\n            : \"Every runout is in this bundle — pick any card.\"}\n        </span>\n      </div>\n\n      <div className=\"flex w-full max-w-[520px] flex-col gap-1\">\n        {SUITS.map((suit) => (\n          <div key={suit} className=\"grid grid-cols-[repeat(13,minmax(0,1fr))] gap-1\">\n            {RANKS.map((rank) => {\n              const card = `${rank}${suit}`;\n              const isDead = deadSet.has(card);\n              const instant = available.has(card);\n              const isSolvingThis = solving?.card === card;\n              return (\n                <button\n                  key={card}\n                  type=\"button\"\n                  disabled={isDead || !!solving}\n                  onClick={() => onPick(card)}\n                  style={{\n                    backgroundColor: suitTile(suit).bg,\n                    opacity: isDead ? 0.15 : isSolvingThis ? 1 : solving ? 0.35 : instant ? 1 : 0.55,\n                  }}\n                  className={`relative flex h-8 items-center justify-center rounded border border-white/25 text-sm font-bold text-white transition ${\n                    isDead || solving ? \"cursor-not-allowed\" : \"hover:brightness-110\"\n                  } ${isSolvingThis ? \"ring-2 ring-white/80\" : \"\"}`}\n                  title={\n                    isDead\n                      ? `${card} is dead`\n                      : instant\n                        ? `${rank}${SUIT_GLYPH[suit]}`\n                        : `${rank}${SUIT_GLYPH[suit]} — solved on demand`\n                  }\n                >\n                  {isSolvingThis ? <Loader2 className=\"size-4 animate-spin\" /> : rank}\n                </button>\n              );\n            })}\n          </div>\n        ))}\n      </div>\n\n      {solving ? (\n        <div className=\"flex items-center gap-3 rounded-lg border border-border bg-card/60 px-4 py-2.5 text-sm text-muted-foreground\">\n          <Loader2 className=\"size-4 animate-spin\" />\n          <span className=\"tabular-nums\">\n            Solving {solving.street} <CardText card={solving.card} className=\"h-5 w-4 align-middle text-[13px]\" />…{\" \"}\n            {progress\n              ? `iter ${progress.iter} · expl ${progress.percent.toFixed(2)}%`\n              : \"starting\"}\n          </span>\n          <button\n            type=\"button\"\n            onClick={onCancel}\n            aria-label=\"Cancel solve\"\n            className=\"rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n          >\n            <X className=\"size-4\" />\n          </button>\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\n// ---------------------------------------------------------------------------\n// Terminal states\n// ---------------------------------------------------------------------------\n\nfunction TerminalCard({\n  path,\n  board,\n  reach,\n}: {\n  path: string[];\n  board: string[];\n  reach: ReachState | null;\n}) {\n  const last = path[path.length - 1] ?? \"\";\n  let text: string;\n  if (last === \"Fold\") {\n    text = \"The hand ends here — the last player folded.\";\n  } else if (board.length >= 5) {\n    text = \"Showdown — the river action is complete.\";\n  } else if (reach && reach.effStack <= 0.01) {\n    text = \"Both players are all-in — the remaining runout has no more decisions.\";\n  } else {\n    text = \"End of this line.\";\n  }\n  return (\n    <div className=\"rounded-xl border border-dashed border-border bg-card/40 px-6 py-8 text-center text-sm text-muted-foreground\">\n      {text}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/solution-viewer.tsx"
    },
    {
      "path": "src/components/explorer/tree-flow.tsx",
      "content": "\"use client\";\n\n// React Flow game-tree visualization with EDITABLE nodes (reactflow.dev\n// editable-nodes pattern). Every action node is a card: its bet/raise sizes\n// are editable inline, and committing an edit lowers to the same engine\n// `NodeEdit` records the Tree-edit strip uses — so pruning here changes the\n// tree the solver ACTUALLY builds, not just the picture.\n//\n// After a solve (dump_nodes), edges carry the aggregate strategy frequency of\n// their action: thick/bright = used, thin/dashed = ~never used → prime\n// pruning candidates. Deal segments are normalized (\"deal:Td\" → \"deal\") and\n// averaged, so a turn edge shows the mean frequency across every turn card.\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport {\n  Background,\n  Controls,\n  Handle,\n  MiniMap,\n  Position,\n  ReactFlow,\n  type Edge,\n  type Node,\n  type NodeProps,\n} from \"@xyflow/react\";\nimport \"@xyflow/react/dist/style.css\";\nimport { ChevronDown, ChevronRight, RotateCcw } from \"lucide-react\";\nimport { ACTION_COLORS } from \"@/components/solver/strategy-grid\";\nimport type { SolverResult } from \"@/lib/solver/types\";\nimport { buildFullTree, type FullTree, type FullTreeNode } from \"@/lib/explorer/tree-sim\";\nimport {\n  pathLabel,\n  type AllinChoice,\n  type NodeEdit,\n  type SizingBase,\n  type SizingGrid,\n} from \"./tree-sizing-editor\";\n\n// ---------------------------------------------------------------------------\n// Frequency index — path key (deals normalized) → token → mean frequency.\n// ---------------------------------------------------------------------------\n\nconst normalizeSeg = (s: string) => (s.startsWith(\"deal\") ? \"deal\" : s);\nconst freqKey = (path: string[]) => path.map(normalizeSeg).join(\"|\");\n\ntype FreqIndex = Map<string, Map<string, { sum: number; n: number }>>;\n\nfunction buildFreqIndex(result: SolverResult | null | undefined): FreqIndex | null {\n  if (!result) return null;\n  const idx: FreqIndex = new Map();\n  const feed = (path: string[], node: { actions: { label: string; add: number }[]; hands: { freqs: number[] }[] }) => {\n    if (node.hands.length === 0) return;\n    const key = freqKey(path);\n    let byToken = idx.get(key);\n    if (!byToken) idx.set(key, (byToken = new Map()));\n    node.actions.forEach((a, i) => {\n      let mean = 0;\n      for (const h of node.hands) mean += h.freqs[i] ?? 0;\n      mean /= node.hands.length;\n      const token = pathLabel(a.label, a.add);\n      const acc = byToken.get(token) ?? { sum: 0, n: 0 };\n      acc.sum += mean;\n      acc.n += 1;\n      byToken.set(token, acc);\n    });\n  };\n  feed([], result.root);\n  for (const n of result.nodes ?? []) feed(n.path, n);\n  return idx.size > 0 ? idx : null;\n}\n\nconst lookupFreq = (idx: FreqIndex | null, path: string[], token: string): number | null => {\n  const acc = idx?.get(freqKey(path))?.get(token);\n  return acc && acc.n > 0 ? acc.sum / acc.n : null;\n};\n\n// ---------------------------------------------------------------------------\n// Layout — tidy left-to-right tree over the VISIBLE nodes only.\n// ---------------------------------------------------------------------------\n\nconst NODE_W = 250;\nconst COL_GAP = 90;\nconst ROW_GAP = 18;\n\nconst nodeHeight = (n: FullTreeNode): number =>\n  n.kind === \"action\" ? 92 + n.actions.length * 19 : 40;\n\n// ---------------------------------------------------------------------------\n// Custom node components\n// ---------------------------------------------------------------------------\n\ninterface ActionNodeData {\n  tree: FullTreeNode;\n  freqs: (number | null)[];\n  collapsed: boolean;\n  onToggleCollapse: (id: string) => void;\n  onCommitSizes: (path: string[], sizes: string) => void;\n  onToggleAllin: (path: string[]) => void;\n  onResetEdit: (path: string[]) => void;\n  [key: string]: unknown;\n}\n\nconst fmtFrac = (f: number) => (Math.round(f * 100) / 100).toString();\n\nfunction ActionNode({ data }: NodeProps<Node<ActionNodeData>>) {\n  const { tree, freqs, collapsed } = data;\n  const fracs = tree.actions.filter((a) => a.frac !== undefined).map((a) => fmtFrac(a.frac!));\n  const allinOn = tree.actions.some((a) => a.label === \"AllIn\");\n  // Local draft so typing doesn't rebuild the tree on every keystroke.\n  const [draft, setDraft] = useState<string | null>(null);\n  const shownSizes = draft ?? (tree.edit && tree.edit.sizes !== \"\" ? tree.edit.sizes : fracs.join(\", \"));\n\n  const commit = () => {\n    if (draft === null) return;\n    data.onCommitSizes(tree.path, draft);\n    setDraft(null);\n  };\n\n  return (\n    <div\n      className={`rounded-lg border bg-card text-left shadow-sm ${\n        tree.edit ? \"border-amber-500/60\" : \"border-border\"\n      }`}\n      style={{ width: NODE_W }}\n    >\n      <Handle type=\"target\" position={Position.Left} className=\"!bg-border\" />\n      <Handle type=\"source\" position={Position.Right} className=\"!bg-border\" />\n\n      <div className=\"flex items-center gap-1.5 border-b border-border/60 px-2 py-1.5\">\n        <button\n          className=\"nodrag rounded p-0.5 hover:bg-accent\"\n          onClick={() => data.onToggleCollapse(tree.id)}\n          title={collapsed ? \"Expand subtree\" : \"Collapse subtree\"}\n        >\n          {collapsed ? <ChevronRight size={12} /> : <ChevronDown size={12} />}\n        </button>\n        <span\n          className={`rounded px-1 text-[10px] font-bold uppercase ${\n            tree.role === \"oop\" ? \"bg-sky-500/20 text-sky-400\" : \"bg-amber-500/20 text-amber-400\"\n          }`}\n        >\n          {tree.role}\n        </span>\n        <span className=\"text-[10px] uppercase tracking-wide text-muted-foreground\">{tree.street}</span>\n        <span className=\"ml-auto text-[10px] tabular-nums text-muted-foreground\">\n          pot {Math.round(tree.pot * 10) / 10}\n          {tree.toCall > 1e-9 ? ` · call ${Math.round(tree.toCall * 10) / 10}` : \"\"}\n        </span>\n        {tree.edit ? (\n          <button\n            className=\"nodrag rounded p-0.5 text-amber-400 hover:bg-accent\"\n            onClick={() => data.onResetEdit(tree.path)}\n            title=\"Reset node edit\"\n          >\n            <RotateCcw size={11} />\n          </button>\n        ) : null}\n      </div>\n\n      <div className=\"flex flex-col px-2 py-1\">\n        {tree.actions.map((a, i) => {\n          const f = freqs[i];\n          return (\n            <div key={a.token} className=\"flex items-center gap-1.5 py-px text-[11px] leading-[18px]\">\n              <span\n                className=\"inline-block size-2 shrink-0 rounded-full\"\n                style={{ backgroundColor: ACTION_COLORS[a.label] ?? \"#888\" }}\n              />\n              <span className=\"truncate text-foreground\">{a.token}</span>\n              {a.frac !== undefined ? (\n                <span className=\"text-muted-foreground/60\">{Math.round(a.frac * 100)}%pot</span>\n              ) : null}\n              {f !== null ? (\n                <span\n                  className={`ml-auto tabular-nums ${\n                    f < 0.005 ? \"text-rose-400/80\" : \"text-muted-foreground\"\n                  }`}\n                >\n                  {(f * 100).toFixed(f < 0.1 ? 1 : 0)}%\n                </span>\n              ) : null}\n            </div>\n          );\n        })}\n      </div>\n\n      <div className=\"flex items-center gap-1.5 border-t border-border/60 px-2 py-1.5\">\n        <input\n          className=\"nodrag h-6 w-0 flex-1 rounded border border-input bg-background px-1.5 text-[11px] text-foreground outline-none focus-visible:border-ring\"\n          value={shownSizes}\n          placeholder='sizes, e.g. \"0.33, 0.75\" or \"none\"'\n          onChange={(e) => setDraft(e.target.value)}\n          onBlur={commit}\n          onKeyDown={(e) => {\n            if (e.key === \"Enter\") (e.target as HTMLInputElement).blur();\n          }}\n          spellCheck={false}\n          title=\"Bet/raise sizes at this node (pot fractions). 'none' = no bets here.\"\n        />\n        <button\n          className={`nodrag rounded border px-1.5 py-0.5 text-[10px] ${\n            allinOn\n              ? \"border-rose-500/50 bg-rose-500/15 text-rose-300\"\n              : \"border-border text-muted-foreground\"\n          }`}\n          onClick={() => data.onToggleAllin(tree.path)}\n          title=\"Toggle all-in at this node\"\n        >\n          AI\n        </button>\n      </div>\n    </div>\n  );\n}\n\ninterface LeafNodeData {\n  tree: FullTreeNode;\n  collapsed?: boolean;\n  onToggleCollapse?: (id: string) => void;\n  [key: string]: unknown;\n}\n\nfunction ChanceNode({ data }: NodeProps<Node<LeafNodeData>>) {\n  const { tree, collapsed } = data;\n  return (\n    <div\n      className=\"flex items-center gap-1 rounded-full border border-emerald-500/40 bg-emerald-500/10 px-2.5 py-1.5 text-[11px] text-emerald-300\"\n      style={{ minWidth: 90 }}\n    >\n      <Handle type=\"target\" position={Position.Left} className=\"!bg-border\" />\n      <Handle type=\"source\" position={Position.Right} className=\"!bg-border\" />\n      <button\n        className=\"nodrag rounded p-0.5 hover:bg-emerald-500/20\"\n        onClick={() => data.onToggleCollapse?.(tree.id)}\n        title={collapsed ? \"Expand runout\" : \"Collapse runout\"}\n      >\n        {collapsed ? <ChevronRight size={11} /> : <ChevronDown size={11} />}\n      </button>\n      deal {tree.street}\n    </div>\n  );\n}\n\nconst TERMINAL_STYLE: Record<string, string> = {\n  fold: \"border-zinc-600/50 bg-zinc-700/20 text-zinc-400\",\n  showdown: \"border-violet-500/40 bg-violet-500/10 text-violet-300\",\n  runout: \"border-rose-500/40 bg-rose-500/10 text-rose-300\",\n};\nconst TERMINAL_LABEL: Record<string, string> = {\n  fold: \"Fold ends\",\n  showdown: \"Showdown\",\n  runout: \"All-in runout\",\n};\n\nfunction TerminalNode({ data }: NodeProps<Node<LeafNodeData>>) {\n  const { tree } = data;\n  return (\n    <div\n      className={`rounded-full border px-2.5 py-1.5 text-[11px] ${TERMINAL_STYLE[tree.terminal ?? \"fold\"]}`}\n    >\n      <Handle type=\"target\" position={Position.Left} className=\"!bg-border\" />\n      {TERMINAL_LABEL[tree.terminal ?? \"fold\"]} · {Math.round(tree.pot * 10) / 10}bb\n    </div>\n  );\n}\n\nconst nodeTypes = { action: ActionNode, chance: ChanceNode, terminal: TerminalNode };\n\n// ---------------------------------------------------------------------------\n// The flow\n// ---------------------------------------------------------------------------\n\nexport interface TreeFlowProps {\n  grid: SizingGrid;\n  base: SizingBase;\n  boardCards: number;\n  nodeEdits: NodeEdit[];\n  onNodeEditsChange: (edits: NodeEdit[]) => void;\n  /** Solve result (dump_nodes) — enables the frequency overlay. */\n  result?: SolverResult | null;\n  /** Node budget for the expansion. */\n  maxNodes?: number;\n  /** Called with tree stats whenever the tree rebuilds. */\n  onStats?: (t: FullTree) => void;\n}\n\nconst samePath = (a: string[], b: string[]) =>\n  a.length === b.length && a.every((t, i) => t === b[i]);\n\nexport function TreeFlow({\n  grid,\n  base,\n  boardCards,\n  nodeEdits,\n  onNodeEditsChange,\n  result,\n  maxNodes = 4000,\n  onStats,\n}: TreeFlowProps) {\n  // Collapse overrides: chance nodes default collapsed (the flop tree reads\n  // clean; expand a deal to open its runout), everything else expanded.\n  const [collapseOverride, setCollapseOverride] = useState<Map<string, boolean>>(new Map());\n  const isCollapsed = useCallback(\n    (n: FullTreeNode) => collapseOverride.get(n.id) ?? n.kind === \"chance\",\n    [collapseOverride],\n  );\n\n  const tree = useMemo(\n    () => buildFullTree(grid, nodeEdits, base, boardCards, maxNodes),\n    [grid, nodeEdits, base, boardCards, maxNodes],\n  );\n\n  useEffect(() => {\n    onStats?.(tree);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [tree]);\n\n  const freqIdx = useMemo(() => buildFreqIndex(result), [result]);\n\n  // ---- edit lowering ------------------------------------------------------\n\n  const upsertEdit = useCallback(\n    (path: string[], patch: Partial<Pick<NodeEdit, \"sizes\" | \"allin\">>) => {\n      const existing = nodeEdits.find((e) => samePath(e.path, path));\n      const next: NodeEdit = {\n        path: [...path],\n        sizes: patch.sizes ?? existing?.sizes ?? \"\",\n        allin: patch.allin ?? existing?.allin ?? \"auto\",\n      };\n      if (next.sizes.trim() === \"\" && next.allin === \"auto\") {\n        onNodeEditsChange(nodeEdits.filter((e) => !samePath(e.path, path)));\n      } else {\n        onNodeEditsChange([...nodeEdits.filter((e) => !samePath(e.path, path)), next]);\n      }\n    },\n    [nodeEdits, onNodeEditsChange],\n  );\n\n  const onCommitSizes = useCallback(\n    (path: string[], sizes: string) => upsertEdit(path, { sizes: sizes.trim() }),\n    [upsertEdit],\n  );\n  const onToggleAllin = useCallback(\n    (path: string[]) => {\n      // Flip against what the tree currently shows at that node.\n      const node = findByPath(tree.root, path);\n      const on = node?.actions.some((a) => a.label === \"AllIn\") ?? false;\n      const choice: AllinChoice = on ? \"off\" : \"on\";\n      upsertEdit(path, { allin: choice });\n    },\n    [tree, upsertEdit],\n  );\n  const onResetEdit = useCallback(\n    (path: string[]) => onNodeEditsChange(nodeEdits.filter((e) => !samePath(e.path, path))),\n    [nodeEdits, onNodeEditsChange],\n  );\n\n  // ---- layout -------------------------------------------------------------\n\n  const { nodes, edges } = useMemo(() => {\n    const nodes: Node[] = [];\n    const edges: Edge[] = [];\n    if (!tree.root) return { nodes, edges };\n\n    // Height of a subtree as laid out (collapsed nodes contribute just their\n    // own card height).\n    const subtreeHeight = (c: FullTreeNode): number => {\n      const cs = isCollapsed(c) ? [] : c.children;\n      if (cs.length === 0) return nodeHeight(c);\n      let total = 0;\n      for (const k of cs) total += subtreeHeight(k.child) + ROW_GAP;\n      return Math.max(nodeHeight(c), total - ROW_GAP);\n    };\n\n    const place = (n: FullTreeNode, depth: number, yTop: number): number => {\n      const h = nodeHeight(n);\n      const collapsed = isCollapsed(n);\n      const kids = collapsed ? [] : n.children;\n\n      let childrenH = 0;\n      const childTops: number[] = [];\n      for (const k of kids) {\n        childTops.push(yTop + childrenH);\n        childrenH += subtreeHeight(k.child) + ROW_GAP;\n      }\n      if (kids.length > 0) childrenH -= ROW_GAP;\n\n      const myH = Math.max(h, childrenH);\n      const y = yTop + myH / 2 - h / 2;\n\n      const data =\n        n.kind === \"action\"\n          ? ({\n              tree: n,\n              freqs: n.actions.map((a) => lookupFreq(freqIdx, n.path, a.token)),\n              collapsed,\n              onToggleCollapse: toggle,\n              onCommitSizes,\n              onToggleAllin,\n              onResetEdit,\n            } satisfies ActionNodeData)\n          : ({ tree: n, collapsed, onToggleCollapse: toggle } satisfies LeafNodeData);\n\n      nodes.push({\n        id: n.id,\n        type: n.kind,\n        position: { x: depth * (NODE_W + COL_GAP), y },\n        data,\n        draggable: false,\n        connectable: false,\n      });\n\n      kids.forEach((k, i) => {\n        place(k.child, depth + 1, childTops[i]);\n        const f = n.kind === \"action\" ? lookupFreq(freqIdx, n.path, k.token) : null;\n        const w = f === null ? 1.5 : 1 + 5 * f;\n        const dead = f !== null && f < 0.005;\n        edges.push({\n          id: `${n.id}->${k.child.id}`,\n          source: n.id,\n          target: k.child.id,\n          type: \"smoothstep\",\n          label: f !== null ? `${(f * 100).toFixed(f < 0.1 && f > 0 ? 1 : 0)}%` : undefined,\n          labelStyle: { fontSize: 9, fill: \"var(--muted-foreground, #999)\" },\n          labelBgStyle: { fill: \"transparent\" },\n          style: {\n            strokeWidth: w,\n            opacity: f === null ? 0.5 : 0.25 + 0.75 * Math.min(1, f * 2),\n            strokeDasharray: dead ? \"4 4\" : undefined,\n            stroke: dead ? \"#f43f5e\" : undefined,\n          },\n        });\n      });\n\n      return myH;\n    };\n\n    // Local alias so data objects capture a stable name.\n    function toggle(id: string) {\n      setCollapseOverride((m) => {\n        const next = new Map(m);\n        const node = findById(tree.root, id);\n        const def = node?.kind === \"chance\";\n        const cur = next.get(id) ?? def;\n        next.set(id, !cur);\n        return next;\n      });\n    }\n\n    place(tree.root, 0, 0);\n    return { nodes, edges };\n  }, [tree, isCollapsed, freqIdx, onCommitSizes, onToggleAllin, onResetEdit]);\n\n  return (\n    <div className=\"h-full w-full\">\n      <ReactFlow\n        nodes={nodes}\n        edges={edges}\n        nodeTypes={nodeTypes}\n        fitView\n        fitViewOptions={{ padding: 0.15, maxZoom: 1 }}\n        minZoom={0.05}\n        proOptions={{ hideAttribution: true }}\n        nodesDraggable={false}\n        nodesConnectable={false}\n        elementsSelectable\n      >\n        <Background gap={24} size={1} />\n        <Controls showInteractive={false} />\n        <MiniMap pannable zoomable className=\"!bg-card\" />\n      </ReactFlow>\n    </div>\n  );\n}\n\nfunction findByPath(root: FullTreeNode | null, path: string[]): FullTreeNode | null {\n  if (!root) return null;\n  if (samePath(root.path, path) && root.kind === \"action\") return root;\n  for (const k of root.children) {\n    const hit = findByPath(k.child, path);\n    if (hit) return hit;\n  }\n  return null;\n}\n\nfunction findById(root: FullTreeNode | null, id: string): FullTreeNode | null {\n  if (!root) return null;\n  if (root.id === id) return root;\n  for (const k of root.children) {\n    const hit = findById(k.child, id);\n    if (hit) return hit;\n  }\n  return null;\n}\n",
      "type": "registry:component",
      "target": "components/explorer/tree-flow.tsx"
    },
    {
      "path": "src/components/explorer/tree-sizing-editor.tsx",
      "content": "\"use client\";\n\n// GTO-Wizard-style \"Tree edit\" for custom solves. Two layers, matching GTOW:\n//\n//  • Street rules — flop/turn/river × OOP/IP bet sizes, raise sizes, all-in.\n//  • Node edits — click INTO a line (choose Bet 4 at the flop, see the raise\n//    node behind it, …) and override one specific node's sizes; the engine\n//    applies it to exactly that action path (`sizing.nodes`, chance steps\n//    generic \"deal\" so a turn-node edit spans every turn card).\n//\n// The strip shows the betting nodes along the currently selected line with\n// their RESOLVED actions (node edit → street rule → base fields — the same\n// precedence chain the engine's tree builder uses). Amounts are real chip\n// counts computed by simulating the line, so a raise node shows raise-to\n// totals over the grown pot, exactly like the tree the solver will build.\n//\n// Path label encoding must stay byte-identical to the engine's\n// `tree::path_label` (\"Bet 4\", \"Call 4\", \"Raise 12.4\", 1-decimal amounts,\n// bare \"Check\"/\"Fold\") — the engine REJECTS a node edit whose path matches\n// no built node, so a drifted label fails loudly, not silently.\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport { Pencil, Plus, RotateCcw, X } from \"lucide-react\";\nimport type { NodeSizingConfig, StreetSizingConfig, TreeSizingConfig } from \"@/lib/solver/types\";\n\nexport type AllinChoice = \"auto\" | \"on\" | \"off\";\n\nexport interface SizingCell {\n  /** Comma list of pot fractions (\"0.33, 0.75\"), \"\" = inherit, \"none\" = []. */\n  bets: string;\n  /** Same grammar; \"\" = inherit (mirrors bets when those are set). */\n  raises: string;\n  allin: AllinChoice;\n}\n\nexport interface SizingGrid {\n  flop: { oop: SizingCell; ip: SizingCell };\n  turn: { oop: SizingCell; ip: SizingCell };\n  river: { oop: SizingCell; ip: SizingCell };\n}\n\n/** One node-specific edit, UI-side (text fields; lowered on Solve). */\nexport interface NodeEdit {\n  /** Engine-encoded action path from the start-street root. */\n  path: string[];\n  /** Comma list of pot fractions; \"none\" = no bets/raises at this node;\n   *  \"\" = only the all-in choice is overridden. */\n  sizes: string;\n  allin: AllinChoice;\n}\n\nconst STREETS = [\"flop\", \"turn\", \"river\"] as const;\nexport type StreetKey = (typeof STREETS)[number];\ntype Role = \"oop\" | \"ip\";\n\nexport const emptySizingCell = (): SizingCell => ({ bets: \"\", raises: \"\", allin: \"auto\" });\n\nexport const emptySizingGrid = (): SizingGrid => ({\n  flop: { oop: emptySizingCell(), ip: emptySizingCell() },\n  turn: { oop: emptySizingCell(), ip: emptySizingCell() },\n  river: { oop: emptySizingCell(), ip: emptySizingCell() },\n});\n\n/** The builder's base abstraction — what unedited nodes fall back to. */\nexport interface SizingBase {\n  betSizes: number[];\n  /** Empty = raises reuse betSizes (legacy engine chain). */\n  raiseSizes?: number[];\n  /** Empty = river reuses betSizes. */\n  riverBetSizes: number[];\n  addAllin: boolean;\n  maxAggressions: number;\n  riverMaxAggressions?: number;\n  potBb: number;\n  effStackBb: number;\n}\n\n/** Parse one sizes list: \"\" → undefined (inherit), \"none\"/\"-\"/\"0\" → [], else\n *  comma-separated positive pot fractions. Throws with a labelled message. */\nexport function parseCellSizes(raw: string, label: string): number[] | undefined {\n  const s = raw.trim();\n  if (!s) return undefined;\n  if (/^(none|-|0)$/i.test(s)) return [];\n  return s.split(\",\").map((t, i) => {\n    const n = Number(t.trim());\n    if (!Number.isFinite(n) || n <= 0) {\n      throw new Error(`${label} #${i + 1} must be a positive pot fraction (or \"none\")`);\n    }\n    return n;\n  });\n}\n\n/**\n * Lower the street-rule grid + node edits to the engine's `sizing` config.\n * Returns undefined when nothing is overridden (pure legacy geometry).\n */\nexport function sizingFromEditor(\n  grid: SizingGrid,\n  nodeEdits: NodeEdit[] = [],\n): TreeSizingConfig | undefined {\n  const out: TreeSizingConfig = {};\n  for (const street of STREETS) {\n    const st: StreetSizingConfig = {};\n    for (const role of [\"oop\", \"ip\"] as const) {\n      const cell = grid[street][role];\n      const label = `${street} ${role.toUpperCase()}`;\n      const bets = parseCellSizes(cell.bets, `${label} bet size`);\n      const raises = parseCellSizes(cell.raises, `${label} raise size`);\n      if (bets !== undefined) st[`${role}_bet_sizes`] = bets;\n      if (raises !== undefined) st[`${role}_raise_sizes`] = raises;\n      if (cell.allin !== \"auto\") st[`${role}_allin`] = cell.allin === \"on\";\n    }\n    if (Object.keys(st).length > 0) out[street] = st;\n  }\n  const nodes: NodeSizingConfig[] = [];\n  for (const edit of nodeEdits) {\n    const sizes = parseCellSizes(edit.sizes, `node ${edit.path.join(\" → \") || \"root\"} size`);\n    const node: NodeSizingConfig = { path: edit.path };\n    if (sizes !== undefined) node.sizes = sizes;\n    if (edit.allin !== \"auto\") node.allin = edit.allin === \"on\";\n    if (node.sizes !== undefined || node.allin !== undefined) nodes.push(node);\n  }\n  if (nodes.length > 0) out.nodes = nodes;\n  return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Back-compat wrapper (older tests / callers without node edits). */\nexport function sizingFromGrid(grid: SizingGrid): TreeSizingConfig | undefined {\n  return sizingFromEditor(grid, []);\n}\n\n// ---------------------------------------------------------------------------\n// Node-edit modal drafts (GTOW \"Edit Node\")\n// ---------------------------------------------------------------------------\n\n/**\n * The size list in effect at a node, as pot **percents** — the modal's initial\n * draft rows. A valid node edit wins; otherwise the street-rule resolution for\n * the node's bet/raise context. An unparsable edit falls back to the rule,\n * matching `simulateLine`'s preview behavior.\n */\nexport function nodeDraftPercents(node: {\n  toCall: number;\n  resolved: ResolvedNode;\n  edit?: NodeEdit;\n}): number[] {\n  let fracs = node.toCall > 0 ? node.resolved.raises : node.resolved.bets;\n  if (node.edit) {\n    try {\n      const s = parseCellSizes(node.edit.sizes, \"node size\");\n      if (s !== undefined) fracs = s;\n    } catch {\n      /* keep the street-rule fallback */\n    }\n  }\n  return fracs.map((f) => round1(f * 100));\n}\n\n/**\n * Lower modal draft rows (pot percents) to a `NodeEdit.sizes` string: comma\n * pot fractions, or \"none\" for an empty draft (the explicit no-bets override —\n * an empty string would mean \"inherit\" and silently undo the user's deletes).\n * Zero/negative/NaN rows are dropped rather than erroring: the modal's number\n * inputs can transiently hold \"\" while typing.\n */\nexport function draftPercentsToSizes(pcts: number[]): string {\n  const clean = pcts.filter((p) => Number.isFinite(p) && p > 0);\n  if (clean.length === 0) return \"none\";\n  // 4 decimals on the fraction keeps sub-percent sizes exact (0.33% pot →\n  // 0.0033) without float noise like 0.33000000000000004.\n  return clean.map((p) => String(Math.round(p * 100) / 10000)).join(\", \");\n}\n\n/** What one node resolves to at street-rule level (mirrors tree.rs). */\nexport interface ResolvedNode {\n  bets: number[];\n  raises: number[];\n  allin: boolean;\n  betsInherited: boolean;\n  raisesInherited: boolean;\n  error?: string;\n}\n\nexport function resolveNode(\n  grid: SizingGrid,\n  base: SizingBase,\n  street: StreetKey,\n  role: Role,\n): ResolvedNode {\n  const cell = grid[street][role];\n  let bets: number[] | undefined;\n  let raises: number[] | undefined;\n  let error: string | undefined;\n  try {\n    bets = parseCellSizes(cell.bets, \"bet size\");\n  } catch (e) {\n    error = e instanceof Error ? e.message : String(e);\n  }\n  try {\n    raises = parseCellSizes(cell.raises, \"raise size\");\n  } catch (e) {\n    error = error ?? (e instanceof Error ? e.message : String(e));\n  }\n  const legacyBets =\n    street === \"river\" && base.riverBetSizes.length > 0 ? base.riverBetSizes : base.betSizes;\n  const legacyRaises =\n    street === \"river\" && base.riverBetSizes.length > 0\n      ? base.riverBetSizes\n      : base.raiseSizes && base.raiseSizes.length > 0\n        ? base.raiseSizes\n        : base.betSizes;\n  return {\n    bets: bets ?? legacyBets,\n    raises: raises ?? bets ?? legacyRaises,\n    allin: cell.allin === \"auto\" ? base.addAllin : cell.allin === \"on\",\n    betsInherited: bets === undefined,\n    raisesInherited: raises === undefined && bets === undefined,\n    error,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Line simulation — mirrors the engine's builder math (tree.rs add_bets) so\n// the strip shows the same nodes, actions, and chip amounts the solve builds.\n// ---------------------------------------------------------------------------\n\n/** Byte-identical to the engine's `tree::round1` for positive amounts. */\nconst round1 = (x: number) => Math.round(x * 10) / 10;\n\n/** Engine `tree::path_label`: label + 1-decimal amount when chips move. */\nexport function pathLabel(label: string, add: number): string {\n  return add > 0 ? `${label} ${round1(add)}` : label;\n}\n\nexport interface SimAction {\n  /** Path token, engine encoding (\"Bet 4\", \"Call 4\", \"Check\", \"AllIn 98.1\"). */\n  token: string;\n  label: \"Check\" | \"Bet\" | \"Raise\" | \"AllIn\" | \"Call\" | \"Fold\";\n  /** Chips this action adds. */\n  add: number;\n  /** Pot fraction (bets/raises only) for the % badge. */\n  frac?: number;\n}\n\nexport interface SimNode {\n  street: StreetKey;\n  role: Role;\n  /** Pot BEFORE this player acts. */\n  pot: number;\n  toCall: number;\n  /** Path from the root to this node (engine encoding; deals as \"deal\"). */\n  path: string[];\n  actions: SimAction[];\n  /** Street-rule resolution behind this node (for the editor panel). */\n  resolved: ResolvedNode;\n  /** The node edit applied here, if any. */\n  edit?: NodeEdit;\n}\n\ninterface SimState {\n  streetIdx: number; // index into the streets visible from the start street\n  pot: number;\n  stacks: [number, number];\n  paid: [number, number]; // this street\n  toCall: number;\n  player: 0 | 1;\n  aggressions: number;\n  path: string[];\n}\n\nconst sameNodePath = (a: string[], b: string[]) =>\n  a.length === b.length && a.every((t, i) => t === b[i]);\n\n/**\n * Walk the tree along `chosen` (then a check/call default continuation),\n * returning the decision nodes the strip renders. Stops when a fold ends the\n * hand, stacks are empty (pure runout), or the river closes.\n */\nexport function simulateLine(\n  grid: SizingGrid,\n  nodeEdits: NodeEdit[],\n  base: SizingBase,\n  boardCards: number,\n  chosen: string[],\n): SimNode[] {\n  const startIdx = boardCards >= 5 ? 2 : boardCards === 4 ? 1 : 0;\n  const streets = STREETS.slice(startIdx);\n  const maxAggrFor = (s: StreetKey) =>\n    s === \"river\" ? (base.riverMaxAggressions ?? base.maxAggressions) : base.maxAggressions;\n\n  const nodes: SimNode[] = [];\n  let st: SimState = {\n    streetIdx: 0,\n    pot: base.potBb,\n    stacks: [base.effStackBb, base.effStackBb],\n    paid: [0, 0],\n    toCall: 0,\n    player: 0,\n    aggressions: 0,\n    path: [],\n  };\n  let cursor = 0;\n\n  for (let guard = 0; guard < 64; guard++) {\n    const street = streets[st.streetIdx];\n    if (!street) break;\n    const role: Role = st.player === 0 ? \"oop\" : \"ip\";\n    const resolved = resolveNode(grid, base, street, role);\n    const edit = nodeEdits.find((e) => sameNodePath(e.path, st.path));\n\n    // Resolve this node's sizes/allin: node edit > street rule > base.\n    let sizes = st.toCall > 0 ? resolved.raises : resolved.bets;\n    let allin = resolved.allin;\n    if (edit) {\n      try {\n        const s = parseCellSizes(edit.sizes, \"node size\");\n        if (s !== undefined) sizes = s;\n      } catch {\n        /* invalid text — preview falls back to the street rule */\n      }\n      if (edit.allin !== \"auto\") allin = edit.allin === \"on\";\n    }\n\n    const stack = st.stacks[st.player];\n    const actions: SimAction[] = [];\n    const canAggress = st.aggressions < maxAggrFor(street) && stack > st.toCall + 1e-9;\n    if (st.toCall <= 1e-9) {\n      actions.push({ token: \"Check\", label: \"Check\", add: 0 });\n    } else {\n      actions.push({ token: \"Fold\", label: \"Fold\", add: 0 });\n      const callAmt = Math.min(st.toCall, stack);\n      actions.push({ token: pathLabel(\"Call\", callAmt), label: \"Call\", add: callAmt });\n    }\n    if (canAggress) {\n      const potAfterCall = st.pot + st.toCall;\n      for (const f of sizes) {\n        const totalAdd = st.toCall + f * potAfterCall;\n        if (totalAdd >= stack - 1e-9) continue; // shove covers it\n        if (totalAdd <= st.toCall + 1e-9) continue;\n        actions.push({\n          token: pathLabel(st.toCall > 0 ? \"Raise\" : \"Bet\", totalAdd),\n          label: st.toCall > 0 ? \"Raise\" : \"Bet\",\n          add: totalAdd,\n          frac: f,\n        });\n      }\n      if (allin) {\n        actions.push({ token: pathLabel(\"AllIn\", stack), label: \"AllIn\", add: stack });\n      }\n    }\n\n    nodes.push({\n      street,\n      role,\n      pot: st.pot,\n      toCall: st.toCall,\n      path: st.path,\n      actions,\n      resolved,\n      edit,\n    });\n\n    // Pick the next step: the chosen line while it lasts, then check/call.\n    let tok = cursor < chosen.length ? chosen[cursor++] : undefined;\n    if (tok !== undefined && !actions.some((a) => a.token === tok)) {\n      // The chosen line no longer exists (sizes changed under it) — fall back\n      // to the default continuation from here on.\n      tok = undefined;\n      cursor = chosen.length;\n    }\n    const act =\n      tok !== undefined\n        ? actions.find((a) => a.token === tok)!\n        : (actions.find((a) => a.label === \"Check\") ?? actions.find((a) => a.label === \"Call\"))!;\n\n    // Apply the action (engine State transitions, HU).\n    const p = st.player;\n    const o = (1 - p) as 0 | 1;\n    if (act.label === \"Fold\") break;\n    if (act.label === \"Check\") {\n      if (p === 0) {\n        st = { ...st, player: 1, path: [...st.path, act.token] };\n      } else {\n        // check-check → next street\n        if (st.streetIdx + 1 >= streets.length) break; // river closes\n        st = {\n          ...st,\n          streetIdx: st.streetIdx + 1,\n          paid: [0, 0],\n          toCall: 0,\n          player: 0,\n          aggressions: 0,\n          path: [...st.path, act.token, \"deal\"],\n        };\n      }\n      continue;\n    }\n    if (act.label === \"Call\") {\n      const stacks: [number, number] = [...st.stacks];\n      stacks[p] -= act.add;\n      const pot = st.pot + act.add;\n      if (stacks[p] <= 1e-9 || stacks[o] <= 1e-9) break; // all-in call → runout\n      if (st.streetIdx + 1 >= streets.length) break; // river call closes the hand\n      st = {\n        streetIdx: st.streetIdx + 1,\n        pot,\n        stacks,\n        paid: [0, 0],\n        toCall: 0,\n        player: 0,\n        aggressions: 0,\n        path: [...st.path, act.token, \"deal\"],\n      };\n      continue;\n    }\n    // Bet / Raise / AllIn\n    {\n      const stacks: [number, number] = [...st.stacks];\n      stacks[p] -= act.add;\n      const paid: [number, number] = [...st.paid];\n      paid[p] += act.add;\n      st = {\n        streetIdx: st.streetIdx,\n        pot: st.pot + act.add,\n        stacks,\n        paid,\n        toCall: paid[p] - paid[o],\n        player: o,\n        aggressions: st.aggressions + 1,\n        path: [...st.path, act.token],\n      };\n    }\n  }\n  return nodes;\n}\n\n// ---------------------------------------------------------------------------\n// UI\n// ---------------------------------------------------------------------------\n\nconst fmt = (n: number) => String(round1(n));\n\nconst CELL_INPUT =\n  \"h-8 w-full rounded-md border border-input bg-card px-2 text-xs text-foreground outline-none transition-colors placeholder:text-muted-foreground/50 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40\";\n\nfunction NodeCard({\n  node,\n  index,\n  selected,\n  nextToken,\n  onSelect,\n  onPickAction,\n  onEdit,\n}: {\n  node: SimNode;\n  index: number;\n  selected: boolean;\n  /** The action this line continues with (highlighted). */\n  nextToken?: string;\n  onSelect: () => void;\n  onPickAction: (token: string) => void;\n  /** Open the Edit Node modal for this node. */\n  onEdit: () => void;\n}) {\n  return (\n    <div\n      role=\"button\"\n      tabIndex={0}\n      onClick={onSelect}\n      onKeyDown={(e) => {\n        if (e.key === \"Enter\" || e.key === \" \") onSelect();\n      }}\n      aria-label={`Node ${index}: ${node.street} ${node.role.toUpperCase()}`}\n      className={`flex w-36 shrink-0 cursor-pointer flex-col gap-1 rounded-lg border px-2.5 py-2 transition-colors ${\n        selected\n          ? \"border-ring bg-card ring-2 ring-ring/40\"\n          : \"border-border bg-card/60 hover:border-ring/50\"\n      }`}\n    >\n      <span className=\"flex items-center justify-between text-[10px] font-semibold uppercase tracking-wide text-muted-foreground\">\n        {node.role.toUpperCase()}\n        <span className=\"flex items-center gap-1\">\n          {node.edit ? (\n            <span className=\"rounded bg-amber-500/15 px-1 py-px text-[9px] font-medium normal-case text-amber-400\">\n              node edit\n            </span>\n          ) : !node.resolved.betsInherited || !node.resolved.raisesInherited ? (\n            <span className=\"rounded bg-foreground/10 px-1 py-px text-[9px] font-medium normal-case text-foreground\">\n              street rule\n            </span>\n          ) : null}\n          <button\n            type=\"button\"\n            onClick={(e) => {\n              e.stopPropagation();\n              onEdit();\n            }}\n            aria-label={`Edit node ${index}`}\n            className=\"rounded p-0.5 text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground\"\n          >\n            <Pencil className=\"size-3\" />\n          </button>\n        </span>\n      </span>\n      {node.actions.map((a) => (\n        <button\n          key={a.token}\n          type=\"button\"\n          onClick={(e) => {\n            e.stopPropagation();\n            onPickAction(a.token);\n          }}\n          className={`flex items-baseline justify-between rounded px-1.5 py-0.5 text-left text-[11px] tabular-nums transition-colors ${\n            nextToken === a.token\n              ? \"bg-foreground text-background\"\n              : \"bg-accent/60 text-foreground hover:bg-accent\"\n          }`}\n        >\n          {a.label === \"AllIn\" ? `All-in ${fmt(a.add)}` : a.add > 0 ? `${a.label} ${fmt(a.add)}` : a.label}\n          {a.frac !== undefined ? (\n            <span\n              className={`text-[10px] ${nextToken === a.token ? \"text-background/70\" : \"text-muted-foreground\"}`}\n            >\n              {Math.round(a.frac * 100)}%\n            </span>\n          ) : null}\n        </button>\n      ))}\n      {node.actions.length <= 1 ? (\n        <span className=\"text-[10px] italic text-muted-foreground/70\">check only</span>\n      ) : null}\n      {node.resolved.error ? (\n        <span className=\"text-[9px] text-destructive\">invalid — showing inherited</span>\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * GTOW-style \"Edit Node\" modal: one row per bet/raise size (numeric % field +\n * slider + remove), an add-size row, and an all-in row. Draft state is local —\n * nothing touches the tree until Confirm. Fixed actions (Check/Fold/Call) are\n * shown but not removable: the engine's node overrides shape *sizes*, never\n * the passive actions.\n */\nfunction NodeEditModal({\n  node,\n  hasAnyEdits,\n  onConfirm,\n  onRemoveEdit,\n  onRemoveAll,\n  onClose,\n}: {\n  node: SimNode;\n  hasAnyEdits: boolean;\n  /** Commit the draft: a `NodeEdit.sizes` string + the all-in choice. */\n  onConfirm: (sizes: string, allin: AllinChoice) => void;\n  onRemoveEdit: () => void;\n  onRemoveAll: () => void;\n  onClose: () => void;\n}) {\n  const [pcts, setPcts] = useState<(number | \"\")[]>(() => nodeDraftPercents(node));\n  const [allin, setAllin] = useState<AllinChoice>(node.edit?.allin ?? \"auto\");\n\n  useEffect(() => {\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") onClose();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [onClose]);\n\n  const kind = node.toCall > 0 ? \"Raise\" : \"Bet\";\n  const fixed = node.actions.filter((a) => a.label === \"Check\" || a.label === \"Fold\" || a.label === \"Call\");\n  const shove = node.actions.find((a) => a.label === \"AllIn\");\n  const setPct = (i: number, v: number | \"\") =>\n    setPcts((p) => p.map((x, j) => (j === i ? v : x)));\n\n  const lineLabel = node.path.filter((t) => t !== \"deal\").join(\" → \");\n\n  return (\n    <div\n      className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4\"\n      onClick={onClose}\n      role=\"presentation\"\n    >\n      <div\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={`Edit node: ${node.street} ${node.role.toUpperCase()}`}\n        onClick={(e) => e.stopPropagation()}\n        className=\"flex w-full max-w-md flex-col gap-3 rounded-xl border border-border bg-card p-4 shadow-xl\"\n      >\n        <div className=\"flex items-start justify-between gap-2\">\n          <div className=\"flex flex-col\">\n            <span className=\"text-base font-semibold text-foreground\">Edit Node</span>\n            <span className=\"text-[11px] text-muted-foreground\">\n              {node.street} · {node.role.toUpperCase()} · pot {fmt(node.pot)}\n              {lineLabel ? ` · after ${lineLabel}` : \"\"}\n              {node.path.includes(\"deal\") ? \" (every runout card)\" : \"\"}\n            </span>\n          </div>\n          <button\n            type=\"button\"\n            onClick={onClose}\n            aria-label=\"Close\"\n            className=\"rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n          >\n            <X className=\"size-4\" />\n          </button>\n        </div>\n\n        <div className=\"flex flex-col gap-1.5\">\n          {/* Passive actions — part of the tree, not removable. */}\n          {fixed.map((a) => (\n            <div\n              key={a.label}\n              className=\"flex h-9 items-center justify-between rounded-md bg-accent/40 px-3 text-sm text-foreground\"\n            >\n              <span>{a.add > 0 ? `${a.label} ${fmt(a.add)}` : a.label}</span>\n              <span className=\"text-[10px] uppercase tracking-wide text-muted-foreground/60\">\n                fixed\n              </span>\n            </div>\n          ))}\n\n          {/* One row per draft size. */}\n          {pcts.map((p, i) => (\n            <div\n              key={i}\n              className=\"flex h-9 items-center gap-2 rounded-md bg-accent/40 px-3 text-sm\"\n            >\n              <span className=\"w-10 shrink-0 text-foreground\">{kind}</span>\n              <input\n                type=\"number\"\n                min={1}\n                value={p}\n                onChange={(e) =>\n                  setPct(i, e.target.value === \"\" ? \"\" : Number(e.target.value))\n                }\n                aria-label={`${kind} size ${i + 1} (% of pot)`}\n                className=\"h-6 w-16 rounded border border-input bg-card px-1.5 text-right text-xs text-foreground outline-none tabular-nums focus-visible:border-ring\"\n              />\n              <span className=\"text-[11px] text-muted-foreground\">%</span>\n              <input\n                type=\"range\"\n                min={1}\n                max={200}\n                step={1}\n                value={typeof p === \"number\" ? Math.min(Math.max(p, 1), 200) : 1}\n                onChange={(e) => setPct(i, Number(e.target.value))}\n                aria-label={`${kind} size ${i + 1} slider`}\n                className=\"min-w-0 flex-1 accent-foreground\"\n              />\n              <button\n                type=\"button\"\n                onClick={() => setPcts((prev) => prev.filter((_, j) => j !== i))}\n                aria-label={`Remove ${kind.toLowerCase()} size ${i + 1}`}\n                className=\"rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n              >\n                <X className=\"size-3.5\" />\n              </button>\n            </div>\n          ))}\n\n          {/* Add-size row. */}\n          <button\n            type=\"button\"\n            onClick={() => setPcts((prev) => [...prev, 75])}\n            className=\"flex h-9 items-center justify-between rounded-md border border-dashed border-border px-3 text-sm text-muted-foreground transition-colors hover:border-ring/50 hover:text-foreground\"\n          >\n            <span>{kind}</span>\n            <Plus className=\"size-4\" />\n          </button>\n\n          {/* All-in row. */}\n          <div className=\"flex h-9 items-center justify-between rounded-md bg-accent/40 px-3 text-sm text-foreground\">\n            <span>All-in{shove ? ` ${fmt(shove.add)}` : \"\"}</span>\n            <select\n              value={allin}\n              onChange={(e) => setAllin(e.target.value as AllinChoice)}\n              aria-label=\"All-in at this node\"\n              className=\"h-6 rounded border border-input bg-card px-1 text-xs text-foreground outline-none focus-visible:border-ring\"\n            >\n              <option value=\"auto\">auto (street rule)</option>\n              <option value=\"on\">yes</option>\n              <option value=\"off\">no</option>\n            </select>\n          </div>\n        </div>\n\n        <div className=\"flex items-center justify-between gap-2 pt-1\">\n          <div className=\"flex items-center gap-2\">\n            {hasAnyEdits ? (\n              <button\n                type=\"button\"\n                onClick={onRemoveAll}\n                className=\"text-[11px] text-muted-foreground transition-colors hover:text-foreground\"\n              >\n                Delete All Node Edits\n              </button>\n            ) : null}\n            {node.edit ? (\n              <button\n                type=\"button\"\n                onClick={onRemoveEdit}\n                className=\"text-[11px] text-muted-foreground transition-colors hover:text-foreground\"\n              >\n                Remove this edit\n              </button>\n            ) : null}\n          </div>\n          <button\n            type=\"button\"\n            onClick={() =>\n              onConfirm(\n                draftPercentsToSizes(pcts.map((p) => (typeof p === \"number\" ? p : NaN))),\n                allin,\n              )\n            }\n            className=\"rounded-md bg-foreground px-4 py-1.5 text-sm font-medium text-background transition-colors hover:bg-foreground/90\"\n          >\n            Confirm\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport function TreeSizingEditor({\n  grid,\n  onChange,\n  nodeEdits,\n  onNodeEditsChange,\n  boardCards,\n  base,\n}: {\n  grid: SizingGrid;\n  onChange: (g: SizingGrid) => void;\n  nodeEdits: NodeEdit[];\n  onNodeEditsChange: (edits: NodeEdit[]) => void;\n  /** 3/4/5 → flop/turn/river start; earlier streets are hidden (never built). */\n  boardCards: number;\n  base: SizingBase;\n}) {\n  // The action line the strip walks (engine path tokens), plus which node\n  // card is selected for editing.\n  const [line, setLine] = useState<string[]>([]);\n  const [selectedIdx, setSelectedIdx] = useState(0);\n  // The GTOW-style \"Edit Node\" modal, over the selected node.\n  const [modalOpen, setModalOpen] = useState(false);\n\n  const sim = useMemo(\n    () => simulateLine(grid, nodeEdits, base, boardCards, line),\n    [grid, nodeEdits, base, boardCards, line],\n  );\n  const sel = sim[Math.min(selectedIdx, sim.length - 1)];\n\n  const setCell = (street: StreetKey, role: Role, patch: Partial<SizingCell>) => {\n    onChange({\n      ...grid,\n      [street]: { ...grid[street], [role]: { ...grid[street][role], ...patch } },\n    });\n  };\n\n  const nodeEditFor = (path: string[]) => nodeEdits.find((e) => sameNodePath(e.path, path));\n  const patchNodeEdit = (path: string[], patch: Partial<Omit<NodeEdit, \"path\">>) => {\n    const existing = nodeEditFor(path);\n    const next: NodeEdit = { path, sizes: \"\", allin: \"auto\", ...existing, ...patch };\n    const rest = nodeEdits.filter((e) => !sameNodePath(e.path, path));\n    // An all-default edit is no edit — drop the entry.\n    if (next.sizes.trim() === \"\" && next.allin === \"auto\") onNodeEditsChange(rest);\n    else onNodeEditsChange([...rest, next]);\n  };\n\n  const pickAction = (nodeIdx: number, token: string) => {\n    // Rebuild the chosen line: everything that led to this node + the pick.\n    // Navigation only — the Edit Node modal opens from the card's pencil.\n    setLine([...sim[nodeIdx].path, token]);\n    setSelectedIdx(nodeIdx + 1 <= sim.length ? nodeIdx + 1 : nodeIdx);\n  };\n\n  const cell = sel ? grid[sel.street][sel.role] : null;\n  const selEdit = sel ? nodeEditFor(sel.path) : undefined;\n\n  return (\n    <div className=\"flex flex-col gap-3\">\n      {/* ---- Line strip ---- */}\n      <div className=\"flex items-start gap-2 overflow-x-auto pb-1\">\n        {sim.map((node, i) => {\n          // Street header card before the first node of each street.\n          const header =\n            i === 0 || sim[i - 1].street !== node.street ? (\n              <div\n                key={`h-${node.street}`}\n                className=\"flex w-14 shrink-0 flex-col items-center justify-center gap-1 self-stretch rounded-lg border border-border bg-card/40 px-2 py-2\"\n              >\n                <span className=\"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground\">\n                  {node.street}\n                </span>\n                <span className=\"text-[10px] text-muted-foreground/70 tabular-nums\">\n                  pot {fmt(node.pot)}\n                </span>\n              </div>\n            ) : null;\n          // The token this line takes out of this node (to highlight it).\n          const nextToken = sim[i + 1]\n            ? sim[i + 1].path[node.path.length] // first token added after this node\n            : undefined;\n          return (\n            <div key={i} className=\"contents\">\n              {header}\n              <NodeCard\n                node={node}\n                index={i}\n                selected={sel === node}\n                nextToken={nextToken}\n                onSelect={() => setSelectedIdx(i)}\n                onPickAction={(tok) => pickAction(i, tok)}\n                onEdit={() => {\n                  setSelectedIdx(i);\n                  setModalOpen(true);\n                }}\n              />\n            </div>\n          );\n        })}\n        {line.length > 0 ? (\n          <button\n            type=\"button\"\n            onClick={() => {\n              setLine([]);\n              setSelectedIdx(0);\n            }}\n            className=\"flex h-8 shrink-0 items-center gap-1 self-center rounded-md border border-border bg-card px-2 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n          >\n            <RotateCcw className=\"size-3\" /> Reset line\n          </button>\n        ) : null}\n      </div>\n\n      {/* ---- Editor for the selected node ---- */}\n      {sel && cell ? (\n        <div className=\"flex flex-col gap-2 rounded-lg border border-border bg-card/40 p-3\">\n          <div className=\"flex flex-wrap items-center justify-between gap-2\">\n            <span className=\"text-[11px] font-medium uppercase tracking-wide text-muted-foreground\">\n              {sel.street} · {sel.role.toUpperCase()}\n              {sel.path.length > 0 ? (\n                <span className=\"ml-2 normal-case tracking-normal text-muted-foreground/70\">\n                  after {sel.path.filter((t) => t !== \"deal\").join(\" → \")}\n                </span>\n              ) : null}\n            </span>\n            <div className=\"flex items-center gap-2 text-[11px]\">\n              <span className=\"rounded-md border border-border px-2 py-0.5 text-muted-foreground\">\n                street rule: all {sel.street} {sel.role.toUpperCase()} nodes\n              </span>\n              <button\n                type=\"button\"\n                onClick={() => setModalOpen(true)}\n                className=\"flex items-center gap-1 rounded-md bg-foreground px-2 py-0.5 font-medium text-background transition-colors hover:bg-foreground/90\"\n              >\n                <Pencil className=\"size-3\" /> Edit this node\n              </button>\n            </div>\n          </div>\n\n          {\n            <>\n              <div className=\"grid grid-cols-2 gap-3\">\n                <label className=\"flex flex-col gap-1\">\n                  <span className=\"text-[11px] text-muted-foreground\">Bet sizes (× pot)</span>\n                  <input\n                    value={cell.bets}\n                    onChange={(e) => setCell(sel.street, sel.role, { bets: e.target.value })}\n                    placeholder=\"inherit\"\n                    spellCheck={false}\n                    aria-label={`${sel.street} ${sel.role.toUpperCase()} bet sizes`}\n                    className={CELL_INPUT}\n                  />\n                </label>\n                <label className=\"flex flex-col gap-1\">\n                  <span className=\"text-[11px] text-muted-foreground\">Raise sizes (× pot)</span>\n                  <input\n                    value={cell.raises}\n                    onChange={(e) => setCell(sel.street, sel.role, { raises: e.target.value })}\n                    placeholder=\"inherit\"\n                    spellCheck={false}\n                    aria-label={`${sel.street} ${sel.role.toUpperCase()} raise sizes`}\n                    className={CELL_INPUT}\n                  />\n                </label>\n              </div>\n              <div className=\"flex items-center justify-between gap-2\">\n                <label className=\"flex items-center gap-2 text-[11px] text-muted-foreground\">\n                  All-in\n                  <select\n                    value={cell.allin}\n                    onChange={(e) =>\n                      setCell(sel.street, sel.role, { allin: e.target.value as AllinChoice })\n                    }\n                    aria-label={`${sel.street} ${sel.role.toUpperCase()} all-in`}\n                    className=\"h-8 rounded-md border border-input bg-card px-1.5 text-xs text-foreground outline-none transition-colors focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40\"\n                  >\n                    <option value=\"auto\">auto</option>\n                    <option value=\"on\">yes</option>\n                    <option value=\"off\">no</option>\n                  </select>\n                </label>\n                {cell.bets.trim() !== \"\" || cell.raises.trim() !== \"\" || cell.allin !== \"auto\" ? (\n                  <button\n                    type=\"button\"\n                    onClick={() => setCell(sel.street, sel.role, emptySizingCell())}\n                    className=\"rounded-md border border-border bg-card px-2 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                  >\n                    Reset rule\n                  </button>\n                ) : null}\n              </div>\n            </>\n          }\n        </div>\n      ) : null}\n\n      {/* ---- GTOW-style Edit Node modal ---- */}\n      {modalOpen && sel ? (\n        <NodeEditModal\n          // Remount per node/edit state so the draft always seeds fresh.\n          key={`${sel.path.join(\"|\")}:${selEdit ? selEdit.sizes + selEdit.allin : \"-\"}`}\n          node={sel}\n          hasAnyEdits={nodeEdits.length > 0}\n          onConfirm={(sizes, allin) => {\n            patchNodeEdit(sel.path, { sizes, allin });\n            setModalOpen(false);\n          }}\n          onRemoveEdit={() => {\n            if (selEdit) onNodeEditsChange(nodeEdits.filter((e) => e !== selEdit));\n            setModalOpen(false);\n          }}\n          onRemoveAll={() => {\n            onNodeEditsChange([]);\n            setModalOpen(false);\n          }}\n          onClose={() => setModalOpen(false)}\n        />\n      ) : null}\n\n      {nodeEdits.length > 0 ? (\n        <span className=\"text-[11px] text-muted-foreground/70 tabular-nums\">\n          {nodeEdits.length} node edit{nodeEdits.length === 1 ? \"\" : \"s\"} active — changing base\n          or street sizes can orphan a node edit; the solve will refuse it with the exact path.\n        </span>\n      ) : null}\n      <span className=\"text-[11px] text-muted-foreground/70\">\n        Click an action to walk into that line; click a card to select it. The panel edits the\n        street rule; the pencil (or &quot;Edit this node&quot;) opens the Edit Node dialog for that\n        exact decision point, GTO-Wizard style. Blank street fields inherit; type{\" \"}\n        <code>none</code>\n        {\" to remove bets or raises. Amounts are chips assuming the shown line.\"}\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/tree-sizing-editor.tsx"
    },
    {
      "path": "src/components/explorer/tree-visualization-modal.tsx",
      "content": "\"use client\";\n\n// Near-fullscreen React Flow view of the game tree the solver will build.\n// Editable nodes: change a node's sizes / all-in inline → lowered to engine\n// `NodeEdit`s shared with the Tree-edit strip, so pruning here IS the solve\n// config. After a solve the edges carry aggregate action frequencies — the\n// bucket-analysis view for spotting sizes the solution never uses.\n\nimport { useEffect, useState } from \"react\";\nimport { X } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport type { SolverResult } from \"@/lib/solver/types\";\nimport type { FullTree } from \"@/lib/explorer/tree-sim\";\nimport { TreeFlow } from \"./tree-flow\";\nimport type { NodeEdit, SizingBase, SizingGrid } from \"./tree-sizing-editor\";\n\ninterface TreeVisualizationModalProps {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  grid: SizingGrid;\n  base: SizingBase;\n  boardCards: number;\n  nodeEdits: NodeEdit[];\n  onNodeEditsChange: (edits: NodeEdit[]) => void;\n  result?: SolverResult | null;\n  onSolve: () => void;\n  isSolving?: boolean;\n}\n\nexport function TreeVisualizationModal({\n  open,\n  onOpenChange,\n  grid,\n  base,\n  boardCards,\n  nodeEdits,\n  onNodeEditsChange,\n  result,\n  onSolve,\n  isSolving = false,\n}: TreeVisualizationModalProps) {\n  const [stats, setStats] = useState<FullTree | null>(null);\n\n  useEffect(() => {\n    if (!open) return;\n    function onKey(e: KeyboardEvent) {\n      if (e.key === \"Escape\") onOpenChange(false);\n    }\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [open, onOpenChange]);\n\n  if (!open) return null;\n\n  return (\n    <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4\">\n      <div className=\"flex h-[92vh] w-[96vw] max-w-[1600px] flex-col overflow-hidden rounded-lg border border-border bg-card shadow-xl\">\n        <div className=\"flex items-center gap-4 border-b border-border px-4 py-3\">\n          <div className=\"min-w-0\">\n            <h2 className=\"text-base font-semibold text-foreground\">Game tree</h2>\n            <p className=\"truncate text-xs text-muted-foreground\">\n              {stats\n                ? `${stats.stats.actionNodes} action · ${stats.stats.chanceNodes} chance · ${stats.stats.terminalNodes} terminal nodes${stats.truncated ? \" — TRUNCATED (node budget)\" : \"\"}`\n                : \"…\"}\n              {\" · \"}\n              edit sizes on any node (&quot;none&quot; = prune all bets there); deals are collapsed —\n              expand to open the runout.\n              {result?.nodes\n                ? \" Edge % = aggregate frequency; dashed red = never used (prune it).\"\n                : \" Solve to overlay usage frequencies.\"}\n            </p>\n          </div>\n          <div className=\"ml-auto flex items-center gap-2\">\n            {nodeEdits.length > 0 ? (\n              <>\n                <span className=\"text-xs text-amber-400\">{nodeEdits.length} node edit(s)</span>\n                <Button size=\"sm\" variant=\"outline\" onClick={() => onNodeEditsChange([])}>\n                  Clear edits\n                </Button>\n              </>\n            ) : null}\n            <Button\n              size=\"sm\"\n              onClick={() => {\n                onOpenChange(false);\n                onSolve();\n              }}\n              disabled={isSolving}\n            >\n              {isSolving ? \"Solving…\" : \"Run solve\"}\n            </Button>\n            <button\n              onClick={() => onOpenChange(false)}\n              className=\"rounded p-1 text-muted-foreground hover:bg-accent\"\n            >\n              <X size={18} />\n            </button>\n          </div>\n        </div>\n\n        <div className=\"min-h-0 flex-1\">\n          <TreeFlow\n            grid={grid}\n            base={base}\n            boardCards={boardCards}\n            nodeEdits={nodeEdits}\n            onNodeEditsChange={onNodeEditsChange}\n            result={result}\n            onStats={setStats}\n          />\n        </div>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/explorer/tree-visualization-modal.tsx"
    },
    {
      "path": "src/components/solver/scenario-strip.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { Loader2, Undo2 } from \"lucide-react\";\nimport {\n  ALL_HANDS,\n  fullRange,\n  totalCombos,\n  type RangePlayer,\n  type RangeWeights,\n} from \"@/lib/solver/range-model\";\nimport {\n  clampWeights,\n  formatBb,\n  getManifest,\n  getNode,\n  labelForAction,\n  parseHistory,\n  PLAY_ORDER,\n  resolveAfterAction,\n  ROOT_HISTORY,\n  sortActionsForDisplay,\n  type NodeAction,\n  type NodeResponse,\n  type Position,\n  type SeatState,\n} from \"@/lib/solver/preflop\";\n\nconst FULL_COMBOS = 1326;\n\nexport interface ResolvedScenario {\n  oop: RangeWeights;\n  ip: RangeWeights;\n  oopPos: Position;\n  ipPos: Position;\n}\n\ninterface HeadsUp {\n  oop: Position;\n  ip: Position;\n  survivors: [Position, Position];\n  closedActor: Position;\n  closedHistory: string;\n}\n\ninterface Props {\n  /** Emitted when the pot closes heads-up (ranges + seats) or the walk resets (null). */\n  onResolved: (r: ResolvedScenario | null) => void;\n}\n\n/**\n * GTO-Wizard–style preflop strip for the solver. The user walks the NL tree one\n * seat at a time; the moment a raise is called the pot closes to heads-up, the\n * two survivors' ranges are handed up to the solver as OOP/IP, and a preview of\n * each range is shown below the strip.\n */\nexport function ScenarioStrip({ onResolved }: Props) {\n  const [stack, setStack] = useState(100);\n  const [stacks, setStacks] = useState<number[]>([100]);\n\n  const [history, setHistory] = useState(ROOT_HISTORY);\n  const [node, setNode] = useState<NodeResponse | null>(null);\n  const [loading, setLoading] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n  const [captured, setCaptured] = useState<Partial<Record<Position, RangeWeights>>>({});\n  const [headsUp, setHeadsUp] = useState<HeadsUp | null>(null);\n  const [resolved, setResolved] = useState<ResolvedScenario | null>(null);\n\n  // Discover the NL tree's available stacks for the picker.\n  useEffect(() => {\n    let cancelled = false;\n    getManifest()\n      .then((m) => {\n        if (cancelled) return;\n        setStacks(m.stacks);\n        setStack((s) => (m.stacks.includes(s) ? s : (m.stacks[0] ?? s)));\n      })\n      .catch(() => {});\n    return () => {\n      cancelled = true;\n    };\n  }, []);\n\n  const emit = (r: ResolvedScenario | null) => {\n    setResolved(r);\n    onResolved(r);\n  };\n\n  // A different stack is a different tree — re-root the walk. Handled here (not\n  // in an effect) so changing stack doesn't cascade renders.\n  const changeStack = (next: number) => {\n    setStack(next);\n    setHistory(ROOT_HISTORY);\n    setCaptured({});\n    setHeadsUp(null);\n    setError(null);\n    emit(null);\n  };\n\n  // Fetch the current decision node while walking (not once the pot has closed).\n  useEffect(() => {\n    if (headsUp) return;\n    let cancelled = false;\n    async function run() {\n      setLoading(true);\n      setError(null);\n      try {\n        const n = await getNode(stack, history);\n        if (!cancelled) setNode(n);\n      } catch (err) {\n        if (!cancelled) {\n          setNode(null);\n          setError(err instanceof Error ? err.message : \"No range here.\");\n        }\n      } finally {\n        if (!cancelled) setLoading(false);\n      }\n    }\n    run();\n    return () => {\n      cancelled = true;\n    };\n  }, [stack, history, headsUp]);\n\n  const advance = (action: NodeAction) => {\n    if (!node) return;\n    const nextCaptured = { ...captured, [node.actor]: clampWeights(action.weights) };\n    setCaptured(nextCaptured);\n\n    const res = resolveAfterAction(history, action.action, action.kind, stack);\n    if (res.kind === \"terminal\") {\n      setError(\"Everyone folded — no postflop spot on this line. Rewind and pick another action.\");\n      return;\n    }\n    if (res.kind === \"headsup\") {\n      setHeadsUp({\n        oop: res.oop,\n        ip: res.ip,\n        survivors: res.survivors,\n        closedActor: node.actor,\n        closedHistory: history,\n      });\n      setError(null);\n      emit({\n        oop: nextCaptured[res.oop] ?? fullRange(),\n        ip: nextCaptured[res.ip] ?? fullRange(),\n        oopPos: res.oop,\n        ipPos: res.ip,\n      });\n      return;\n    }\n    setHistory(res.nextHistory);\n  };\n\n  // Rewind the line to `position` (an already-acted seat), pruning stale captures.\n  const jumpBack = (position: Position) => {\n    const base = headsUp ? headsUp.closedHistory : history;\n    const tokens = base.split(\"_\");\n    const indices: number[] = [];\n    for (let i = 0; i < tokens.length; i += 2) if (tokens[i] === position) indices.push(i);\n    if (indices.length === 0) return;\n    const targetIdx = indices[indices.length - 1];\n    const newHistory = tokens.slice(0, targetIdx + 1).join(\"_\");\n\n    const { seats, hero } = parseHistory(newHistory, stack);\n    const kept: Partial<Record<Position, RangeWeights>> = {};\n    for (const p of PLAY_ORDER) {\n      if (p === hero) continue;\n      if (captured[p] && seats[p].action && !seats[p].folded) kept[p] = captured[p];\n    }\n    setCaptured(kept);\n    setHeadsUp(null);\n    setError(null);\n    setHistory(newHistory);\n    emit(null);\n  };\n\n  const reset = () => {\n    setHeadsUp(null);\n    setCaptured({});\n    setError(null);\n    setHistory(ROOT_HISTORY);\n    emit(null);\n  };\n\n  // Build the per-seat view. While walking, parseHistory drives it. Once closed,\n  // mark the closing call, fold everyone but the two survivors, and badge OOP/IP.\n  const walk = parseHistory(headsUp ? headsUp.closedHistory : history, stack);\n  const seats = headsUp ? closedSeats(headsUp, walk.seats, stack) : walk.seats;\n  const actor: Position | null = headsUp ? null : walk.hero;\n  const roleOf = (p: Position): RangePlayer | null =>\n    headsUp ? (p === headsUp.oop ? \"oop\" : p === headsUp.ip ? \"ip\" : null) : null;\n\n  const atRoot = history === ROOT_HISTORY && !headsUp;\n\n  return (\n    <div className=\"flex flex-col gap-2\">\n      <div className=\"flex items-center justify-between\">\n        <span className=\"text-xs font-medium text-muted-foreground\">Scenario</span>\n        <div className=\"flex items-center gap-2\">\n          <label className=\"flex items-center gap-1.5 text-[11px] text-muted-foreground\">\n            Stack\n            <select\n              value={stack}\n              onChange={(e) => changeStack(Number(e.target.value))}\n              className=\"h-7 rounded-md border border-input bg-card px-1.5 text-xs text-foreground outline-none focus-visible:border-ring\"\n            >\n              {stacks.map((s) => (\n                <option key={s} value={s}>\n                  {s}bb\n                </option>\n              ))}\n            </select>\n          </label>\n          <button\n            type=\"button\"\n            onClick={reset}\n            disabled={atRoot}\n            className=\"flex items-center gap-1 rounded-md border border-border bg-card px-2 py-1 text-[11px] text-foreground transition-colors hover:bg-accent disabled:opacity-30\"\n          >\n            <Undo2 className=\"size-3\" /> Reset\n          </button>\n        </div>\n      </div>\n\n      <div className=\"flex gap-2 overflow-x-auto pb-1\">\n        {PLAY_ORDER.map((p) => (\n          <SeatCard\n            key={p}\n            seat={seats[p]}\n            isActor={p === actor}\n            actions={p === actor && node?.actor === p ? node?.actions : undefined}\n            role={roleOf(p)}\n            stack={stack}\n            disabled={loading}\n            onSelectAction={advance}\n            onJumpBack={() => jumpBack(p)}\n          />\n        ))}\n        {loading && !headsUp ? (\n          <div className=\"flex min-h-[96px] w-12 shrink-0 items-center justify-center\">\n            <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n          </div>\n        ) : null}\n      </div>\n\n      {error ? <p className=\"text-[11px] text-destructive\">{error}</p> : null}\n\n      {resolved ? (\n        <div className=\"grid grid-cols-2 gap-2\">\n          <RangePreviewTile pos={resolved.oopPos} role=\"oop\" weights={resolved.oop} />\n          <RangePreviewTile pos={resolved.ipPos} role=\"ip\" weights={resolved.ip} />\n        </div>\n      ) : (\n        <p className=\"text-[11px] text-muted-foreground/70\">\n          Walk the preflop tree above until a raise is called — both players&apos; ranges load\n          automatically. Or leave it for full (random) ranges.\n        </p>\n      )}\n    </div>\n  );\n}\n\nfunction SeatCard({\n  seat,\n  isActor,\n  actions,\n  role,\n  stack,\n  disabled,\n  onSelectAction,\n  onJumpBack,\n}: {\n  seat: SeatState;\n  isActor: boolean;\n  actions?: NodeAction[];\n  role: RangePlayer | null;\n  stack: number;\n  disabled?: boolean;\n  onSelectAction: (a: NodeAction) => void;\n  onJumpBack: () => void;\n}) {\n  const highlighted = isActor || !!role;\n  const sorted = actions ? sortActionsForDisplay(actions) : [];\n  const clickable = !isActor && !!seat.action;\n\n  const header = (\n    <>\n      <div className=\"flex items-center justify-between\">\n        <div className=\"flex items-center gap-1.5\">\n          <span\n            className={`text-sm font-semibold tracking-wide ${\n              highlighted ? \"text-foreground\" : seat.folded ? \"text-muted-foreground/50\" : \"text-foreground\"\n            }`}\n          >\n            {seat.position}\n          </span>\n          {seat.isDealer ? (\n            <span className=\"flex size-3.5 items-center justify-center rounded-full bg-foreground text-[8px] font-bold text-background\">\n              D\n            </span>\n          ) : null}\n          {role ? (\n            <span\n              className={`rounded px-1 py-px text-[8px] font-bold tracking-wide ${\n                role === \"oop\"\n                  ? \"bg-foreground text-background\"\n                  : \"border border-foreground/50 text-foreground\"\n              }`}\n            >\n              {role.toUpperCase()}\n            </span>\n          ) : null}\n        </div>\n        <span className={`text-[11px] font-medium ${seat.folded ? \"text-muted-foreground/40\" : \"text-muted-foreground\"}`}>\n          {formatBb(seat.remaining)}\n        </span>\n      </div>\n      {seat.committed > 0 ? (\n        <span className={`text-[10px] ${seat.folded ? \"text-muted-foreground/30\" : \"text-muted-foreground/70\"}`}>\n          in {formatBb(seat.committed)}\n        </span>\n      ) : null}\n    </>\n  );\n\n  const body = isActor ? (\n    <div className=\"flex flex-col\">\n      {sorted.length === 0 ? (\n        <span className=\"py-1 text-xs text-muted-foreground\">—</span>\n      ) : (\n        sorted.map((a) => (\n          <button\n            key={a.action}\n            type=\"button\"\n            disabled={disabled}\n            onClick={() => onSelectAction(a)}\n            className=\"flex items-center justify-between rounded px-1 py-1 text-left text-xs text-foreground transition-colors hover:bg-accent disabled:opacity-40\"\n          >\n            <span className=\"truncate\">{labelForAction(a, stack)}</span>\n            <span className=\"size-2.5 shrink-0 rounded-full border border-muted-foreground/50\" />\n          </button>\n        ))\n      )}\n    </div>\n  ) : (\n    <div className=\"flex flex-1 items-center py-1\">\n      {seat.action ? (\n        <span\n          className={`inline-block max-w-full truncate rounded px-2 py-0.5 text-xs font-semibold ${\n            seat.folded\n              ? \"border border-border text-muted-foreground/60\"\n              : \"bg-accent text-foreground\"\n          }`}\n        >\n          {seat.action}\n        </span>\n      ) : (\n        <span className=\"text-xs text-muted-foreground/60\">—</span>\n      )}\n    </div>\n  );\n\n  const className = `flex min-h-[96px] w-[124px] shrink-0 flex-col gap-1 rounded-xl border p-2 transition-colors ${\n    highlighted ? \"border-foreground/40 bg-accent/40\" : \"border-border bg-card/40\"\n  } ${clickable ? \"cursor-pointer hover:border-foreground/30\" : \"\"}`;\n\n  if (clickable) {\n    return (\n      <button type=\"button\" onClick={onJumpBack} className={`${className} text-left`}>\n        {header}\n        {body}\n      </button>\n    );\n  }\n  return (\n    <div className={className}>\n      {header}\n      {body}\n    </div>\n  );\n}\n\n/** A non-interactive 13×13 thumbnail of a range — cells lit by weight. */\nfunction RangeMini({ weights }: { weights: RangeWeights }) {\n  return (\n    <div className=\"grid size-16 shrink-0 grid-cols-[repeat(13,minmax(0,1fr))] gap-px\">\n      {ALL_HANDS.map((hand) => {\n        const w = weights[hand] ?? 0;\n        return (\n          <div\n            key={hand}\n            className={w > 0 ? \"bg-foreground\" : \"bg-foreground/10\"}\n            style={w > 0 ? { opacity: 0.25 + 0.75 * Math.min(w, 1) } : undefined}\n          />\n        );\n      })}\n    </div>\n  );\n}\n\nfunction RangePreviewTile({\n  pos,\n  role,\n  weights,\n}: {\n  pos: Position;\n  role: RangePlayer;\n  weights: RangeWeights;\n}) {\n  const combos = totalCombos(weights);\n  const pct = (combos / FULL_COMBOS) * 100;\n  return (\n    <div className=\"flex items-center gap-3 rounded-lg border border-border bg-card/40 p-2.5\">\n      <RangeMini weights={weights} />\n      <div className=\"flex flex-col gap-0.5\">\n        <div className=\"flex items-center gap-1.5\">\n          <span className=\"text-sm font-semibold text-foreground\">{pos}</span>\n          <span\n            className={`rounded px-1 py-px text-[8px] font-bold tracking-wide ${\n              role === \"oop\" ? \"bg-foreground text-background\" : \"border border-foreground/50 text-foreground\"\n            }`}\n          >\n            {role.toUpperCase()}\n          </span>\n        </div>\n        <span className=\"text-xs text-muted-foreground tabular-nums\">{combos.toFixed(1)} combos</span>\n        <span className=\"text-xs text-muted-foreground tabular-nums\">{pct.toFixed(1)}%</span>\n      </div>\n    </div>\n  );\n}\n\n/** Project the walking state onto the closed-pot view (mirror of mobile closedSeats). */\nfunction closedSeats(\n  hu: HeadsUp,\n  walkSeats: Record<Position, SeatState>,\n  stack: number,\n): Record<Position, SeatState> {\n  const survivors = new Set<Position>(hu.survivors);\n  const other = hu.survivors.find((p) => p !== hu.closedActor) ?? hu.closedActor;\n  const out = {} as Record<Position, SeatState>;\n  for (const p of PLAY_ORDER) {\n    const s = { ...walkSeats[p], isHero: false };\n    if (p === hu.closedActor) {\n      s.action = \"Call\";\n      s.committed = walkSeats[other].committed;\n      s.remaining = Math.max(0, stack - s.committed);\n    } else if (!survivors.has(p)) {\n      s.folded = true;\n      if (!s.action) s.action = \"Fold\";\n    }\n    out[p] = s;\n  }\n  return out;\n}\n",
      "type": "registry:component",
      "target": "components/solver/scenario-strip.tsx"
    },
    {
      "path": "src/components/solver/strategy-grid.tsx",
      "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport type { SolverActionInfo, SolverHandStrategy } from \"@/lib/solver/types\";\nimport { HandMatrix, type MatrixCell } from \"@/components/pokerstudy/hand-matrix\";\nimport { RANGE_COLORS } from \"@/lib/pokerstudy/poker\";\n\n// Ranks high-to-low; the 13×13 grid is indexed by these. Suited combos sit above\n// the diagonal, offsuit below, pairs on it — the standard hand matrix.\nconst RANKS = [\"A\", \"K\", \"Q\", \"J\", \"T\", \"9\", \"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\"];\n\n// Per-action colors live in the registry core (lib/pokerstudy/poker.ts) so the\n// installable components and the app paint ranges identically (the default\n// Mint palette). Exported so every strategy surface uses this one palette.\nexport const ACTION_COLORS: Record<SolverActionInfo[\"label\"], string> = RANGE_COLORS;\n\n// The 13×13 matrix itself ships as the `hand-matrix` registry item; both the\n// postflop `StrategyGrid` and the Explorer's preflop grid render through it.\nexport { HandMatrix, type MatrixCell };\n\nfunction classOf(combo: string): { row: number; col: number; label: string } | null {\n  if (combo.length !== 4) return null;\n  const r1 = RANKS.indexOf(combo[0].toUpperCase());\n  const r2 = RANKS.indexOf(combo[2].toUpperCase());\n  if (r1 < 0 || r2 < 0) return null;\n  const suited = combo[1].toLowerCase() === combo[3].toLowerCase();\n  if (r1 === r2) {\n    const r = RANKS[r1];\n    return { row: r1, col: r1, label: `${r}${r}` };\n  }\n  const hi = Math.min(r1, r2); // smaller index = higher rank\n  const lo = Math.max(r1, r2);\n  const label = `${RANKS[hi]}${RANKS[lo]}${suited ? \"s\" : \"o\"}`;\n  // Suited above the diagonal (row=hi, col=lo); offsuit below (row=lo, col=hi).\n  return suited ? { row: hi, col: lo, label } : { row: lo, col: hi, label };\n}\n\n/** Below this share of a combo the hand is treated as not in the range. */\nconst REACH_EPS = 1e-9;\n\n/**\n * Aggregate the per-combo strategy into the 13×13 hand matrix, weighted by how\n * often the acting player actually HOLDS each combo here.\n *\n * The weighting is not cosmetic. The engine solves — and dumps — a strategy at\n * every infoset whether or not the line reaches it, so deep in a tree most\n * dumped combos are hands the player can no longer have. Averaging those in\n * unweighted made the grid disagree with the action summary next to it: on a\n * turn node after a check-call, 168 of 329 dumped combos had zero reach and bet\n * 63% between them, painting a wall of red under a \"Bet 1%\" header.\n *\n * `reach` is optional: solve roots (the /solver page, replays) query the full\n * starting range, where every dumped combo is genuinely held and weight 1 is\n * right. Passing it makes a class that is out of the range render as an empty\n * square rather than as a fully-saturated cell.\n */\nexport function buildGrid(\n  actions: SolverActionInfo[],\n  hands: SolverHandStrategy[],\n  reach?: ReadonlyMap<string, number> | null,\n): (MatrixCell | null)[][] {\n  const n = actions.length;\n  const sums = RANKS.map(() =>\n    RANKS.map(() => ({ freqs: new Array<number>(n).fill(0), weight: 0, label: \"\" })),\n  );\n  for (const hand of hands) {\n    const cls = classOf(hand.combo);\n    if (!cls) continue;\n    const w = reach ? (reach.get(hand.combo) ?? 0) : 1;\n    if (w <= REACH_EPS) continue;\n    const slot = sums[cls.row][cls.col];\n    slot.label = cls.label;\n    slot.weight += w;\n    for (let a = 0; a < n; a++) slot.freqs[a] += w * (hand.freqs[a] ?? 0);\n  }\n  return sums.map((rowArr) =>\n    rowArr.map((slot) =>\n      slot.weight <= REACH_EPS\n        ? null\n        : { label: slot.label, freqs: slot.freqs.map((f) => f / slot.weight) },\n    ),\n  );\n}\n\nexport function StrategyGrid({\n  actions,\n  hands,\n  reach,\n}: {\n  actions: SolverActionInfo[];\n  hands: SolverHandStrategy[];\n  /** Per-combo reach at this node. Omit at a solve root, where the dumped\n   *  combos ARE the range; pass it anywhere the line has narrowed the range,\n   *  so the grid agrees with the reach-weighted action summary. */\n  reach?: ReadonlyMap<string, number> | null;\n}) {\n  const cells = useMemo(() => buildGrid(actions, hands, reach).flat(), [actions, hands, reach]);\n  const colors = useMemo(() => actions.map((a) => ACTION_COLORS[a.label]), [actions]);\n  const legend = useMemo(\n    () =>\n      actions.map((action) => ({\n        // add is a raw engine amount — round for display (\"Bet 3.97\", not\n        // \"Bet 3.9749999999999996\").\n        label: `${action.label}${action.add > 0 ? ` ${Math.round(action.add * 100) / 100}` : \"\"}`,\n        color: ACTION_COLORS[action.label],\n      })),\n    [actions],\n  );\n\n  const foldIndex = actions.findIndex((a) => a.label === \"Fold\");\n  return (\n    <HandMatrix\n      cells={cells}\n      colors={colors}\n      legend={legend}\n      foldIndex={foldIndex < 0 ? undefined : foldIndex}\n      aggressiveFirst\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/solver/strategy-grid.tsx"
    },
    {
      "path": "src/lib/access/grant-scope.ts",
      "content": "import { DATA_ACCESS, type Dataset, type Plan } from \"@/lib/access/policy\";\n\n/**\n * The crypto-free half of the ranges grant: the header name, the payload\n * shape, and what a scope allows. The trainer client imports this; signing\n * and verifying stay in `grant.ts`, which needs `node:crypto` and so can\n * only be bundled for the server.\n */\n\nexport const GRANT_HEADER = \"x-ranges-grant\";\n\nexport type StackGrant = \"all\" | number[];\nexport type RangesScope = Partial<Record<Dataset, StackGrant>>;\n\nexport type GrantPayload = {\n  v: 1;\n  plan: Plan;\n  /** Unix seconds. */\n  exp: number;\n};\n\nexport function scopeForPlan(plan: Plan): RangesScope {\n  const scope: RangesScope = {};\n  for (const dataset of Object.keys(DATA_ACCESS) as Dataset[]) {\n    const grant = DATA_ACCESS[dataset].plans[plan];\n    if (!grant) continue;\n    scope[dataset] = grant === \"all\" ? \"all\" : [...grant.stacks];\n  }\n  return scope;\n}\n\nexport function scopeAllows(scope: RangesScope | null | undefined, dataset: Dataset, stack: number): boolean {\n  if (!scope) return false;\n  const grant = scope[dataset];\n  if (grant === \"all\") return true;\n  return Array.isArray(grant) && grant.includes(stack);\n}\n",
      "type": "registry:lib",
      "target": "lib/access/grant-scope.ts"
    },
    {
      "path": "src/lib/access/plan-required.ts",
      "content": "import { toast } from \"sonner\";\n\nimport { currentRangesPlan, forgetRangesSession } from \"@/lib/access/session-client\";\nimport { explorerHost } from \"@/lib/explorer/host\";\n\n/**\n * Client side of the data gate ([gate.ts]): when a ranges call comes back\n * 401/403, tell the user why once, with a way forward, instead of letting the\n * surface show a raw HTTP error.\n *\n * Both prompts are once per browser session (sessionStorage, falling back to\n * once per page): a hand of a paid game fetches a node at every decision, and\n * a toast at each one is noise, not information. The upgrade prompt never\n * shows to a player whose session grant already says Pro, Studio or trial: a\n * 403 there means a stale grant, so it is dropped and re-read instead. A\n * no-op on the server.\n */\n\nconst SEEN_KEY = \"pokerstudy.plan-prompt.v1\";\nconst TOAST_ID = \"plan-required\";\nconst PAID_PLANS = new Set([\"trial\", \"pro\", \"studio\"]);\n\n/** Prompts already shown on this page (the fallback when storage is blocked). */\nconst shownThisPage = new Set<\"sign-in\" | \"upgrade\">();\n/**\n * Clerk's signed-in bit from the page that mounted the trainer. `null` means\n * Clerk hasn't reported yet. A 401 is a sign-in prompt only when this is\n * explicitly false — a signed-in player with a stale cookie must not see it.\n */\nlet clerkSignedIn: boolean | null = null;\n\n/** Set from the play / trainer shell as soon as `useAuth()` has loaded. */\nexport function setPlanPromptAuth(signedIn: boolean | null): void {\n  clerkSignedIn = signedIn;\n}\n\nexport function resetPlanPromptForTests(): void {\n  clerkSignedIn = null;\n  shownThisPage.clear();\n}\n\nfunction seenThisSession(kind: \"sign-in\" | \"upgrade\"): boolean {\n  if (shownThisPage.has(kind)) return true;\n  try {\n    return window.sessionStorage?.getItem(`${SEEN_KEY}:${kind}`) === \"1\";\n  } catch {\n    return false;\n  }\n}\n\nfunction markSeen(kind: \"sign-in\" | \"upgrade\"): void {\n  shownThisPage.add(kind);\n  try {\n    window.sessionStorage?.setItem(`${SEEN_KEY}:${kind}`, \"1\");\n  } catch {\n    // Private mode / blocked storage: once per page still holds.\n  }\n}\n\n/** Call with any ranges response status; only 401/403 do anything. */\nexport function notifyPlanRequired(status: number): void {\n  if (status !== 401 && status !== 403) return;\n  if (typeof window === \"undefined\") return;\n  if (status === 401 && clerkSignedIn !== false) return;\n  const kind = status === 401 ? \"sign-in\" : \"upgrade\";\n  if (kind === \"upgrade\") {\n    const plan = currentRangesPlan();\n    if (plan && PAID_PLANS.has(plan)) {\n      // A paid grant was refused: it is stale (or the plan just changed).\n      // Re-read the plan on the next fetch rather than asking a paying\n      // player to upgrade.\n      forgetRangesSession();\n      return;\n    }\n  }\n  if (seenThisSession(kind)) return;\n  markSeen(kind);\n  const signIn = kind === \"sign-in\";\n  // A host with its own plans (pokerdata.io) words the prompt itself.\n  const custom = explorerHost().planPrompt?.[kind];\n  if (custom) {\n    toast(custom.title, {\n      id: TOAST_ID,\n      closeButton: true,\n      description: custom.description,\n      action: {\n        label: custom.label,\n        onClick: () => {\n          window.location.href = custom.href(window.location.pathname + window.location.search);\n        },\n      },\n    });\n    return;\n  }\n  toast(signIn ? \"Sign in to study this spot\" : \"This spot is part of Pro and Studio\", {\n    id: TOAST_ID,\n    closeButton: true,\n    description: signIn\n      ? \"6-max NL is free for everyone. Other games are part of Pro and Studio.\"\n      : \"6-max NL is free for everyone. Upgrade for every other game.\",\n    action: {\n      label: signIn ? \"Sign in\" : \"See plans\",\n      onClick: () => {\n        window.location.href = signIn\n          ? `/sign-in?redirect_url=${encodeURIComponent(window.location.pathname)}`\n          : \"/pricing\";\n      },\n    },\n  });\n}\n",
      "type": "registry:lib",
      "target": "lib/access/plan-required.ts"
    },
    {
      "path": "src/lib/access/policy.ts",
      "content": "/**\n * THE access table for solver data: which plan (or API key) may read which\n * dataset. Every data route checks it through `requireDataAccess`\n * ([gate.ts]), so changing who gets what is an edit to `DATA_ACCESS` below\n * and nothing else.\n *\n * Pure (no DB, no Clerk) so it can be unit-tested and read at a glance.\n */\n\n/**\n * Who is asking, by plan. `guest` is no account at all; `trial` is a free\n * account inside a code-redemption trial window (see lib/subscription).\n */\nexport type Plan = \"guest\" | \"free\" | \"trial\" | \"pro\" | \"studio\";\n\n/**\n * How the caller proved who they are. `api-key` is a Studio `psk_…` token\n * (the programmatic / MCP path); `internal` is pokerdata.io's server proxy,\n * which enforces its own subscription before calling us.\n */\nexport type Credential = \"none\" | \"session\" | \"api-key\" | \"internal\";\n\n/** The datasets behind `/api/ranges/<dataset>/*`. */\nexport type Dataset =\n  | \"nl\"\n  | \"nl9\"\n  | \"nlmtt8\"\n  | \"nlh8-hydra\"\n  | \"nlh8-icm\"\n  | \"nlhu\"\n  | \"plo\"\n  | \"plo4hu\"\n  | \"plo5\"\n  | \"plo6hu\"\n  | \"plo9\";\n\n/** What a plan may read of a dataset: all of it, or only some stack depths. */\nexport type Grant = \"all\" | { stacks: readonly number[] };\n\nexport type DataRule = {\n  /** Per-plan grant. A plan that isn't listed gets nothing. */\n  plans: Partial<Record<Plan, Grant>>;\n  /** Whether a Studio API key (`psk_…`) may read this dataset. */\n  apiKey: boolean;\n};\n\nconst PAID: Partial<Record<Plan, Grant>> = { trial: \"all\", pro: \"all\", studio: \"all\" };\n\nexport const DATA_ACCESS: Record<Dataset, DataRule> = {\n  // 6-max NL is open to everyone, guests included, at every stack, so Train\n  // and Play work with no account: the App Store requires that (5.1.1(v),\n  // see #493), and app builds from before this gate send no credential at\n  // all. The other games are paid.\n  nl: { plans: { ...PAID, free: \"all\", guest: \"all\" }, apiKey: true },\n  nl9: { plans: PAID, apiKey: true },\n  nlmtt8: { plans: PAID, apiKey: true },\n  \"nlh8-hydra\": { plans: PAID, apiKey: true },\n  \"nlh8-icm\": { plans: PAID, apiKey: true },\n  nlhu: { plans: PAID, apiKey: true },\n  plo: { plans: PAID, apiKey: true },\n  plo4hu: { plans: PAID, apiKey: true },\n  plo5: { plans: PAID, apiKey: true },\n  plo6hu: { plans: PAID, apiKey: true },\n  plo9: { plans: PAID, apiKey: true },\n};\n\nexport type AccessVerdict =\n  | { ok: true }\n  | { ok: false; reason: \"sign-in\" | \"upgrade\" };\n\n/**\n * May this caller read `dataset` at `stack`? Discovery (the manifest roots,\n * which only list stacks and endpoints) is not checked here; callers gate the\n * data endpoints only.\n */\nexport function checkDataAccess(\n  dataset: Dataset,\n  caller: { plan: Plan; credential: Credential },\n  stack: number,\n): AccessVerdict {\n  if (caller.credential === \"internal\") return { ok: true };\n  const rule = DATA_ACCESS[dataset];\n  if (caller.credential === \"api-key\" && !rule.apiKey) {\n    return { ok: false, reason: \"upgrade\" };\n  }\n  const grant = rule.plans[caller.plan];\n  if (grant === \"all\") return { ok: true };\n  if (grant && grant.stacks.includes(stack)) return { ok: true };\n  return { ok: false, reason: caller.plan === \"guest\" ? \"sign-in\" : \"upgrade\" };\n}\n",
      "type": "registry:lib",
      "target": "lib/access/policy.ts"
    },
    {
      "path": "src/lib/access/session-client.ts",
      "content": "import { explorerHost } from \"@/lib/explorer/host\";\nimport type { Dataset } from \"@/lib/access/policy\";\nimport { trainerToken } from \"@/lib/trainer/auth\";\nimport {\n  scopeAllows as scopeGrants,\n  type GrantPayload,\n  type RangesScope,\n} from \"@/lib/access/grant-scope\";\n\n/**\n * The trainer's one entitlement read. `/api/ranges/session` returns the plan,\n * the stacks it may open, and a signed grant. Node fetches reuse that grant\n * until it expires — they do not call this again.\n */\n\nexport type RangesSession = {\n  plan: GrantPayload[\"plan\"];\n  exp: number;\n  token: string;\n  scope: RangesScope;\n};\n\nlet clerkSignedIn: boolean | null = null;\nlet current: RangesSession | null = null;\nlet pending: Promise<RangesSession | null> | null = null;\n\nexport function rangesClerkSignedIn(): boolean | null {\n  return clerkSignedIn;\n}\n\n/** Called from the play / trainer shells as soon as Clerk has loaded. */\nexport function setRangesClerkSignedIn(signedIn: boolean | null): void {\n  clerkSignedIn = signedIn;\n  if (signedIn === false) {\n    current = null;\n    pending = null;\n  }\n}\n\nexport function peekGrantToken(): string | null {\n  if (!current || current.exp * 1000 <= Date.now() + 5_000) return null;\n  return current.token;\n}\n\n/** The plan of the current, unexpired session grant, or null when there is none. */\nexport function currentRangesPlan(): GrantPayload[\"plan\"] | null {\n  if (!current || current.exp * 1000 <= Date.now()) return null;\n  return current.plan;\n}\n\n/** Drop the cached grant so the next node fetch re-reads the plan. */\nexport function forgetRangesSession(): void {\n  current = null;\n}\n\nexport function scopeAllows(dataset: Dataset, stack: number): boolean {\n  if (!current || current.exp * 1000 <= Date.now()) return false;\n  return scopeGrants(current.scope, dataset, stack);\n}\n\nexport function rememberRangesSession(session: RangesSession | null): void {\n  current = session;\n  pending = null;\n}\n\nexport function resetRangesSessionForTests(): void {\n  clerkSignedIn = null;\n  current = null;\n  pending = null;\n}\n\n/**\n * One in-flight session read, shared by every caller. A fresh grant is\n * returned without touching the network.\n */\nexport function ensureRangesSession(): Promise<RangesSession | null> {\n  if (clerkSignedIn === false) return Promise.resolve(null);\n  if (current && current.exp * 1000 > Date.now() + 60_000) return Promise.resolve(current);\n  if (pending) return pending;\n  pending = loadSession().finally(() => {\n    pending = null;\n  });\n  return pending;\n}\n\nasync function loadSession(): Promise<RangesSession | null> {\n  // A host that gates its ranges feed itself has no session to read.\n  const sessionUrl = explorerHost().rangesSession;\n  if (!sessionUrl) return null;\n  try {\n    const headers: Record<string, string> = { Accept: \"application/json\" };\n    const token = await trainerToken().catch(() => null);\n    if (token) headers.Authorization = `Bearer ${token}`;\n    const res = await fetch(sessionUrl, { headers, credentials: \"same-origin\" });\n    if (!res.ok) return null;\n    const body = (await res.json()) as Partial<RangesSession>;\n    if (!body || typeof body.token !== \"string\" || typeof body.exp !== \"number\" || !body.scope) {\n      return null;\n    }\n    current = {\n      plan: body.plan ?? \"free\",\n      exp: body.exp,\n      token: body.token,\n      scope: body.scope,\n    };\n    return current;\n  } catch {\n    return null;\n  }\n}\n",
      "type": "registry:lib",
      "target": "lib/access/session-client.ts"
    },
    {
      "path": "src/lib/explorer/bet-size.ts",
      "content": "/**\n * Bet and raise sizes as a percentage of the pot, GTO Wizard's convention:\n *\n * - a bet is its chips over the pot before it: 3 into 6 is \"Bet 50%\";\n * - a raise is the chips beyond the call over the pot after the call, so a\n *   pot-size raise is \"Raise 100%\" (the pot-limit maximum).\n *\n * The NL preflop tokens (\"60%\", \"76%\") and MonkerSolver's PLO size codes\n * already use this convention; this module covers the PLO depth tags and the\n * engine's postflop chip labels, which carry an amount instead.\n */\n\n/** MonkerSolver PLO raise tokens: a depth tag, optionally size-coded (\"Open-40075\"). */\nconst PLO_RAISE_RE = /^(Open|3B|4B|5B|6B|7B|8B)(?:-(\\d+))?$/;\n\n/**\n * Pot percentage of a MonkerSolver PLO raise token, or null when the token\n * isn't one or its size code isn't a pot fraction. A bare depth tag is a pot\n * raise (100%); size code 40000 + n is n% pot.\n */\nexport function ploRaisePotPct(token: string): number | null {\n  const m = token.match(PLO_RAISE_RE);\n  if (!m) return null;\n  if (m[2] === undefined) return 100;\n  const code = Number(m[2]);\n  return code > 40000 ? code - 40000 : null;\n}\n\n/** \"Bet 3\" → { kind: \"Bet\", amount: 3 }; labels without an amount give amount 0. */\nfunction parseChipLabel(label: string): { kind: string; amount: number } {\n  const [kind, amt] = label.split(\" \");\n  const amount = amt === undefined ? 0 : Number(amt);\n  return { kind, amount: Number.isFinite(amount) ? amount : 0 };\n}\n\n/**\n * Pot percentage of a postflop bet or raise, from the street's starting pot and\n * the actions before it on the street. Labels are the engine's (\"Check\",\n * \"Bet 3\", \"Call 3\", \"Raise 12.4\", \"AllIn 97\"): the amount is the chips that\n * action puts in. Players alternate, so the walk needs no seat. Null for\n * anything that isn't a sized Bet or Raise.\n */\nexport function streetBetPotPct(streetPot: number, prior: string[], label: string): number | null {\n  const { kind, amount } = parseChipLabel(label);\n  if ((kind !== \"Bet\" && kind !== \"Raise\") || amount <= 0) return null;\n  const put = [0, 0];\n  prior.forEach((l, i) => {\n    put[i % 2] += parseChipLabel(l).amount;\n  });\n  const me = prior.length % 2;\n  const toCall = Math.max(0, put[1 - me] - put[me]);\n  const pot = streetPot + put[0] + put[1];\n  const raise = amount - toCall;\n  const base = pot + toCall;\n  if (base <= 0 || raise <= 0) return null;\n  return Math.round((raise / base) * 100);\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/bet-size.ts"
    },
    {
      "path": "src/lib/explorer/custom-solve.ts",
      "content": "// Custom postflop solve requests (#231): the one place that decides what a\n// product-quality Explorer solve looks like. The builder UI, the offline\n// sample-fixture generator (scripts/build-sample-solutions.ts), and the tests\n// all build their engine configs through `buildPostflopSolveRequest`, so a\n// user-built flop solution and the canonical fixtures share the same shape:\n// dump_nodes + dump_ev, one chance deal of dumped depth, and the #220 river\n// action abstraction that keeps a flop tree solvable in ~10-15 minutes.\n//\n// Client-safe: no server imports. The localStorage pending-solve record lives\n// here too, because a flop solve outlives most tabs — the worker keeps jobs\n// server-side, so the builder can resume by job id after a reload.\n\nimport type { SolveRequest, TreeSizingConfig } from \"@/lib/solver/types\";\n\n/** Defaults matching the sample fixtures' product-quality profile. */\nexport const CUSTOM_SOLVE_DEFAULTS = {\n  /** Pot-fraction bet sizes on flop + turn. */\n  betSizes: [0.75],\n  addAllin: true,\n  /** 2, like the sample fixtures — NOT 3: with a single sizing + all-in, one\n   *  extra raise level multiplies the dumped flop tree past Node's ~512MB\n   *  string cap (measured live), which no client can read back. */\n  maxAggressions: 2,\n  /** Coarser river-only abstraction (#220) — keeps flop trees tractable. */\n  riverBetSizes: [0.75],\n  riverMaxAggressions: 2,\n  /** Ceiling only — the exploitability target or the convergence plateau\n   *  stops the solve in practice. */\n  iterations: 2500,\n  /** Stop at 1% of pot — study grade. Range charts are visually identical to\n   *  a 0.5% solve well before 1%, and deep spots decay ~1/iterations, so the\n   *  old 0.5% default routinely ground to the iteration cap for precision\n   *  nobody could see. Users who want 0.5% can type it. */\n  targetExploitability: 1.0,\n  /** Convergence-plateau early stop (#243 step 1, engine-side): end the solve\n   *  once a progress chunk improves exploitability by less than this relative\n   *  fraction (with the engine's built-in warmup + patience), i.e. when it has\n   *  effectively converged — even if the typed target is unreachable for the\n   *  spot. This is what keeps deep 100bb solves from running the full cap. */\n  convergencePlateau: 0.04,\n  /** Iterations for a depth-limited \"AI solve\" (no exploitability target —\n   *  the net-leaf tree converges on iteration budget alone). */\n  aiIterations: 1000,\n} as const;\n\nexport interface PostflopSolveSpec {\n  /** Board cards, space-separated: 3 (flop), 4 (turn), or 5 (river). */\n  board: string;\n  /** Pot at the start street, bb. */\n  potBb: number;\n  /** Chips behind each player, bb. */\n  effStackBb: number;\n  /** Engine range strings (169-grid classes or explicit combos). */\n  oopRange: string;\n  ipRange: string;\n  betSizes: number[];\n  addAllin: boolean;\n  maxAggressions: number;\n  /** Omit / empty to use `betSizes` on the river too. */\n  riverBetSizes?: number[];\n  riverMaxAggressions?: number;\n  /** Per-street, per-player tree overrides (GTO-Wizard-style tree editor).\n   *  Unset cells inherit the flat fields above. Omit for the legacy tree. */\n  sizing?: TreeSizingConfig;\n  iterations: number;\n  targetExploitability?: number;\n  /** Relative per-chunk improvement below which the solve is considered\n   *  converged (engine convergence_plateau). Omit to disable. */\n  convergencePlateau?: number;\n  /** Iterations between progress ticks (default 10). */\n  logInterval?: number;\n  /** Dumped chance-deal depth (default 1 — the fixture shape: a flop start\n   *  dumps every turn subtree, rivers come from the viewer's on-demand\n   *  solves; a turn start dumps every river subtree). */\n  dumpMaxDeals?: number;\n  /** Emit per-action EV on every dumped node — what turns a graded\n   *  mistake into a bb figure instead of a bare tier. Off by default: it\n   *  roughly doubles the dump's numeric payload, and a flop tree already sits\n   *  close to the reader-side size ceiling `maxAggressions` guards. */\n  dumpActionEvs?: boolean;\n  /** Depth-limited \"AI solve\" (flop only): the tree ends in value-net leaves\n   *  at the turn boundary, so the dump carries flop-street nodes only and\n   *  every turn card resolves via the viewer's on-demand exact child solves. */\n  aiSolve?: boolean;\n}\n\n/** The exact engine request for a custom postflop solution. */\nexport function buildPostflopSolveRequest(spec: PostflopSolveSpec): SolveRequest {\n  const req: SolveRequest = {\n    variant: \"nlhe\",\n    limit: \"nolimit\",\n    board: spec.board.trim(),\n    pot: spec.potBb,\n    effective_stack: spec.effStackBb,\n    bet_sizes: spec.betSizes,\n    add_allin: spec.addAllin,\n    max_aggressions: spec.maxAggressions,\n    iterations: spec.iterations,\n    target_exploitability: spec.targetExploitability,\n    // Each progress report costs a full best-response evaluation, which is\n    // single-threaded in the engine — at 10 it can dominate deep-tree solve\n    // wall-clock (measured on a 96-core box: long serial plateaus between\n    // parallel CFR bursts). 50 keeps the progress line and the early-stop\n    // check alive at a fifth of the tax.\n    log_interval: spec.logInterval ?? 50,\n    dump_ev: true,\n    dump_nodes: true,\n    dump_max_deals: spec.dumpMaxDeals ?? 1,\n    ...(spec.dumpActionEvs ? { dump_action_evs: true } : {}),\n    oop_range: spec.oopRange,\n    ip_range: spec.ipRange,\n  };\n  if (spec.convergencePlateau !== undefined) {\n    req.convergence_plateau = spec.convergencePlateau;\n  }\n  // Exact solves use PCFR+ (#253): ~1.9× fewer iterations to the same\n  // exploitability, verified on the convergence battery + prod spot. The\n  // depth-limited AI path stays on the engine default.\n  if (!spec.aiSolve) {\n    req.cfr_variant = \"pcfr+\";\n    // Always keep the snapshot (#262): it costs the worker a bounded LRU\n    // slot and makes the next same-geometry re-solve warm (seconds, not\n    // minutes). The AI path can't snapshot (net state isn't fingerprinted).\n    req.keep_snapshot = true;\n    // Emit the CFR-D carry for OOP (#233): the opponent-CFV promises that\n    // seed *safe* on-demand subgame re-solves in the viewer (resolve-carry.ts)\n    // instead of the unsafe reach-range bootstrap. Costs one EV walk at the\n    // root; exact solves only (a net-leaf tree would price promises off the\n    // net, unvalidated).\n    req.emit_carry_for = 0;\n  }\n  if (spec.riverBetSizes && spec.riverBetSizes.length > 0) {\n    req.river_bet_sizes = spec.riverBetSizes;\n  }\n  if (spec.riverMaxAggressions !== undefined) {\n    req.river_max_aggressions = spec.riverMaxAggressions;\n  }\n  if (spec.sizing && Object.keys(spec.sizing).length > 0) {\n    req.sizing = spec.sizing;\n  }\n  if (spec.aiSolve) req.aiSolve = true;\n  return req;\n}\n\n/** True when two requests describe the SAME solve geometry — board, tree\n *  shape, and ranges — so a warm start (#262) is valid between them. Only\n *  convergence knobs (iterations, target, plateau, log cadence) may differ;\n *  anything else changes the engine's snapshot fingerprint and would be\n *  rejected server-side, so the client never sends warm_start_from for it. */\nexport function sameSolveGeometry(a: SolveRequest, b: SolveRequest): boolean {\n  const eq = (x: unknown, y: unknown) => JSON.stringify(x ?? null) === JSON.stringify(y ?? null);\n  return (\n    a.board === b.board &&\n    a.pot === b.pot &&\n    a.effective_stack === b.effective_stack &&\n    eq(a.bet_sizes, b.bet_sizes) &&\n    a.add_allin === b.add_allin &&\n    a.max_aggressions === b.max_aggressions &&\n    eq(a.river_bet_sizes, b.river_bet_sizes) &&\n    a.river_max_aggressions === b.river_max_aggressions &&\n    eq(a.sizing, b.sizing) &&\n    a.oop_range === b.oop_range &&\n    a.ip_range === b.ip_range &&\n    a.variant === b.variant &&\n    a.limit === b.limit &&\n    !a.aiSolve === !b.aiSolve\n  );\n}\n\n/** A human ETA hint for the solve, by start street (and solve kind). */\nexport function solveEtaHint(boardCardCount: number, ai = false): string {\n  if (ai) return \"AI flop solves take seconds–minutes (beta)\";\n  if (boardCardCount <= 3) return \"flop solves typically take 1–2 minutes\";\n  if (boardCardCount === 4) return \"turn solves typically take 1–2 minutes\";\n  return \"river solves typically take 1–2 minutes\";\n}\n\n/**\n * Friendlier copy for solve-submission failures. The worker queues excess\n * jobs rather than rejecting them, so \"busy\" errors are rare — but a proxy or\n * future limiter may still 429/503, and an unreachable worker 502s.\n */\nexport function describeSolveError(message: string): string {\n  const m = message.toLowerCase();\n  if (m.includes(\"unreachable\") || m.includes(\"not configured\")) {\n    return \"The solver service is offline right now, so custom solves can't run. Please try again in a few minutes.\";\n  }\n  if (m.includes(\"429\") || m.includes(\"too many\") || m.includes(\"busy\") || m.includes(\"slot\")) {\n    return \"The solver is busy with other solves right now — your job will queue; retry in a moment if it doesn't start.\";\n  }\n  return message;\n}\n\n// ---------------------------------------------------------------------------\n// Pending-solve record — resume a long solve after a tab reload.\n//\n// The worker (`solve serve`) keeps every job in memory until the process\n// restarts, and `/api/solver/jobs/:id` polls it statelessly, so the browser\n// only needs to remember the job id + the request it posted. One slot is\n// enough: the worker runs 2 concurrent solves and the builder starts one at a\n// time.\n// ---------------------------------------------------------------------------\n\nconst PENDING_KEY = \"explorer.pendingSolve.v1\";\n\nexport interface PendingSolve {\n  jobId: string;\n  request: SolveRequest;\n  /** Epoch ms when the job was accepted. */\n  startedAt: number;\n  /** Seat labels for the eventual save meta. */\n  oopLabel: string;\n  ipLabel: string;\n  /** Suggested title (\"BB vs BTN · Ad 7c 2s\"). */\n  title: string;\n  /** True when this is a depth-limited AI solve (affects the resume copy). */\n  ai?: boolean;\n}\n\nexport function readPendingSolve(): PendingSolve | null {\n  try {\n    const raw = window.localStorage.getItem(PENDING_KEY);\n    if (!raw) return null;\n    const p = JSON.parse(raw) as PendingSolve;\n    if (!p || typeof p.jobId !== \"string\" || !p.request) return null;\n    return p;\n  } catch {\n    return null;\n  }\n}\n\nexport function writePendingSolve(p: PendingSolve): void {\n  try {\n    window.localStorage.setItem(PENDING_KEY, JSON.stringify(p));\n  } catch {\n    /* storage full / private mode — resume is best-effort */\n  }\n}\n\nexport function clearPendingSolve(): void {\n  try {\n    window.localStorage.removeItem(PENDING_KEY);\n  } catch {\n    /* ignore */\n  }\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/custom-solve.ts"
    },
    {
      "path": "src/lib/explorer/host.ts",
      "content": "/**\n * Where the shared Explorer (`explorer-app`) reads and writes, and which of its\n * pokerstudy.ai-only features are on. The defaults are pokerstudy.ai's own\n * same-origin routes; another host (pokerdata.io's /app/explorer) calls\n * `setExplorerHost` once, before the Explorer mounts, to point the reads at its\n * own proxies and switch off what it doesn't serve.\n *\n * A feed keeps the same contract wherever it is served: the `/api/ranges/*`\n * layout (`/nl/v2/node?…`, `/plo5/node?…`), a 401/403 that the plan prompt\n * explains, and a 404 on a node meaning the betting round closed there.\n */\nexport interface ExplorerHost {\n  /** Ranges feed root, the `/api/ranges/*` layout. */\n  ranges: string;\n  /**\n   * The ranges session (`<ranges>/session`): which plan the visitor's reads\n   * run under. Null when the host gates its feed itself (its proxy asserts\n   * the plan), so the Explorer never asks.\n   */\n  rangesSession: string | null;\n  /**\n   * Custom postflop solves: the solver job routes (`/jobs`, `/jobs/:id`, …).\n   * Null switches the inline flop solve off; a heads-up line then ends on the\n   * end card, with `solveElsewhere` as its next step.\n   */\n  solver: string | null;\n  /** Saving a custom solve (`POST`, `PATCH /:id`). Null hides Save. */\n  solutions: string | null;\n  /** Heads-up PLO4 blueprint flop + turn/river re-solves. Null switches them off. */\n  plo4huPostflop: string | null;\n  /**\n   * The download link for a pack in the solution picker, or null for none\n   * (the picker then shows `packHref` instead, when the host gives one).\n   */\n  downloadHref: ((packId: string) => string) | null;\n  /** The host's page for a pack (to buy it), shown when there's no download. */\n  packHref: ((packId: string) => string | null) | null;\n  /** Where a closed heads-up line points when this host can't solve postflop. */\n  solveElsewhere: { href: string; label: string } | null;\n  /**\n   * The toast a refused ranges read (401 sign-in / 403 upgrade) shows. Null\n   * keeps pokerstudy.ai's plan copy. `href` may be a function of the page path.\n   */\n  planPrompt: Record<\"sign-in\" | \"upgrade\", PlanPromptCopy> | null;\n}\n\nexport interface PlanPromptCopy {\n  title: string;\n  description: string;\n  label: string;\n  href: (path: string) => string;\n}\n\nconst POKERSTUDY: ExplorerHost = {\n  ranges: \"/api/ranges\",\n  rangesSession: \"/api/ranges/session\",\n  solver: \"/api/solver\",\n  solutions: \"/api/explorer/solutions\",\n  plo4huPostflop: \"/api/explorer/plo4hu-postflop\",\n  downloadHref: (packId) => `/api/downloads/${encodeURIComponent(packId)}`,\n  packHref: null,\n  solveElsewhere: null,\n  planPrompt: null,\n};\n\nlet current: ExplorerHost = POKERSTUDY;\n\nexport function explorerHost(): ExplorerHost {\n  return current;\n}\n\nexport function setExplorerHost(next: Partial<ExplorerHost>): void {\n  current = { ...current, ...next };\n}\n\n/** `<ranges>/<path>` — `rangesUrl(\"nl/v2/node?…\")`. */\nexport function rangesUrl(path: string): string {\n  return `${current.ranges}/${path.replace(/^\\//, \"\")}`;\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/host.ts"
    },
    {
      "path": "src/lib/explorer/locks.ts",
      "content": "// Node-lock request construction (#268, P2 — the explorer UI half of node\n// locking). The viewer collects strategy edits (\"lock this node to these\n// action frequencies\"), and this module turns them into the engine's\n// `locked_nodes` entries plus the full \"re-solve with edits\" request.\n//\n// The one rule that matters (PR #269's key finding): a locked re-solve must\n// ALWAYS warm-start from the unlocked base solve's snapshot. A lock that\n// zeroes an action gives the subtree behind it zero counterfactual reach, so\n// a cold locked solve can never train the opponent's response there — it\n// stays uniform forever and the result is silently wrong. So\n// `buildLockedResolveRequest` requires a base job id; callers with no base\n// snapshot must surface an error, never fall back to a cold locked solve.\n//\n// Client-safe: pure functions, no server imports.\n\nimport type { LockedNode, SolveRequest, SolverNode } from \"@/lib/solver/types\";\n\n/**\n * Hard cap on locks per solve. Shared with the jobs-proxy sanitizer so the\n * client never builds a request the server would reject, and the worker never\n * sees an unbounded array.\n */\nexport const MAX_LOCKED_NODES = 16;\n\n/** Default convergence plateau for locked re-solves (see\n *  `buildLockedResolveRequest`) — matches CUSTOM_SOLVE_DEFAULTS. */\nconst LOCKED_SOLVE_PLATEAU = 0.04;\n\n/**\n * Normalize a raw frequency vector for a lock: clamp negatives to 0, scale to\n * sum 1, and round to 4 decimals (with the residual folded into the largest\n * entry so the sum stays at 1 up to float epsilon — the engine accepts ±0.001\n * but there's no reason to spend the tolerance). Returns null when the vector\n * is degenerate (empty, all zero, or non-finite).\n */\nexport function normalizeLockFreqs(raw: readonly number[]): number[] | null {\n  if (raw.length === 0) return null;\n  const clamped = raw.map((f) => (Number.isFinite(f) && f > 0 ? f : 0));\n  const sum = clamped.reduce((a, b) => a + b, 0);\n  if (sum <= 0) return null;\n  const out = clamped.map((f) => Math.round((f / sum) * 10000) / 10000);\n  // Fold the rounding residual into the largest entry.\n  const residual = 1 - out.reduce((a, b) => a + b, 0);\n  if (residual !== 0) {\n    let maxIdx = 0;\n    for (let i = 1; i < out.length; i++) if (out[i] > out[maxIdx]) maxIdx = i;\n    out[maxIdx] = Math.round((out[maxIdx] + residual) * 10000) / 10000;\n  }\n  return out;\n}\n\n/**\n * Build an aggregate (`all_hands`) lock for the node at `path`: every combo of\n * the acting player's range plays `freqs` verbatim. `freqs` is raw slider\n * weight — normalized here. Throws on a shape mismatch or a degenerate vector,\n * so the editor can't emit a lock the engine would reject.\n */\nexport function buildAggregateLock(\n  path: readonly string[],\n  node: Pick<SolverNode, \"actions\">,\n  freqs: readonly number[],\n): LockedNode {\n  if (freqs.length !== node.actions.length) {\n    throw new Error(\n      `lock vector has ${freqs.length} frequencies but the node has ${node.actions.length} actions`,\n    );\n  }\n  const normalized = normalizeLockFreqs(freqs);\n  if (!normalized) {\n    throw new Error(\"lock frequencies must include at least one positive value\");\n  }\n  return { path: [...path], all_hands: normalized };\n}\n\n/**\n * The full \"re-solve with edits\" request (#268): the base solve's exact config\n * with `locked_nodes` attached and `warm_start_from` pointing at the base\n * job's snapshot. Throws rather than building a request that would be wrong or\n * rejected:\n *   • no locks / too many locks;\n *   • an AI (depth-limited) base — those never snapshot, so the required warm\n *     start can't exist.\n *\n * Two deliberate knob changes vs the base:\n *   • `keep_snapshot: false` — a locked solve's own snapshot fingerprints\n *     iso=0 (#269 caveat) and must never become a later warm-start base; the\n *     unlocked base job stays the one warm-start source.\n *   • a convergence plateau is always set — the composed exploitability\n *     plateaus at the lock's floor (13% in #269's demo), so a base target like\n *     1% is typically unreachable and the plateau is what actually ends the\n *     solve instead of grinding to the iteration cap.\n */\nexport function buildLockedResolveRequest(\n  base: SolveRequest,\n  locks: readonly LockedNode[],\n  baseJobId: string,\n): SolveRequest {\n  if (locks.length === 0) throw new Error(\"no locked nodes — edit a strategy first\");\n  if (locks.length > MAX_LOCKED_NODES) {\n    throw new Error(`at most ${MAX_LOCKED_NODES} nodes can be locked per solve`);\n  }\n  if (base.aiSolve) {\n    throw new Error(\n      \"locked re-solves need the exact solve's snapshot — AI solves can't be edited\",\n    );\n  }\n  if (!baseJobId) {\n    throw new Error(\"locked re-solves must warm-start from the base solve's job\");\n  }\n  const req: SolveRequest = {\n    ...base,\n    locked_nodes: locks.map((l) => ({ ...l, path: [...l.path] })),\n    warm_start_from: baseJobId,\n    keep_snapshot: false,\n    convergence_plateau: base.convergence_plateau ?? LOCKED_SOLVE_PLATEAU,\n  };\n  return req;\n}\n\n/** True when `err` means the warm-start snapshot is gone / rejected — the one\n *  failure a locked re-solve must NOT retry cold (see module header). */\nexport function isWarmStartFailure(message: string): boolean {\n  return /snapshot|warm/i.test(message);\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/locks.ts"
    },
    {
      "path": "src/lib/explorer/plo-filter.ts",
      "content": "/**\n * PLO hand-property filtering for the range explorer.\n *\n * Ported from pokerdata.io's explorer (which took it from the mobile app), and\n * pointed at the PLO hand helpers the trainer already ships here, so both\n * surfaces classify a hand identically.\n *\n * Filter the 16,432 starting hands by suitedness, connectedness (rundown /\n * gaps), pairing, and card height. Properties are derived from a canonical\n * MonkerSolver string (see plo-hand.ts) so they line up exactly with the hands\n * in a node's weights.\n */\n\nimport { parseHandString } from \"@/lib/trainer/plo-hand\";\nimport { rankIndex, type Rank } from \"@/lib/trainer/hand\";\n\nexport type Suitedness = \"Double Suited\" | \"Single Suited\" | \"Rainbow\";\nexport type Pairing = \"Quads\" | \"Trips\" | \"Two Pair\" | \"One Pair\" | \"Unpaired\";\nexport type Connect = \"Rundown\" | \"One Gap\" | \"Two Gap\" | null;\nexport type Height = \"High\" | \"Low\" | \"High-Low\";\n\nexport interface HandProps {\n  pairing: Pairing;\n  suitedness: Suitedness;\n  /** True when the hand holds a pair of aces (AAxx). */\n  hasAces: boolean;\n  /** Connectedness, only defined for four distinct ranks (else null). */\n  connect: Connect;\n  height: Height;\n}\n\n// Higher rank → higher value. A=12 … 2=0. (RANKS is 'AKQJT98765432'.)\nfunction rankValue(r: Rank): number {\n  return 12 - rankIndex(r);\n}\n\n/** Sum of interior gaps spanned by a set of distinct rank values. */\nfunction spanGaps(values: number[]): number {\n  const s = [...values].sort((a, b) => a - b);\n  return s[s.length - 1] - s[0] - (s.length - 1);\n}\n\nfunction connectedness(ranks: Rank[]): Connect {\n  const distinct = [...new Set(ranks)];\n  if (distinct.length !== 4) return null;\n  const base = distinct.map(rankValue);\n  let gaps = spanGaps(base);\n  // An ace also plays low for wheel-ish hands (A-2-3-4); take the tighter span.\n  if (distinct.includes(\"A\")) {\n    gaps = Math.min(gaps, spanGaps(base.map((v) => (v === 12 ? -1 : v))));\n  }\n  if (gaps === 0) return \"Rundown\";\n  if (gaps === 1) return \"One Gap\";\n  if (gaps === 2) return \"Two Gap\";\n  return null;\n}\n\nfunction heightOf(ranks: Rank[]): Height {\n  // High cards are T,J,Q,K,A (rankIndex 0–4); everything else is low.\n  let high = 0;\n  let low = 0;\n  for (const r of ranks) {\n    if (rankIndex(r) <= 4) high++;\n    else low++;\n  }\n  if (low === 0) return \"High\";\n  if (high === 0) return \"Low\";\n  return \"High-Low\";\n}\n\n/** Derive filterable properties from a canonical PLO hand string. */\nexport function handProps(hand: string): HandProps {\n  const groups = parseHandString(hand);\n  const ranks = groups.flat() as Rank[];\n\n  const counts = new Map<Rank, number>();\n  for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);\n  const vals = [...counts.values()];\n  const maxOfRank = Math.max(...vals);\n  const pairs = vals.filter((v) => v >= 2).length;\n\n  let pairing: Pairing;\n  if (maxOfRank >= 4) pairing = \"Quads\";\n  else if (maxOfRank === 3) pairing = \"Trips\";\n  else if (pairs >= 2) pairing = \"Two Pair\";\n  else if (pairs === 1) pairing = \"One Pair\";\n  else pairing = \"Unpaired\";\n\n  const suited = groups.filter((g) => g.length >= 2).length;\n  const suitedness: Suitedness =\n    suited >= 2 ? \"Double Suited\" : suited === 1 ? \"Single Suited\" : \"Rainbow\";\n\n  return {\n    pairing,\n    suitedness,\n    hasAces: (counts.get(\"A\") ?? 0) >= 2,\n    connect: connectedness(ranks),\n    height: heightOf(ranks),\n  };\n}\n\nexport type FilterId =\n  | \"ds\"\n  | \"ss\"\n  | \"rainbow\"\n  | \"rundown\"\n  | \"gap1\"\n  | \"gap2\"\n  | \"aces\"\n  | \"twopair\"\n  | \"trips\"\n  | \"unpaired\"\n  | \"high\"\n  | \"low\"\n  | \"highlow\";\n\ninterface ChipDef {\n  id: FilterId;\n  label: string;\n}\n\n/**\n * Chips grouped by dimension. Selecting multiple chips in one group is an OR;\n * selecting across groups is an AND (e.g. Double Suited AND Rundown).\n */\nexport const FILTER_GROUPS: { key: string; chips: ChipDef[] }[] = [\n  {\n    key: \"Suits\",\n    chips: [\n      { id: \"ds\", label: \"Double Suited\" },\n      { id: \"ss\", label: \"Single Suited\" },\n      { id: \"rainbow\", label: \"Rainbow\" },\n    ],\n  },\n  {\n    key: \"Shape\",\n    chips: [\n      { id: \"rundown\", label: \"Rundown\" },\n      { id: \"gap1\", label: \"1-Gap\" },\n      { id: \"gap2\", label: \"2-Gap\" },\n    ],\n  },\n  {\n    key: \"Pairs\",\n    chips: [\n      { id: \"aces\", label: \"Aces\" },\n      { id: \"twopair\", label: \"Two Pair\" },\n      { id: \"trips\", label: \"Trips+\" },\n      { id: \"unpaired\", label: \"Unpaired\" },\n    ],\n  },\n  {\n    key: \"Height\",\n    chips: [\n      { id: \"high\", label: \"High\" },\n      { id: \"low\", label: \"Low\" },\n      { id: \"highlow\", label: \"High-Low\" },\n    ],\n  },\n];\n\nconst PREDICATE: Record<FilterId, (p: HandProps) => boolean> = {\n  ds: (p) => p.suitedness === \"Double Suited\",\n  ss: (p) => p.suitedness === \"Single Suited\",\n  rainbow: (p) => p.suitedness === \"Rainbow\",\n  rundown: (p) => p.connect === \"Rundown\",\n  gap1: (p) => p.connect === \"One Gap\",\n  gap2: (p) => p.connect === \"Two Gap\",\n  aces: (p) => p.hasAces,\n  twopair: (p) => p.pairing === \"Two Pair\",\n  trips: (p) => p.pairing === \"Trips\" || p.pairing === \"Quads\",\n  unpaired: (p) => p.pairing === \"Unpaired\",\n  high: (p) => p.height === \"High\",\n  low: (p) => p.height === \"Low\",\n  highlow: (p) => p.height === \"High-Low\",\n};\n\n/** A hand passes when, for every constrained dimension, it matches ≥1 chip. */\nexport function matchesFilters(p: HandProps, active: Set<FilterId>): boolean {\n  if (active.size === 0) return true;\n  for (const group of FILTER_GROUPS) {\n    const selected = group.chips.filter((c) => active.has(c.id));\n    if (selected.length === 0) continue;\n    if (!selected.some((c) => PREDICATE[c.id](p))) return false;\n  }\n  return true;\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/plo-filter.ts"
    },
    {
      "path": "src/lib/explorer/plo4hu-postflop-stacks.ts",
      "content": "/** Heads-up PLO4 stack depths whose postflop the engine serves (one Monker postflop blueprint each). */\nexport const PLO4HU_POSTFLOP_STACKS: readonly number[] = [30, 50, 100, 200];\n",
      "type": "registry:lib",
      "target": "lib/explorer/plo4hu-postflop-stacks.ts"
    },
    {
      "path": "src/lib/explorer/resolve-carry.ts",
      "content": "// CFR-D promise extraction for on-demand subgame re-solves (#233).\n//\n// A cold child solve at a chance boundary is *unsafe*: it hands the opponent\n// their full reach-weighted range unconditionally, as if they were never\n// allowed to avoid the subgame (the engine measured that bootstrap at ~15% pot\n// of extra exploitability in agent mode). The CFR-D gadget fixes this — the\n// opponent's root behavior becomes \"Terminate for the carried CFV promise, or\n// Follow into the subgame\" — but it needs those promises, and the only place\n// the HTTP API emits them today is at the PARENT solve's root actions\n// (`emit_carry_for` → `SolverResult.resolve.carry`).\n//\n// This module decides when that root carry is a valid promise vector for a\n// child solve deeper in the tree, following the engine's own carry semantics\n// (resolve_agent.rs):\n//\n//   • promises pass through the OPPONENT's actions unchanged — CFVs are\n//     counterfactual, so conditioning on the opponent's choice would assume a\n//     policy for them;\n//   • promises do NOT pass through the RESOLVER's own later actions — each\n//     resolver decision needs a fresh re-solve whose carry covers it, and we\n//     only hold the parent root's. A path where the resolver acts again is\n//     therefore ineligible (return null → the caller falls back to the\n//     reach-range solve);\n//   • promises crossing a dealt card should be *pinned* on it\n//     (`node_cfvs_pinned`); the HTTP carry is the runout average, which the\n//     engine measured at ~4-5% pot of mispricing — still far better than the\n//     unsafe bootstrap, so we use it and flag the result `approximate`.\n//\n// Both limitations are closed by the worker's `POST /solve/:id/carry`\n// endpoint when the parent solve's job kept its accumulator snapshot (#262):\n// the worker reloads the parent, walks the path with exact reaches (any\n// number of resolver decisions), and prices the promises pinned on the dealt\n// card. `pinnedCarryForChild` below prefers that endpoint and returns\n// `approximate: false`; this module's root-carry extraction stays as the\n// fallback for parents with no live snapshot (saved bundles, gadget children\n// — the engine cannot snapshot gadget solves — or an evicted/restarted\n// worker).\n//\n// The resolver is fixed to OOP (player 0): postflop OOP acts first at every\n// street root, so the parent root is always the resolver's decision and every\n// child root opens with the resolver again — the shape the chain needs.\n\nimport { explorerHost } from \"@/lib/explorer/host\";\nimport type { ResolveConfig, SolveRequest, SolverResult } from \"@/lib/solver/types\";\nimport { actionSegment, dealCard, isDealSegment, nodeAtPath } from \"./subgame\";\n\n/** The resolver whose perspective the viewer chain re-solves for (OOP). */\nexport const CHAIN_RESOLVER = 0 as const;\n\nexport interface CarryAttach {\n  /** Engine gadget config, ready to place on the child `SolveRequest`. */\n  resolve: ResolveConfig;\n  /** True when the promises crossed one or more dealt cards and are therefore\n   *  runout-averaged rather than card-pinned (engine-measured ~4-5% pot of\n   *  mispricing vs ~15% for no gadget at all). Surfaced in the viewer so a\n   *  \"safe re-solve\" badge never overclaims. */\n  approximate: boolean;\n}\n\n/**\n * The CFV promises for the subgame rooted after dealing `card` at the chance\n * node reached by `path` through the parent solve — or null when the parent\n * result carries none that are valid there (no `emit_carry_for` output, a PLO\n * solve, the resolver acting more than once along the path, or every carried\n * combo blocked by the runout).\n */\nexport function carryForChild(\n  config: SolveRequest,\n  result: SolverResult,\n  path: readonly string[],\n  card: string,\n): CarryAttach | null {\n  // NLHE only — the engine rejects the gadget for PLO, and the 4-char combo\n  // blocker logic below assumes two-card combos.\n  if ((config.variant ?? \"nlhe\") !== \"nlhe\") return null;\n\n  const carry = result.resolve?.carry;\n  if (!carry || carry.length === 0) return null;\n  if (path.length === 0) return null;\n\n  // The parent root must be the resolver's decision and the path must open\n  // with one of its actions — that action indexes the carry vector.\n  if (result.root.player !== CHAIN_RESOLVER) return null;\n  const first = path[0];\n  if (isDealSegment(first)) return null;\n  const rootIdx = result.root.actions.findIndex((a) => actionSegment(a) === first);\n  if (rootIdx < 0 || rootIdx >= carry.length) return null;\n  const promises = carry[rootIdx];\n  if (!promises || promises.length === 0) return null;\n\n  // Walk the rest of the path: opponent actions and deals pass through;\n  // another resolver decision invalidates the root carry.\n  const dealt: string[] = [];\n  for (let i = 1; i < path.length; i++) {\n    const seg = path[i];\n    if (isDealSegment(seg)) {\n      dealt.push(dealCard(seg));\n      continue;\n    }\n    const node = nodeAtPath(result.nodes ?? [], path.slice(0, i));\n    if (!node) return null;\n    if (node.player === CHAIN_RESOLVER) return null;\n  }\n  dealt.push(card);\n\n  // Drop promise combos blocked by the cards dealt since the parent root.\n  const blocked = new Set(dealt.map((c) => `${c[0].toUpperCase()}${c[1].toLowerCase()}`));\n  const opponent_cfvs: [string, number][] = [];\n  for (const [combo, cfv] of promises) {\n    if (blocked.has(combo.slice(0, 2)) || blocked.has(combo.slice(2, 4))) continue;\n    opponent_cfvs.push([combo, cfv]);\n  }\n  if (opponent_cfvs.length === 0) return null;\n\n  return {\n    resolve: { resolver: CHAIN_RESOLVER, opponent_cfvs },\n    // `card` itself always crosses a deal; the promises were computed at the\n    // parent root, before any runout, so they are runout-averaged by\n    // construction. Only a same-street action chain with no deal would be\n    // exact, and a chance-boundary child never is.\n    approximate: true,\n  };\n}\n\n/**\n * Fetch card-pinned promises from the worker for the subgame rooted after\n * dealing `card` at the chance node reached by `path` through the parent\n * solve — exact for any path, including lines where the resolver acts more\n * than once. `jobId` must be the parent solve's worker job; it needs a kept\n * snapshot (`keep_snapshot`, #262), so this only works for solves run in the\n * current worker lifetime. Returns null on any failure (no snapshot, evicted,\n * worker restarted, non-NLHE...) — the caller falls back to `carryForChild`.\n */\nexport async function fetchPinnedCarry(\n  jobId: string,\n  path: readonly string[],\n  card: string,\n): Promise<CarryAttach | null> {\n  try {\n    const solver = explorerHost().solver;\n    if (!solver) return null;\n    const res = await fetch(`${solver}/jobs/${jobId}/carry`, {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n      body: JSON.stringify({ resolver: CHAIN_RESOLVER, path, card }),\n    });\n    if (!res.ok) return null;\n    const payload = (await res.json()) as { opponent_cfvs?: unknown };\n    const cfvs = payload.opponent_cfvs;\n    if (!Array.isArray(cfvs) || cfvs.length === 0) return null;\n    const opponent_cfvs: [string, number][] = [];\n    for (const entry of cfvs) {\n      if (\n        !Array.isArray(entry) ||\n        entry.length !== 2 ||\n        typeof entry[0] !== \"string\" ||\n        typeof entry[1] !== \"number\" ||\n        !Number.isFinite(entry[1])\n      ) {\n        return null;\n      }\n      opponent_cfvs.push([entry[0], entry[1]]);\n    }\n    return {\n      resolve: { resolver: CHAIN_RESOLVER, opponent_cfvs },\n      // The worker pinned the promises on `card` with exact path reaches —\n      // this is the full CFR-D carry, not the runout-averaged root fallback.\n      approximate: false,\n    };\n  } catch {\n    return null;\n  }\n}\n\n/**\n * The promises for a child re-solve, preferring the worker's pinned endpoint\n * (exact, any path) when the parent has a live snapshot job, falling back to\n * the client-side root-carry extraction (runout-averaged, root-anchored\n * paths only), then to null — the unsafe reach bootstrap.\n */\nexport async function pinnedCarryForChild(\n  parentJobId: string | undefined,\n  config: SolveRequest,\n  result: SolverResult,\n  path: readonly string[],\n  card: string,\n): Promise<CarryAttach | null> {\n  // NLHE only, mirroring carryForChild — don't ask the worker what the\n  // engine will reject anyway.\n  if ((config.variant ?? \"nlhe\") === \"nlhe\" && parentJobId && path.length > 0) {\n    const pinned = await fetchPinnedCarry(parentJobId, path, card);\n    if (pinned) return pinned;\n  }\n  return carryForChild(config, result, path, card);\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/resolve-carry.ts"
    },
    {
      "path": "src/lib/explorer/share-url.ts",
      "content": "// The Explorer's shareable state, as it lives in the /explorer query string.\n//\n//   game   dataset id (nl, plo, plo4hu, plo9, plo5, plo6hu, nlmtt8)\n//   stack  stack depth in bb (the field's average on the ICM sets)\n//   table  ICM sets only: the stack table, a scenario id (\"33left-avg30-short-btn\")\n//   line   the walked history, e.g. \"UTG_Fold_HJ_Raise2.5_CO\" (omitted at the root)\n//   close  the action that closed the round on `line` (a history stops at the\n//          seat that acted, so the closing action can't live in it)\n//   tab    \"buckets\" when that range tab is open (Explorer is the default)\n//   f      PLO filter chips, comma-separated ids (\"ds,rundown\")\n//   q      PLO5/PLO6 rank filter text\n//   s      PLO hand search in GTO Wizard syntax (\"AA**:$ds\", see lib/hand-search)\n//\n// Pure: parsing never throws, and anything malformed is dropped so a bad or\n// stale link opens the default view instead of a broken one.\n\nimport { SEAT_ORDER, type ExplorerGame } from \"@/lib/solver/preflop\";\n\nexport const EXPLORER_GAMES = Object.keys(SEAT_ORDER) as ExplorerGame[];\n\nexport type ExplorerUrlKey = \"game\" | \"stack\" | \"table\" | \"line\" | \"close\" | \"tab\" | \"f\" | \"q\" | \"s\";\nexport const EXPLORER_URL_KEYS: ExplorerUrlKey[] = [\n  \"game\",\n  \"stack\",\n  \"table\",\n  \"line\",\n  \"close\",\n  \"tab\",\n  \"f\",\n  \"q\",\n  \"s\",\n];\n\nexport type ExplorerUrlState = Partial<Record<ExplorerUrlKey, string>>;\n\n// Action labels vary by dataset (\"Fold\", \"Raise2.5\", \"60%\", \"AllIn\"); `_` is\n// the history separator, so anything else printable is allowed. Lines are\n// only ever sent URL-encoded to the ranges API.\nconst ACTION_TOKEN = /^[^_\\s<>\"'`]{1,32}$/;\n\n/** First query value for each known key, from Next's `searchParams` shape. */\nexport function pickExplorerParams(\n  params: Record<string, string | string[] | undefined>,\n): ExplorerUrlState {\n  const out: ExplorerUrlState = {};\n  for (const key of EXPLORER_URL_KEYS) {\n    const raw = params[key];\n    const v = Array.isArray(raw) ? raw[0] : raw;\n    if (typeof v === \"string\" && v.length > 0 && v.length <= 400) out[key] = v;\n  }\n  return out;\n}\n\nexport function parseGame(v: string | undefined): ExplorerGame | null {\n  return v && (EXPLORER_GAMES as string[]).includes(v) ? (v as ExplorerGame) : null;\n}\n\nexport function parseStack(v: string | undefined): number | null {\n  if (!v || !/^\\d{1,4}$/.test(v)) return null;\n  const n = Number(v);\n  return n > 0 ? n : null;\n}\n\n/** A history this dataset's walk can replay: starts at its first actor,\n *  alternates seat / action, and ends on a seat. */\nexport function parseLine(v: string | undefined, game: ExplorerGame): string | null {\n  if (!v) return null;\n  const order = SEAT_ORDER[game] as string[];\n  const tokens = v.split(\"_\");\n  if (tokens.length % 2 === 0 || tokens[0] !== order[0]) return null;\n  for (let i = 0; i < tokens.length; i++) {\n    const ok = i % 2 === 0 ? order.includes(tokens[i]) : ACTION_TOKEN.test(tokens[i]);\n    if (!ok) return null;\n  }\n  return v;\n}\n\n/** An ICM stack table id (`33left-avg30-short-btn`), or null. */\nexport function parseTable(v: string | undefined): string | null {\n  return v && /^\\d{1,3}left-avg\\d{1,3}(?:\\.\\d+)?-[a-z0-9-]{1,24}$/.test(v) ? v : null;\n}\n\nexport function parseAction(v: string | undefined): string | null {\n  return v && ACTION_TOKEN.test(v) ? v : null;\n}\n\n/** Merge `patch` into `search` (null/\"\" removes a key), keeping unrelated\n *  params, and return the query string with a leading \"?\" (or \"\"). */\nexport function mergeSearch(search: string, patch: ExplorerUrlState | Record<string, string | null>): string {\n  const params = new URLSearchParams(search);\n  for (const [k, v] of Object.entries(patch)) {\n    if (v == null || v === \"\") params.delete(k);\n    else params.set(k, v);\n  }\n  const s = params.toString();\n  return s ? `?${s}` : \"\";\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/share-url.ts"
    },
    {
      "path": "src/lib/explorer/solution-catalog.ts",
      "content": "// Client-safe catalog of preflop solutions the Explorer can switch between —\n// the data behind the GTO-Wizard-style solution selector. Grouped by game/\n// format, mirroring the `/sims` catalog.\n//\n// `browsable` solutions are walkable in the Explorer (today: NLHE 6-max, served\n// by `/api/ranges/nl`); the rest are download-only for now and deep-link to the\n// `/sims` catalog. Stacks are gated at runtime against the ranges manifest, so a\n// browsable row only opens if its dataset is actually present.\n\nimport type { ExplorerGame } from \"@/lib/solver/preflop\";\n\nexport interface SolutionStack {\n  /** Effective stack in bb. */\n  stack: number;\n  /** Raise/sizing tree, human-readable. */\n  raises: string;\n  /** \"Pre-flop\" | \"Post-flop\". */\n  type: \"Pre-flop\" | \"Post-flop\";\n  /** Approx download size label, e.g. \"7 MB\" (download-only groups). */\n  size?: string;\n  /**\n   * ICM sets: the stack tables solved at this average depth (one solve each,\n   * uneven stacks included), by scenario id. The first is the default.\n   */\n  tables?: SolutionTable[];\n}\n\n/** One ICM stack table: a scenario of `/api/ranges/nlh8-icm`. */\nexport interface SolutionTable {\n  /** Scenario id, e.g. `33left-avg30-short-btn`. */\n  scenario: string;\n  /** Short label for a picker chip, e.g. \"Short BTN\". */\n  label: string;\n}\n\nexport type GameKind = \"holdem\" | \"omaha\" | \"plo5\" | \"plo6\";\nexport type PlayersKind = \"hu\" | \"6max\" | \"8max\" | \"9max\";\n/** Format facet: ring cash game or tournament. */\nexport type FormatKind = \"cash\" | \"tournament\";\n/**\n * Rake facet. Cash solves are tiered by the rake they were solved with, since\n * rake (not blinds) is what changes a solver's strategy: a big cap in bb is\n * what low stakes pay, a tiny cap is high stakes. `chipev` means no rake at\n * all: tournament chip-EV solves and rake-free cash solves. `icm` is a\n * tournament solve whose EVs are prize money (ICM), so no rake either.\n *   low:  named micro/low stake (NL25) or cap of 1bb and up\n *   mid:  cap from 0.1bb up to 1bb\n *   high: cap under 0.1bb\n */\nexport type RakeTier = \"low\" | \"mid\" | \"high\" | \"chipev\" | \"icm\";\n\nexport const FORMAT_LABEL: Record<FormatKind, string> = {\n  cash: \"Cash\",\n  tournament: \"Tournament\",\n};\nexport const RAKE_TIER_LABEL: Record<RakeTier, string> = {\n  low: \"Low stakes\",\n  mid: \"Mid stakes\",\n  high: \"High stakes\",\n  chipev: \"Chip EV\",\n  icm: \"ICM\",\n};\n\nexport interface SolutionGroup {\n  id: string;\n  /** Format line, e.g. \"No-limit hold'em · 6-max\". */\n  format: string;\n  /** Rake line, e.g. \"rake 5%, 0.5bb cap\". */\n  rake: string;\n  /** Game facet. */\n  game: GameKind;\n  /** Table-size facet. */\n  players: PlayersKind;\n  /** Short rake label for the table column, e.g. \"NL25\" / \"PLO\" / \"none\". */\n  rakeShort: string;\n  /** Format facet (cash / tournament). */\n  formatKind: FormatKind;\n  /** Rake facet; see {@link RakeTier} for how a group is tiered. */\n  rakeTier: RakeTier;\n  /** True when the Explorer can interactively browse this group. */\n  browsable: boolean;\n  stacks: SolutionStack[];\n}\n\nexport const SOLUTION_GROUPS: SolutionGroup[] = [\n  {\n    id: \"nlhe-6max\",\n    format: \"No-limit hold'em · 6-max\",\n    rake: \"rake 5%, 0.5bb cap\",\n    game: \"holdem\",\n    players: \"6max\",\n    rakeShort: \"NL25\",\n    formatKind: \"cash\",\n    rakeTier: \"low\",\n    browsable: true,\n    stacks: [\n      { stack: 20, raises: \"Min + 55–100% pot + all-in\", type: \"Pre-flop\" },\n      { stack: 30, raises: \"Min + 40–120% pot + all-in\", type: \"Pre-flop\" },\n      { stack: 40, raises: \"Min + 45–120% pot + all-in\", type: \"Pre-flop\" },\n      { stack: 50, raises: \"Min + 44–125% pot + all-in\", type: \"Pre-flop\" },\n      { stack: 70, raises: \"45–175% pot + all-in\", type: \"Pre-flop\" },\n      { stack: 100, raises: \"49–200% pot + all-in\", type: \"Pre-flop\" },\n      { stack: 150, raises: \"49–200% pot + all-in\", type: \"Pre-flop\" },\n      { stack: 200, raises: \"49–200% pot + all-in\", type: \"Pre-flop\" },\n    ],\n  },\n  {\n    id: \"nlhe-mtt-8max\",\n    format: \"No-limit hold'em tournament · 8-max\",\n    rake: \"none — tournament chip EV, 1bb BB-ante\",\n    game: \"holdem\",\n    players: \"8max\",\n    rakeShort: \"MTT\",\n    formatKind: \"tournament\",\n    rakeTier: \"chipev\",\n    browsable: true,\n    stacks: [\n      { stack: 10, raises: \"All-in / fold\", type: \"Pre-flop\" },\n      { stack: 15, raises: \"Min + all-in\", type: \"Pre-flop\" },\n      { stack: 20, raises: \"Min + pot% + all-in\", type: \"Pre-flop\" },\n      { stack: 30, raises: \"Min + pot% + all-in\", type: \"Pre-flop\" },\n      { stack: 40, raises: \"34% pot open + all-in\", type: \"Pre-flop\" },\n      { stack: 50, raises: \"34% pot open + all-in\", type: \"Pre-flop\" },\n      { stack: 75, raises: \"43% pot open + all-in\", type: \"Pre-flop\" },\n      { stack: 100, raises: \"34% pot open + all-in\", type: \"Pre-flop\" },\n      { stack: 200, raises: \"43% pot open + all-in\", type: \"Pre-flop\" },\n      { stack: 300, raises: \"43% pot open + all-in\", type: \"Pre-flop\" },\n    ],\n  },\n  {\n    id: \"nlhe-icm-ft\",\n    format: \"No-limit hold'em ICM · 8-max final table\",\n    rake: \"none — ICM final table: 8 left, 8 paid, $27,728 pool · 0.125bb ante per seat\",\n    game: \"holdem\",\n    players: \"8max\",\n    rakeShort: \"ICM\",\n    formatKind: \"tournament\",\n    rakeTier: \"icm\",\n    browsable: true,\n    stacks: [\n      {\n        stack: 15,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"8left-avg15-even\", label: \"Even stacks\" },\n        { scenario: \"8left-avg15-short-bb\", label: \"Short BB\" },\n        { scenario: \"8left-avg15-short-co\", label: \"Short CO\" },\n        { scenario: \"8left-avg15-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"8left-avg15-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"8left-avg15-big-btn\", label: \"Big BTN\" },\n        { scenario: \"8left-avg15-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n      {\n        stack: 20,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"8left-avg20-even\", label: \"Even stacks\" },\n        { scenario: \"8left-avg20-short-bb\", label: \"Short BB\" },\n        { scenario: \"8left-avg20-short-co\", label: \"Short CO\" },\n        { scenario: \"8left-avg20-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"8left-avg20-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"8left-avg20-big-btn\", label: \"Big BTN\" },\n        { scenario: \"8left-avg20-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n      {\n        stack: 25,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"8left-avg25-even\", label: \"Even stacks\" },\n        { scenario: \"8left-avg25-short-lj\", label: \"Short LJ\" },\n        { scenario: \"8left-avg25-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"8left-avg25-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"8left-avg25-big-bb\", label: \"Big BB\" },\n        { scenario: \"8left-avg25-big-hj\", label: \"Big HJ\" },\n        ],\n      },\n      {\n        stack: 30,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"8left-avg30-even\", label: \"Even stacks\" },\n        { scenario: \"8left-avg30-short-btn\", label: \"Short BTN\" },\n        { scenario: \"8left-avg30-short-utg\", label: \"Short UTG\" },\n        { scenario: \"8left-avg30-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"8left-avg30-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"8left-avg30-big-sb\", label: \"Big SB\" },\n        { scenario: \"8left-avg30-big-co\", label: \"Big CO\" },\n        ],\n      },\n      {\n        stack: 40,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"8left-avg40-short-bb\", label: \"Short BB\" },\n        { scenario: \"8left-avg40-short-co\", label: \"Short CO\" },\n        { scenario: \"8left-avg40-short-sb\", label: \"Short SB\" },\n        { scenario: \"8left-avg40-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"8left-avg40-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"8left-avg40-big-bb\", label: \"Big BB\" },\n        { scenario: \"8left-avg40-big-btn\", label: \"Big BTN\" },\n        { scenario: \"8left-avg40-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n    ],\n  },\n  {\n    id: \"nlhe-icm-bubble\",\n    format: \"No-limit hold'em ICM · 8-max near the bubble\",\n    rake: \"none — ICM near the bubble: 33 of 200 left, 30 paid, $40,000 pool · 0.125bb ante per seat\",\n    game: \"holdem\",\n    players: \"8max\",\n    rakeShort: \"ICM\",\n    formatKind: \"tournament\",\n    rakeTier: \"icm\",\n    browsable: true,\n    stacks: [\n      {\n        stack: 15,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"33left-avg15-even\", label: \"Even stacks\" },\n        { scenario: \"33left-avg15-short-bb\", label: \"Short BB\" },\n        { scenario: \"33left-avg15-short-co\", label: \"Short CO\" },\n        { scenario: \"33left-avg15-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"33left-avg15-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"33left-avg15-big-btn\", label: \"Big BTN\" },\n        { scenario: \"33left-avg15-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n      {\n        stack: 20,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"33left-avg20-even\", label: \"Even stacks\" },\n        { scenario: \"33left-avg20-short-bb\", label: \"Short BB\" },\n        { scenario: \"33left-avg20-short-co\", label: \"Short CO\" },\n        { scenario: \"33left-avg20-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"33left-avg20-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"33left-avg20-big-btn\", label: \"Big BTN\" },\n        { scenario: \"33left-avg20-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n      {\n        stack: 25,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"33left-avg25-even\", label: \"Even stacks\" },\n        { scenario: \"33left-avg25-short-lj\", label: \"Short LJ\" },\n        { scenario: \"33left-avg25-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"33left-avg25-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"33left-avg25-big-bb\", label: \"Big BB\" },\n        { scenario: \"33left-avg25-big-hj\", label: \"Big HJ\" },\n        ],\n      },\n      {\n        stack: 30,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"33left-avg30-even\", label: \"Even stacks\" },\n        { scenario: \"33left-avg30-short-btn\", label: \"Short BTN\" },\n        { scenario: \"33left-avg30-short-utg\", label: \"Short UTG\" },\n        { scenario: \"33left-avg30-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"33left-avg30-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"33left-avg30-big-sb\", label: \"Big SB\" },\n        { scenario: \"33left-avg30-big-co\", label: \"Big CO\" },\n        ],\n      },\n      {\n        stack: 40,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"33left-avg40-short-bb\", label: \"Short BB\" },\n        { scenario: \"33left-avg40-short-co\", label: \"Short CO\" },\n        { scenario: \"33left-avg40-short-sb\", label: \"Short SB\" },\n        { scenario: \"33left-avg40-mix-1\", label: \"Mixed 1\" },\n        { scenario: \"33left-avg40-mix-2\", label: \"Mixed 2\" },\n        { scenario: \"33left-avg40-big-bb\", label: \"Big BB\" },\n        { scenario: \"33left-avg40-big-btn\", label: \"Big BTN\" },\n        { scenario: \"33left-avg40-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n    ],\n  },\n  {\n    id: \"nlhe-icm-bubble35\",\n    format: \"No-limit hold'em ICM · 8-max near the bubble, multi-table\",\n    rake: \"none — ICM near the bubble: 35 of 200 left over several tables, 30 paid, $50,000 pool · 0.125bb ante per seat\",\n    game: \"holdem\",\n    players: \"8max\",\n    rakeShort: \"ICM\",\n    formatKind: \"tournament\",\n    rakeTier: \"icm\",\n    browsable: true,\n    stacks: [\n      {\n        stack: 20,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"35left-avg20-even\", label: \"Even stacks\" },\n        { scenario: \"35left-avg20-big-btn\", label: \"Big BTN\" },\n        { scenario: \"35left-avg20-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n      {\n        stack: 25,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"35left-avg25-even\", label: \"Even stacks\" },\n        { scenario: \"35left-avg25-big-bb\", label: \"Big BB\" },\n        ],\n      },\n      {\n        stack: 30,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"35left-avg30-even\", label: \"Even stacks\" },\n        { scenario: \"35left-avg30-big-co\", label: \"Big CO\" },\n        ],\n      },\n      {\n        stack: 40,\n        raises: \"Open + 3-bet + all-in\",\n        type: \"Pre-flop\",\n        tables: [\n        { scenario: \"35left-avg40-even\", label: \"Even stacks\" },\n        { scenario: \"35left-avg40-short-bb\", label: \"Short BB\" },\n        { scenario: \"35left-avg40-short-sb\", label: \"Short SB\" },\n        { scenario: \"35left-avg40-big-bb\", label: \"Big BB\" },\n        { scenario: \"35left-avg40-big-btn\", label: \"Big BTN\" },\n        { scenario: \"35left-avg40-big-utg\", label: \"Big UTG\" },\n        ],\n      },\n    ],\n  },\n  {\n    id: \"plo-9max\",\n    format: \"Pot-limit Omaha · 9-max\",\n    rake: \"rake 5%, 2bb cap\",\n    game: \"omaha\",\n    players: \"9max\",\n    rakeShort: \"PLO\",\n    formatKind: \"cash\",\n    rakeTier: \"low\",\n    browsable: false,\n    stacks: [\n      { stack: 60, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"4.3 GB\" },\n      { stack: 100, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"8.9 GB\" },\n    ],\n  },\n  {\n    id: \"plo-6max\",\n    format: \"Pot-limit Omaha · 6-max\",\n    rake: \"rake 5%, 1bb cap\",\n    game: \"omaha\",\n    players: \"6max\",\n    rakeShort: \"PLO\",\n    formatKind: \"cash\",\n    rakeTier: \"low\",\n    // Walkable since the Explorer learned to render Omaha ranges as a\n    // hand-class list. PLO 9-max stays download-only: its bundles are too big\n    // for the whole-bundle ranges API (issues #35/#36), so /api/ranges/plo9\n    // has no data to serve.\n    browsable: true,\n    stacks: [\n      { stack: 12, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"23 MB\" },\n      { stack: 20, raises: \"Pot + min-raise + all-in\", type: \"Pre-flop\", size: \"98 MB\" },\n      { stack: 30, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"97 MB\" },\n      { stack: 40, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"414 MB\" },\n      { stack: 50, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"182 MB\" },\n      { stack: 75, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"582 MB\" },\n      { stack: 100, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"645 MB\" },\n      { stack: 150, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"683 MB\" },\n      { stack: 200, raises: \"Pot + all-in\", type: \"Pre-flop\", size: \"986 MB\" },\n    ],\n  },\n  {\n    id: \"plo-hu\",\n    format: \"Pot-limit Omaha · Heads-up\",\n    rake: \"rake 4.5%, 0.045bb cap · no flop, no drop\",\n    game: \"omaha\",\n    players: \"hu\",\n    rakeShort: \"PLO\",\n    formatKind: \"cash\",\n    rakeTier: \"high\",\n    // MonkerSolver blueprints (Nov 2026; 100bb, 200bb and 75bb on monker-2; 50bb, 40bb, 30bb, 20bb and 10bb on monker-1):\n    // SB may limp, every raise is pot-sized. Walkable through /api/ranges/plo4hu.\n    browsable: true,\n    stacks: [\n      { stack: 10, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n      { stack: 20, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n      { stack: 30, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n      { stack: 40, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n      { stack: 50, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n      { stack: 75, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n      { stack: 100, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n      { stack: 200, raises: \"Limp or pot raise + pot re-raises\", type: \"Pre-flop\" },\n    ],\n  },\n  {\n    id: \"plo5-6max\",\n    format: \"Pot-limit Omaha 5 · 6-max\",\n    rake: \"rake 5%, 1bb cap · 1.2bb ante\",\n    game: \"plo5\",\n    players: \"6max\",\n    rakeShort: \"PLO5\",\n    formatKind: \"cash\",\n    rakeTier: \"low\",\n    browsable: true,\n    stacks: [\n      { stack: 100, raises: \"4.7x open + raise tree\", type: \"Pre-flop\" },\n    ],\n  },\n  {\n    id: \"plo6-hu\",\n    format: \"Pot-limit Omaha 6 · Heads-up\",\n    rake: \"rake 5%, 0.5bb cap · 0.4bb ante\",\n    game: \"plo6\",\n    players: \"hu\",\n    rakeShort: \"PLO6\",\n    formatKind: \"cash\",\n    rakeTier: \"mid\",\n    browsable: true,\n    stacks: [\n      { stack: 100, raises: \"3.4x open + 10.6x / 32.2x / jam\", type: \"Pre-flop\" },\n    ],\n  },\n  {\n    id: \"nlhe-hu\",\n    format: \"No-limit hold'em · Heads-up\",\n    rake: \"rake none\",\n    game: \"holdem\",\n    players: \"hu\",\n    rakeShort: \"none\",\n    formatKind: \"cash\",\n    rakeTier: \"chipev\",\n    browsable: false,\n    stacks: [{ stack: 100, raises: \"33%/75% pot + all-in\", type: \"Post-flop\", size: \"221 KB\" }],\n  },\n];\n\n/** A flattened, filterable table row (one per group×stack). */\nexport interface SolutionRow {\n  group: SolutionGroup;\n  stack: SolutionStack;\n}\n\nexport function allRows(): SolutionRow[] {\n  return SOLUTION_GROUPS.flatMap((group) => group.stacks.map((stack) => ({ group, stack })));\n}\n\n/** The single browsable group the Explorer walks today. */\nexport const BROWSABLE_GROUP = SOLUTION_GROUPS.find((g) => g.browsable)!;\n\n/**\n * Catalog groups ↔ the ranges datasets the Explorer can walk. Only browsable\n * groups map; everything else is preview/download-only.\n */\nconst GROUP_GAME: Record<string, ExplorerGame> = {\n  \"nlhe-6max\": \"nl\",\n  \"nlhe-mtt-8max\": \"nlmtt8\",\n  \"nlhe-icm-ft\": \"icmft\",\n  \"nlhe-icm-bubble\": \"icmbubble\",\n  \"nlhe-icm-bubble35\": \"icmbubble35\",\n  \"plo-6max\": \"plo\",\n  \"plo-hu\": \"plo4hu\",\n  \"plo5-6max\": \"plo5\",\n  \"plo6-hu\": \"plo6hu\",\n};\n\nexport function gameForGroup(groupId: string): ExplorerGame | null {\n  return GROUP_GAME[groupId] ?? null;\n}\n\nexport function groupForGame(game: ExplorerGame): SolutionGroup {\n  const id = Object.keys(GROUP_GAME).find((k) => GROUP_GAME[k] === game);\n  return (id ? groupById(id) : undefined) ?? BROWSABLE_GROUP;\n}\n\nexport function groupById(id: string): SolutionGroup | undefined {\n  return SOLUTION_GROUPS.find((g) => g.id === id);\n}\n\n/** Raise label for a group's stack (for the card subtitle). */\n/**\n * pokerdata.io's pack id prefix per catalog group, for the explorer's\n * Download button: `<prefix>-<stack>bb` is the preflop pack that holds the\n * solve on screen (ids match pokerdata's `src/lib/sims.ts`). Groups without\n * a pack for sale map to nothing.\n */\nconst PACK_PREFIX: Record<string, string> = {\n  \"nlhe-6max\": \"nlh-6max\",\n  \"nlhe-mtt-8max\": \"nlh-mtt-8max\",\n  \"plo-9max\": \"plo9-9max\",\n  \"plo-6max\": \"plo6-6max\",\n  \"plo5-6max\": \"plo5-6max\",\n};\n\n/** The downloadable pack for a group at a stack, or null when none is sold. */\nexport function packIdFor(groupId: string, stack: number): string | null {\n  const prefix = PACK_PREFIX[groupId];\n  return prefix ? `${prefix}-${stack}bb` : null;\n}\n\n/** The stack tables at a depth (ICM sets), or [] where a depth is one solve. */\nexport function tablesFor(group: SolutionGroup, stack: number): SolutionTable[] {\n  return group.stacks.find((s) => s.stack === stack)?.tables ?? [];\n}\n\n/** The table a pick of (group, stack) opens: the named one if it's there, else the first. */\nexport function defaultTable(\n  group: SolutionGroup,\n  stack: number,\n  scenario?: string | null,\n): SolutionTable | null {\n  const tables = tablesFor(group, stack);\n  return tables.find((t) => t.scenario === scenario) ?? tables[0] ?? null;\n}\n\n/** Number of solves a stack row stands for: one per table, else one. */\nexport function solveCount(s: SolutionStack): number {\n  return s.tables?.length || 1;\n}\n\nexport function raisesFor(group: SolutionGroup, stack: number): string | undefined {\n  return group.stacks.find((s) => s.stack === stack)?.raises;\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/solution-catalog.ts"
    },
    {
      "path": "src/lib/explorer/subgame.ts",
      "content": "// Subgame extraction for the postflop solution viewer (#231).\n//\n// A saved `CustomSolutionBundle` carries the solved strategy at every action\n// node up to `dump_max_deals` chance deals past the start street. Walking past\n// that horizon (e.g. picking a river card in a flop bundle dumped at one deal)\n// needs a *new* solve of the subgame rooted after the chosen card. This module\n// derives that child `SolveRequest` from the bundle alone:\n//\n//   • the reach-weighted ranges at the chance node — walk the per-node\n//     strategies from the root ranges, multiplying each combo's weight by the\n//     frequency of the action actually taken at every decision on the path,\n//     and zeroing combos blocked by dealt cards;\n//   • the pot and effective stack — accumulated from each taken action's\n//     chip `add` along the path (a chance node is only reachable with equal\n//     street contributions, so stack-behind = start stack − half the growth).\n//\n// Everything here is pure and client-safe; the viewer submits the produced\n// request through the existing `/api/solver/jobs` plumbing.\n\nimport type {\n  ResolveConfig,\n  SolveRequest,\n  SolverActionInfo,\n  SolverNode,\n  SolverResult,\n} from \"@/lib/solver/types\";\n\n// Engine card order (solver-engine/src/card.rs): index = rank*4 + suit with\n// ranks 2..A ascending and suits c<d<h<s. Combo strings put the higher card\n// first (\"AsAh\"), so building keys in this order matches the engine's dump\n// byte-for-byte — no normalization needed when joining maps to node hands.\nconst RANK_CHARS = \"23456789TJQKA\";\nconst SUIT_CHARS = \"cdhs\";\n\n/** Engine ordinal of a card string (\"Th\" → 34); -1 when unparsable. */\nexport function cardOrd(card: string): number {\n  if (card.length !== 2) return -1;\n  const r = RANK_CHARS.indexOf(card[0].toUpperCase());\n  const s = SUIT_CHARS.indexOf(card[1].toLowerCase());\n  if (r < 0 || s < 0) return -1;\n  return r * 4 + s;\n}\n\nfunction ordToCard(ord: number): string {\n  return `${RANK_CHARS[ord >> 2]}${SUIT_CHARS[ord & 3]}`;\n}\n\n/** Canonical engine combo key: higher engine-ordinal card first. */\nexport function comboKey(a: string, b: string): string {\n  return cardOrd(a) >= cardOrd(b) ? `${a}${b}` : `${b}${a}`;\n}\n\n/** Per-combo weights keyed by the engine combo string (\"AsAh\"). */\nexport type ComboWeights = Map<string, number>;\n\n/** Split a board string into its card list. */\nexport function boardCards(board: string): string[] {\n  return board.trim().split(/\\s+/).filter(Boolean);\n}\n\nconst WEIGHT_EPS = 5e-4;\n\n/**\n * Expand an NLHE engine range string into per-combo weights, excluding combos\n * that collide with `dead` cards. Supports the grammar our own builders emit:\n * `random`/`100`/`100%`, 169-grid classes (`AA`, `AKs`, `AKo`), and explicit\n * combos (`AsKh`), each with an optional `:weight`.\n */\nexport function expandEngineRange(range: string, dead: ReadonlySet<string>): ComboWeights {\n  const out: ComboWeights = new Map();\n  const blocked = (card: string) => dead.has(card);\n  const set = (a: string, b: string, w: number) => {\n    if (w <= 0 || blocked(a) || blocked(b)) return;\n    out.set(comboKey(a, b), w);\n  };\n\n  const cleaned = range.trim().toLowerCase();\n  if (cleaned === \"random\" || cleaned === \"100\" || cleaned === \"100%\") {\n    for (let hi = 1; hi < 52; hi++) {\n      for (let lo = 0; lo < hi; lo++) set(ordToCard(hi), ordToCard(lo), 1);\n    }\n    return out;\n  }\n\n  for (const raw of range.split(\",\")) {\n    const tok = raw.trim();\n    if (!tok) continue;\n    const [body, weightStr] = splitWeight(tok);\n    const w = weightStr === undefined ? 1 : Number(weightStr);\n    if (!Number.isFinite(w)) throw new Error(`invalid weight in range token \"${tok}\"`);\n\n    // Explicit two-card combo, e.g. \"AhKs\".\n    if (body.length === 4 && isSuit(body[1]) && isSuit(body[3])) {\n      const a = `${body[0].toUpperCase()}${body[1].toLowerCase()}`;\n      const b = `${body[2].toUpperCase()}${body[3].toLowerCase()}`;\n      if (cardOrd(a) < 0 || cardOrd(b) < 0) throw new Error(`bad combo \"${tok}\"`);\n      set(a, b, w);\n      continue;\n    }\n\n    // 169-grid class: \"AA\", \"AKs\", \"AKo\".\n    const r1 = RANK_CHARS.indexOf(body[0]?.toUpperCase() ?? \"\");\n    const r2 = RANK_CHARS.indexOf(body[1]?.toUpperCase() ?? \"\");\n    const suffix = body.slice(2).toLowerCase();\n    if (r1 < 0 || r2 < 0 || (suffix !== \"\" && suffix !== \"s\" && suffix !== \"o\")) {\n      throw new Error(`unsupported range token \"${tok}\"`);\n    }\n    if (r1 === r2) {\n      if (suffix !== \"\") throw new Error(`pairs take no suffix: \"${tok}\"`);\n      for (let s1 = 0; s1 < 4; s1++)\n        for (let s2 = 0; s2 < s1; s2++)\n          set(`${RANK_CHARS[r1]}${SUIT_CHARS[s1]}`, `${RANK_CHARS[r1]}${SUIT_CHARS[s2]}`, w);\n    } else {\n      for (let s1 = 0; s1 < 4; s1++) {\n        for (let s2 = 0; s2 < 4; s2++) {\n          const suited = s1 === s2;\n          if (suffix === \"s\" && !suited) continue;\n          if (suffix === \"o\" && suited) continue;\n          set(`${RANK_CHARS[r1]}${SUIT_CHARS[s1]}`, `${RANK_CHARS[r2]}${SUIT_CHARS[s2]}`, w);\n        }\n      }\n    }\n  }\n  return out;\n}\n\nfunction splitWeight(tok: string): [string, string | undefined] {\n  const i = tok.indexOf(\":\");\n  return i < 0 ? [tok, undefined] : [tok.slice(0, i).trim(), tok.slice(i + 1).trim()];\n}\n\nfunction isSuit(c: string): boolean {\n  return SUIT_CHARS.includes(c.toLowerCase());\n}\n\n/** Serialize combo weights back to the engine grammar (\"AsKh:0.42,…\"). */\nexport function serializeComboRange(weights: ComboWeights): string {\n  const parts: string[] = [];\n  for (const [combo, w] of weights) {\n    if (w < WEIGHT_EPS) continue;\n    parts.push(w >= 0.9995 ? combo : `${combo}:${Number(w.toFixed(4))}`);\n  }\n  return parts.join(\",\");\n}\n\n// ---------------------------------------------------------------------------\n// Node-tree helpers (shared by the viewer's navigation)\n// ---------------------------------------------------------------------------\n\nexport function pathsEqual(a: readonly string[], b: readonly string[]): boolean {\n  return a.length === b.length && a.every((x, i) => x === b[i]);\n}\n\nexport function isPathPrefix(prefix: readonly string[], path: readonly string[]): boolean {\n  return prefix.length <= path.length && prefix.every((x, i) => x === path[i]);\n}\n\nexport function nodeAtPath(nodes: readonly SolverNode[], path: readonly string[]): SolverNode | null {\n  return nodes.find((n) => pathsEqual(n.path, path)) ?? null;\n}\n\n/** The distinct next path segments after `path`, in node order. */\nexport function nextSegments(nodes: readonly SolverNode[], path: readonly string[]): string[] {\n  const seen = new Set<string>();\n  const out: string[] = [];\n  for (const n of nodes) {\n    if (n.path.length <= path.length) continue;\n    if (!isPathPrefix(path, n.path)) continue;\n    const seg = n.path[path.length];\n    if (!seen.has(seg)) {\n      seen.add(seg);\n      out.push(seg);\n    }\n  }\n  return out;\n}\n\n/** The engine's path label for an action (\"Bet 5.6\", \"Call\") — must mirror\n *  `action_path_label` in solver-engine/src/api.rs (add rounded to 1dp). */\nexport function actionSegment(a: SolverActionInfo): string {\n  if (a.add > 0) return `${a.label} ${Math.round(a.add * 10) / 10}`;\n  return a.label;\n}\n\nexport const DEAL_PREFIX = \"deal:\";\n\nexport function isDealSegment(seg: string): boolean {\n  return seg.startsWith(DEAL_PREFIX);\n}\n\nexport function dealCard(seg: string): string {\n  return seg.slice(DEAL_PREFIX.length);\n}\n\n// ---------------------------------------------------------------------------\n// Reach walk\n// ---------------------------------------------------------------------------\n\nexport interface ReachState {\n  /** All cards on the board at this point (start board + dealt runouts). */\n  board: string[];\n  /** Total pot after the last taken action, in chips (= bb). */\n  pot: number;\n  /**\n   * Chips behind each player, assuming equal street contributions — exact at\n   * street boundaries (the only place a child solve is rooted) and at the\n   * start of the walk.\n   */\n  effStack: number;\n  /** Reach-weighted OOP range (root range × taken-action frequencies). */\n  oop: ComboWeights;\n  /** Reach-weighted IP range. */\n  ip: ComboWeights;\n}\n\n/**\n * Walk `path` through a solved bundle and return the reach state at its end.\n * Every action-node prefix of `path` must exist in `result.nodes` (it does for\n * any path the viewer can navigate to); deal segments just filter the ranges.\n */\nexport function walkReach(\n  config: SolveRequest,\n  result: SolverResult,\n  path: readonly string[],\n): ReachState {\n  const nodes = result.nodes ?? [];\n  const board = boardCards(config.board);\n  const dead = new Set(board);\n  const oop = expandEngineRange(config.oop_range, dead);\n  const ip = expandEngineRange(config.ip_range, dead);\n  let pot = config.pot;\n\n  for (let i = 0; i < path.length; i++) {\n    const seg = path[i];\n    if (isDealSegment(seg)) {\n      const card = dealCard(seg);\n      board.push(card);\n      removeBlocked(oop, card);\n      removeBlocked(ip, card);\n      continue;\n    }\n    const node = nodeAtPath(nodes, path.slice(0, i));\n    if (!node) throw new Error(`no strategy node at \"${path.slice(0, i).join(\" › \")}\"`);\n    const idx = node.actions.findIndex((a) => actionSegment(a) === seg);\n    if (idx < 0) throw new Error(`action \"${seg}\" not found at \"${path.slice(0, i).join(\" › \")}\"`);\n    pot = node.pot + node.actions[idx].add;\n\n    const actor = node.player === 0 ? oop : ip;\n    const next: ComboWeights = new Map();\n    for (const hand of node.hands) {\n      const w = actor.get(hand.combo);\n      if (w === undefined || w <= 0) continue;\n      const nw = w * (hand.freqs[idx] ?? 0);\n      if (nw > WEIGHT_EPS) next.set(hand.combo, nw);\n    }\n    if (node.player === 0) {\n      oop.clear();\n      for (const [k, v] of next) oop.set(k, v);\n    } else {\n      ip.clear();\n      for (const [k, v] of next) ip.set(k, v);\n    }\n  }\n\n  const effStack = config.effective_stack - (pot - config.pot) / 2;\n  return { board, pot, effStack, oop, ip };\n}\n\nfunction removeBlocked(weights: ComboWeights, card: string) {\n  const upper = `${card[0].toUpperCase()}${card[1].toLowerCase()}`;\n  for (const combo of [...weights.keys()]) {\n    if (combo.slice(0, 2) === upper || combo.slice(2, 4) === upper) weights.delete(combo);\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Child solve request\n// ---------------------------------------------------------------------------\n\n/** Iteration ceiling for on-demand subgame solves — a turn/river subgame is\n *  tiny next to a flop tree, so the exploitability target stops it long before\n *  this in practice. */\nconst CHILD_MAX_ITERATIONS = 2000;\nconst CHILD_DEFAULT_TARGET = 0.4;\n\n/**\n * Build the `SolveRequest` for the subgame rooted after dealing `card` at the\n * chance node reached by `path` (which must end exactly where a street closed).\n * Ranges are the reach-weighted ranges at that point, minus combos blocked by\n * the new card; geometry (pot / stack) is derived from the taken actions.\n */\nexport function buildChildRequest(\n  config: SolveRequest,\n  result: SolverResult,\n  path: readonly string[],\n  card: string,\n  opts?: {\n    /** CFR-D gadget config (#233) from `resolve-carry.ts`: when present the\n     *  child is a *safe* re-solve (opponent may Terminate for their carried\n     *  CFV), pinned to DCFR — the engine rejects the gadget under pcfr+. */\n    resolve?: ResolveConfig;\n  },\n): SolveRequest {\n  const state = walkReach(config, result, path);\n  if (state.effStack <= 0.01) {\n    throw new Error(\"players are all-in — there are no more decisions to solve\");\n  }\n  if (state.board.includes(card)) throw new Error(`${card} is already on the board`);\n  if (state.board.length >= 5) throw new Error(\"the board is already complete\");\n\n  const oop = new Map(state.oop);\n  const ip = new Map(state.ip);\n  removeBlocked(oop, card);\n  removeBlocked(ip, card);\n  if (oop.size === 0 || ip.size === 0) {\n    throw new Error(`dealing ${card} leaves a player with no hands`);\n  }\n\n  const round2 = (x: number) => Math.round(x * 100) / 100;\n  const req: SolveRequest = {\n    variant: config.variant ?? \"nlhe\",\n    limit: config.limit ?? \"nolimit\",\n    board: [...state.board, card].join(\" \"),\n    pot: round2(state.pot),\n    effective_stack: round2(state.effStack),\n    bet_sizes: config.bet_sizes,\n    add_allin: config.add_allin,\n    max_aggressions: config.max_aggressions,\n    iterations: Math.min(config.iterations || CHILD_MAX_ITERATIONS, CHILD_MAX_ITERATIONS),\n    target_exploitability: config.target_exploitability ?? CHILD_DEFAULT_TARGET,\n    log_interval: 10,\n    dump_ev: true,\n    dump_nodes: true,\n    // One deal of depth: a turn-rooted child carries every river subtree, and a\n    // river-rooted child has no chance nodes at all.\n    dump_max_deals: 1,\n    // Follow the parent: a full-hand drill pack grades turn and river decisions\n    // out of these child solves, so they need per-action EV for the same reason\n    // the flop does. An Explorer re-solve's parent leaves it unset and\n    // pays nothing.\n    ...(config.dump_action_evs ? { dump_action_evs: true } : {}),\n    oop_range: serializeComboRange(oop),\n    ip_range: serializeComboRange(ip),\n  };\n  // Preserve the parent's river action abstraction (#220) so a spliced\n  // subgame bets the same tree the bundle was solved with.\n  if (config.river_bet_sizes && config.river_bet_sizes.length > 0) {\n    req.river_bet_sizes = config.river_bet_sizes;\n  }\n  if (config.river_max_aggressions !== undefined) {\n    req.river_max_aggressions = config.river_max_aggressions;\n  }\n  // Preserve the parent's per-street sizing rules for the streets the child\n  // still contains, so a spliced subgame offers the same tree the bundle was\n  // configured with. Node-specific overrides are dropped: their paths are\n  // relative to the PARENT root and would either miss (engine rejects) or,\n  // worse, silently match a different node in the child tree.\n  if (config.sizing) {\n    const childStreets =\n      state.board.length + 1 === 4 ? ([\"turn\", \"river\"] as const) : ([\"river\"] as const);\n    const inherit: NonNullable<SolveRequest[\"sizing\"]> = {};\n    for (const street of childStreets) {\n      if (config.sizing[street]) inherit[street] = config.sizing[street];\n    }\n    if (Object.keys(inherit).length > 0) req.sizing = inherit;\n  }\n  if (opts?.resolve) {\n    // Safe re-solve: attach the gadget and pin DCFR (the gadget rejects\n    // pcfr+). Snapshots can't combine with the gadget, so none are kept.\n    req.resolve = opts.resolve;\n    req.cfr_variant = \"dcfr\";\n  } else {\n    // No promises available — the child bootstraps on reach ranges. Emit\n    // carry from ITS root so navigation below it can chain safe re-solves,\n    // and keep its snapshot so deeper boundaries can fetch card-*pinned*\n    // promises from `POST /api/solver/jobs/:id/carry` (#233 — a gadget child\n    // can't: the engine rejects snapshots with `resolve`).\n    req.emit_carry_for = 0;\n    req.keep_snapshot = true;\n  }\n  return req;\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/subgame.ts"
    },
    {
      "path": "src/lib/explorer/tree-sim.ts",
      "content": "// Full postflop game-tree expansion for the tree-visualization flow. Mirrors\n// the engine's builder math EXACTLY the way tree-sizing-editor's simulateLine\n// does (same action generation, same state transitions, same node-edit\n// precedence chain) — but walks EVERY branch instead of one chosen line, so\n// React Flow can render the whole tree the solver would build.\n//\n// Chance nodes are collapsed to a single generic \"deal\" step (matching the\n// engine's node-edit path encoding), so the tree stays structural: a turn\n// subtree stands for \"every turn card\", not 49 copies.\n\nimport {\n  parseCellSizes,\n  pathLabel,\n  resolveNode,\n  type NodeEdit,\n  type SimAction,\n  type SizingBase,\n  type SizingGrid,\n  type StreetKey,\n} from \"@/components/explorer/tree-sizing-editor\";\n\nexport type Role = \"oop\" | \"ip\";\nexport type TreeKind = \"action\" | \"chance\" | \"terminal\";\nexport type TerminalKind = \"fold\" | \"showdown\" | \"runout\";\n\nexport interface FullTreeNode {\n  /** Path joined — unique across the tree. */\n  id: string;\n  /** Engine-encoded action path from the root (deals as generic \"deal\"). */\n  path: string[];\n  kind: TreeKind;\n  street: StreetKey;\n  /** Acting player (action nodes only). */\n  role?: Role;\n  /** Pot BEFORE this player acts (action) / final pot (terminal/chance). */\n  pot: number;\n  toCall: number;\n  /** Available actions (action nodes only; parallel to `children`). */\n  actions: SimAction[];\n  /** The node edit applied here, if any. */\n  edit?: NodeEdit;\n  terminal?: TerminalKind;\n  children: { token: string; child: FullTreeNode }[];\n}\n\nexport interface FullTreeStats {\n  actionNodes: number;\n  chanceNodes: number;\n  terminalNodes: number;\n  maxDepth: number;\n}\n\nexport interface FullTree {\n  root: FullTreeNode | null;\n  stats: FullTreeStats;\n  /** True when the node budget ran out — the tree shown is a prefix. */\n  truncated: boolean;\n}\n\nconst STREETS = [\"flop\", \"turn\", \"river\"] as const;\n\ninterface BuildState {\n  streetIdx: number;\n  pot: number;\n  stacks: [number, number];\n  paid: [number, number];\n  toCall: number;\n  player: 0 | 1;\n  aggressions: number;\n  path: string[];\n}\n\nconst sameNodePath = (a: string[], b: string[]) =>\n  a.length === b.length && a.every((t, i) => t === b[i]);\n\nconst idOf = (path: string[], suffix = \"\") =>\n  path.length === 0 && !suffix ? \"root\" : [...path, suffix].filter(Boolean).join(\"|\");\n\n/**\n * Expand the full tree the engine would build for this abstraction. `maxNodes`\n * bounds the walk (bigger abstractions explode combinatorially); when hit,\n * `truncated` is set and the deepest branches are cut.\n */\nexport function buildFullTree(\n  grid: SizingGrid,\n  nodeEdits: NodeEdit[],\n  base: SizingBase,\n  boardCards: number,\n  maxNodes = 4000,\n): FullTree {\n  const startIdx = boardCards >= 5 ? 2 : boardCards === 4 ? 1 : 0;\n  const streets = STREETS.slice(startIdx);\n  const maxAggrFor = (s: StreetKey) =>\n    s === \"river\" ? (base.riverMaxAggressions ?? base.maxAggressions) : base.maxAggressions;\n\n  let budget = maxNodes;\n  let truncated = false;\n  const stats: FullTreeStats = { actionNodes: 0, chanceNodes: 0, terminalNodes: 0, maxDepth: 0 };\n\n  const terminal = (\n    path: string[],\n    street: StreetKey,\n    kind: TerminalKind,\n    pot: number,\n  ): FullTreeNode => {\n    stats.terminalNodes++;\n    stats.maxDepth = Math.max(stats.maxDepth, path.length);\n    return {\n      id: idOf(path, `#${kind}`),\n      path,\n      kind: \"terminal\",\n      street,\n      pot,\n      toCall: 0,\n      actions: [],\n      terminal: kind,\n      children: [],\n    };\n  };\n\n  function build(st: BuildState): FullTreeNode | null {\n    if (budget <= 0) {\n      truncated = true;\n      return null;\n    }\n    budget--;\n\n    const street = streets[st.streetIdx];\n    const role: Role = st.player === 0 ? \"oop\" : \"ip\";\n    const resolved = resolveNode(grid, base, street, role);\n    const edit = nodeEdits.find((e) => sameNodePath(e.path, st.path));\n\n    // Node edit > street rule > base — same chain as the engine / simulateLine.\n    let sizes = st.toCall > 0 ? resolved.raises : resolved.bets;\n    let allin = resolved.allin;\n    if (edit) {\n      try {\n        const s = parseCellSizes(edit.sizes, \"node size\");\n        if (s !== undefined) sizes = s;\n      } catch {\n        /* invalid text — preview falls back to the street rule */\n      }\n      if (edit.allin !== \"auto\") allin = edit.allin === \"on\";\n    }\n\n    const stack = st.stacks[st.player];\n    const actions: SimAction[] = [];\n    const canAggress = st.aggressions < maxAggrFor(street) && stack > st.toCall + 1e-9;\n    if (st.toCall <= 1e-9) {\n      actions.push({ token: \"Check\", label: \"Check\", add: 0 });\n    } else {\n      actions.push({ token: \"Fold\", label: \"Fold\", add: 0 });\n      const callAmt = Math.min(st.toCall, stack);\n      actions.push({ token: pathLabel(\"Call\", callAmt), label: \"Call\", add: callAmt });\n    }\n    if (canAggress) {\n      const potAfterCall = st.pot + st.toCall;\n      for (const f of sizes) {\n        const totalAdd = st.toCall + f * potAfterCall;\n        if (totalAdd >= stack - 1e-9) continue; // shove covers it\n        if (totalAdd <= st.toCall + 1e-9) continue;\n        actions.push({\n          token: pathLabel(st.toCall > 0 ? \"Raise\" : \"Bet\", totalAdd),\n          label: st.toCall > 0 ? \"Raise\" : \"Bet\",\n          add: totalAdd,\n          frac: f,\n        });\n      }\n      if (allin) {\n        actions.push({ token: pathLabel(\"AllIn\", stack), label: \"AllIn\", add: stack });\n      }\n    }\n\n    stats.actionNodes++;\n    stats.maxDepth = Math.max(stats.maxDepth, st.path.length);\n    const node: FullTreeNode = {\n      id: idOf(st.path),\n      path: st.path,\n      kind: \"action\",\n      street,\n      role,\n      pot: st.pot,\n      toCall: st.toCall,\n      actions,\n      edit,\n      children: [],\n    };\n\n    const p = st.player;\n    const o = (1 - p) as 0 | 1;\n\n    for (const act of actions) {\n      const childPath = [...st.path, act.token];\n      let child: FullTreeNode | null = null;\n\n      if (act.label === \"Fold\") {\n        child = terminal(childPath, street, \"fold\", st.pot);\n      } else if (act.label === \"Check\") {\n        if (p === 0) {\n          child = build({ ...st, player: 1, path: childPath });\n        } else if (st.streetIdx + 1 >= streets.length) {\n          child = terminal(childPath, street, \"showdown\", st.pot);\n        } else {\n          child = chance(childPath, st, [st.stacks[0], st.stacks[1]], st.pot);\n        }\n      } else if (act.label === \"Call\") {\n        const stacks: [number, number] = [...st.stacks];\n        stacks[p] -= act.add;\n        const pot = st.pot + act.add;\n        if (stacks[p] <= 1e-9 || stacks[o] <= 1e-9) {\n          child = terminal(childPath, street, \"runout\", pot);\n        } else if (st.streetIdx + 1 >= streets.length) {\n          child = terminal(childPath, street, \"showdown\", pot);\n        } else {\n          child = chance(childPath, st, stacks, pot);\n        }\n      } else {\n        // Bet / Raise / AllIn\n        const stacks: [number, number] = [...st.stacks];\n        stacks[p] -= act.add;\n        const paid: [number, number] = [...st.paid];\n        paid[p] += act.add;\n        child = build({\n          streetIdx: st.streetIdx,\n          pot: st.pot + act.add,\n          stacks,\n          paid,\n          toCall: paid[p] - paid[o],\n          player: o,\n          aggressions: st.aggressions + 1,\n          path: childPath,\n        });\n      }\n\n      if (child) node.children.push({ token: act.token, child });\n    }\n\n    return node;\n  }\n\n  /** Street-closing check/call → a \"deal\" chance node wrapping the next street. */\n  function chance(\n    closedPath: string[],\n    st: BuildState,\n    stacks: [number, number],\n    pot: number,\n  ): FullTreeNode | null {\n    const nextStreet = streets[st.streetIdx + 1];\n    stats.chanceNodes++;\n    const next = build({\n      streetIdx: st.streetIdx + 1,\n      pot,\n      stacks,\n      paid: [0, 0],\n      toCall: 0,\n      player: 0,\n      aggressions: 0,\n      path: [...closedPath, \"deal\"],\n    });\n    const node: FullTreeNode = {\n      id: idOf(closedPath, \"#deal\"),\n      path: closedPath,\n      kind: \"chance\",\n      street: nextStreet,\n      pot,\n      toCall: 0,\n      actions: [],\n      children: next ? [{ token: \"deal\", child: next }] : [],\n    };\n    return node;\n  }\n\n  const root = build({\n    streetIdx: 0,\n    pot: base.potBb,\n    stacks: [base.effStackBb, base.effStackBb],\n    paid: [0, 0],\n    toCall: 0,\n    player: 0,\n    aggressions: 0,\n    path: [],\n  });\n\n  return { root, stats, truncated };\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/tree-sim.ts"
    },
    {
      "path": "src/lib/explorer/types.ts",
      "content": "// Shared types for the Explorer: custom solutions the user builds, solves, and\n// saves. No secrets here — safe to import from both client and server. The\n// server-only Blob read/write lives in `store.ts`.\n\nimport type { SolveRequest, SolverResult } from \"@/lib/solver/types\";\n\n/** Display metadata stored on the row + bundle so the catalog renders without\n *  fetching the (multi-MB) gzipped tree. */\nexport interface CustomSolutionMeta {\n  /** Pot at the start street, in bb (= chips). */\n  potBb: number;\n  /** Effective stack behind, in bb. */\n  effStackBb: number;\n  /** Human bet sizing, e.g. \"75% pot + all-in\". */\n  betSizing: string;\n  /** Out-of-position seat label, e.g. \"OOP\" or \"BB\". */\n  oopLabel: string;\n  /** In-position seat label, e.g. \"IP\" or \"BTN\". */\n  ipLabel: string;\n  /** Start street, derived from the board length. */\n  startStreet: \"flop\" | \"turn\" | \"river\";\n  /** True when solved via the AI (depth-limited) path. AI solves have no\n   *  measurable exploitability — the 0 the engine reports must not be shown\n   *  as if it were a grade. Absent on pre-AI saves. */\n  ai?: boolean;\n}\n\n/** The lightweight catalog entry the Explorer lists (mirrors the DB row, minus\n *  the heavy bundle which is fetched on open). */\nexport interface CustomSolutionSummary {\n  id: string;\n  title: string;\n  variant: \"nlhe\" | \"plo\";\n  kind: \"postflop\";\n  tags: string[];\n  board: string;\n  exploitabilityPct: number;\n  meta: CustomSolutionMeta;\n  createdAt: string;\n  updatedAt: string;\n}\n\n/** The full saved artifact: summary + the solved strategy tree (gzipped on\n *  Blob). `result.nodes` is the `dump_nodes` walk that powers the tree viewer. */\nexport interface CustomSolutionBundle {\n  id: string;\n  title: string;\n  tags: string[];\n  board: string;\n  meta: CustomSolutionMeta;\n  /** The SolveRequest it was solved from (re-open in the builder). */\n  config: SolveRequest;\n  /** The engine output, including the `dump_nodes` walk. */\n  result: SolverResult;\n  generatedAt: string;\n}\n\n/** Body of POST /api/explorer/solutions — the client solves, then saves. */\nexport interface SaveSolutionRequest {\n  title: string;\n  tags: string[];\n  config: SolveRequest;\n  result: SolverResult;\n  meta: CustomSolutionMeta;\n}\n\n/** Body of PATCH /api/explorer/solutions/[id] — rename / retag. */\nexport interface UpdateSolutionRequest {\n  title?: string;\n  tags?: string[];\n}\n\n/** Derive the start street from a board string (\"Qs Jh 2h\" → \"flop\"). */\nexport function streetForBoard(board: string): \"flop\" | \"turn\" | \"river\" {\n  const n = board.trim().split(/\\s+/).filter(Boolean).length;\n  if (n <= 3) return \"flop\";\n  if (n === 4) return \"turn\";\n  return \"river\";\n}\n\n/** Human bet sizing label from the solve config. */\nexport function betSizingLabel(config: SolveRequest): string {\n  const pct = config.bet_sizes.map((b) => `${Math.round(b * 100)}%`).join(\"/\");\n  const base = config.add_allin ? `${pct} pot + all-in` : `${pct} pot`;\n  // Per-street/per-player overrides make the flat summary a lie — say so.\n  return config.sizing ? `${base} · custom tree` : base;\n}\n",
      "type": "registry:lib",
      "target": "lib/explorer/types.ts"
    },
    {
      "path": "src/lib/hand-search/index.ts",
      "content": "/**\n * Hand search: GTO Wizard-style syntax for filtering Omaha (and Hold'em) hands.\n *\n *   AK**            an ace, a king and any two cards (order never matters)\n *   AxKx  AxKy      suit variables: same letter = same suit, different = different\n *   RRON  RROO      rank variables: R/P and O bind ranks (RR = a pair), N = a rank\n *                   that appears once in the hand\n *   [AK]Q  [T-A]s   bracket lists of ranks, rank ranges, suits or exact cards\n *   $ds  $0g  $hp   preflop macros (see PREFLOP_MACROS)\n *   TP  NFD1  >2P   postflop macros and category comparisons (need a board)\n *   a,b  a:b  a!b   union, intersection, difference; !a = every hand but a;\n *   (…)             grouping. `,` binds loosest; `:` and `!` read left to right.\n *\n * Hands are arrays of two-char cards (\"As\", \"Td\"). `parseHandQuery` never\n * throws: bad syntax comes back as `{ ok: false, error, index }` for the UI.\n * Pure and dependency-free so Train, the Explorer and pokerdata.io share one\n * implementation.\n */\n\nimport { categoryIndex, postflopFacts, rankOf, suitOf, type PostflopFacts } from \"./postflop\";\n\nexport { CATEGORIES } from \"./postflop\";\n\n// ── Macros ──────────────────────────────────────────────────────────────────\n\nconst BROADWAY = (r: number) => r >= 8; // T J Q K A\nconst WHEEL = (r: number) => r === 12 || r <= 3; // A 2 3 4 5\n\nfunction rankCounts(hand: string[]): number[] {\n  const c = new Array(13).fill(0);\n  for (const card of hand) c[rankOf(card)]++;\n  return c;\n}\n\n/** Suit groups of the hand, largest first: [[cards of one suit], ...]. */\nfunction suitGroups(hand: string[]): string[][] {\n  const m = new Map<string, string[]>();\n  for (const c of hand) m.set(suitOf(c), [...(m.get(suitOf(c)) ?? []), c]);\n  return [...m.values()].sort((a, b) => b.length - a.length);\n}\n\n/** Smallest total gap across any four distinct ranks of the hand (ace plays\n *  high or low), or Infinity with fewer than four distinct ranks. */\nfunction minGaps(hand: string[]): number {\n  const distinct = [...new Set(hand.map(rankOf))];\n  if (distinct.length < 4) return Infinity;\n  let best = Infinity;\n  const span = (vals: number[]) => {\n    const s = [...vals].sort((a, b) => a - b);\n    return s[3] - s[0] - 3;\n  };\n  const n = distinct.length;\n  for (let a = 0; a < n; a++)\n    for (let b = a + 1; b < n; b++)\n      for (let c = b + 1; c < n; c++)\n        for (let d = c + 1; d < n; d++) {\n          const four = [distinct[a], distinct[b], distinct[c], distinct[d]];\n          best = Math.min(best, span(four));\n          if (four.includes(12)) best = Math.min(best, span(four.map((v) => (v === 12 ? -1 : v))));\n        }\n  return best;\n}\n\nconst pairedRanks = (hand: string[]) =>\n  rankCounts(hand)\n    .map((n, r) => ({ n, r }))\n    .filter((x) => x.n >= 2);\n\nconst isDs = (h: string[]) => suitGroups(h).filter((g) => g.length === 2).length >= 2 && suitGroups(h)[0].length === 2;\nconst isSs = (h: string[]) => suitGroups(h).filter((g) => g.length === 2).length === 1 && suitGroups(h)[0].length === 2;\nconst hasAce = (cards: string[]) => cards.some((c) => rankOf(c) === 12);\nconst suitedPairs = (h: string[]) => suitGroups(h).filter((g) => g.length === 2);\nconst broadwayCount = (h: string[]) => h.filter((c) => BROADWAY(rankOf(c))).length;\n/** Broadway cards beside one ace (other aces count as Broadway). */\nfunction aceSideBroadways(h: string[]): number {\n  const i = h.findIndex((c) => rankOf(c) === 12);\n  if (i < 0) return -1;\n  return broadwayCount(h.filter((_, j) => j !== i));\n}\n\nexport interface MacroDoc {\n  name: string;\n  help: string;\n}\n\nconst PREFLOP: Record<string, { help: string; test: (h: string[]) => boolean }> = {\n  \"0g\": { help: \"Zero-gap rundown: four connected ranks\", test: (h) => minGaps(h) === 0 },\n  \"1g\": { help: \"One-gap rundown: four ranks with one gap\", test: (h) => minGaps(h) === 1 },\n  \"2g\": { help: \"Two-gap rundown: four ranks with two gaps\", test: (h) => minGaps(h) === 2 },\n  b: { help: \"Broadway hands: every card T or higher\", test: (h) => h.every((c) => BROADWAY(rankOf(c))) },\n  dp: { help: \"Two pair: two distinct paired ranks\", test: (h) => pairedRanks(h).length >= 2 },\n  tp: { help: \"Two pair (same as $dp)\", test: (h) => pairedRanks(h).length >= 2 },\n  dsdn: {\n    help: \"Double-suited, double nut: both suited pairs hold an ace\",\n    test: (h) => isDs(h) && suitedPairs(h).every(hasAce),\n  },\n  dsn: { help: \"Double-suited, nut: a suited pair holds an ace\", test: (h) => isDs(h) && suitedPairs(h).some(hasAce) },\n  dsnn: { help: \"Double-suited, non-nut: no ace in either suited pair\", test: (h) => isDs(h) && !suitedPairs(h).some(hasAce) },\n  hp: { help: \"High pair: a pair of TT or higher\", test: (h) => pairedRanks(h).some((p) => p.r >= 8) },\n  mp: { help: \"Middle pair: a pair from 99 to 66\", test: (h) => pairedRanks(h).some((p) => p.r >= 4 && p.r <= 7) },\n  lp: { help: \"Low pair: a pair of 55 or lower\", test: (h) => pairedRanks(h).some((p) => p.r <= 3) },\n  mt: { help: \"Monotone: every card the same suit\", test: (h) => suitGroups(h).length === 1 },\n  np: { help: \"No pairs: every rank different\", test: (h) => pairedRanks(h).length === 0 },\n  nt: { help: \"No trips: no rank three or more times (pairs allowed)\", test: (h) => Math.max(...rankCounts(h)) <= 2 },\n  op: {\n    help: \"One pair only: exactly one paired rank, no trips\",\n    test: (h) => pairedRanks(h).length === 1 && pairedRanks(h)[0].n === 2,\n  },\n  rb: { help: \"Rainbow: every card a different suit\", test: (h) => suitGroups(h).every((g) => g.length === 1) },\n  ssn: { help: \"Single-suited, nut: the suited pair holds an ace\", test: (h) => isSs(h) && suitedPairs(h).some(hasAce) },\n  ssnn: { help: \"Single-suited, non-nut: no ace in the suited pair\", test: (h) => isSs(h) && !suitedPairs(h).some(hasAce) },\n  ts: { help: \"Triple-suited: three cards of one suit\", test: (h) => suitGroups(h)[0].length === 3 },\n  w: { help: \"Wheel hands: every card A, 2, 3, 4 or 5\", test: (h) => h.every((c) => WHEEL(rankOf(c))) },\n  a0b: { help: \"Ace with no Broadway side cards\", test: (h) => aceSideBroadways(h) === 0 },\n  a1b: { help: \"Ace with one Broadway side card\", test: (h) => aceSideBroadways(h) === 1 },\n  a2b: { help: \"Ace with two Broadway side cards\", test: (h) => aceSideBroadways(h) === 2 },\n  a3b: { help: \"Ace with three Broadway side cards\", test: (h) => aceSideBroadways(h) === 3 },\n  \"1b\": { help: \"Exactly one Broadway card\", test: (h) => broadwayCount(h) === 1 },\n  \"2b\": { help: \"Exactly two Broadway cards\", test: (h) => broadwayCount(h) === 2 },\n  \"3b\": { help: \"Exactly three Broadway cards\", test: (h) => broadwayCount(h) === 3 },\n  \"4b\": { help: \"Four Broadway cards\", test: (h) => broadwayCount(h) === 4 },\n  ds: { help: \"Double-suited: two suited pairs\", test: isDs },\n  ss: { help: \"Single-suited: one suited pair, the rest offsuit\", test: isSs },\n};\n\nexport const PREFLOP_MACROS: MacroDoc[] = Object.entries(PREFLOP).map(([k, v]) => ({ name: `$${k}`, help: v.help }));\n\nconst POSTFLOP_HELP: Record<string, string> = {\n  RF: \"Royal flush\",\n  SF: \"Straight flush\",\n  QS: \"Four of a kind\",\n  FH: \"Full house\",\n  FL: \"Any flush\",\n  FLN: \"Nut flush\",\n  FLN2: \"Second-nut flush\",\n  FLNN: \"Flush below the second nut\",\n  STR: \"Any straight\",\n  STRN: \"Nut straight\",\n  STR2: \"Second-nut straight\",\n  STRNN: \"Straight below the second nut\",\n  SET: \"Set: pocket pair plus a board card\",\n  SETT: \"Top set\",\n  SETM: \"Middle set\",\n  SETB: \"Bottom set\",\n  TRIPS: \"Trips: one hole card plus a board pair\",\n  \"2P\": \"Any two pair\",\n  \"2PTT\": \"Top two pair\",\n  \"2PTB\": \"Two pair including top pair\",\n  \"2PB\": \"Other two pair (no top pair)\",\n  PAIR: \"Any pair\",\n  OP: \"Overpair\",\n  TP: \"Top pair\",\n  MP: \"Middle pair\",\n  BP: \"Bottom pair\",\n  UP: \"Underpair\",\n  AIR: \"High card only\",\n};\nconst DRAW_HELP: Record<string, string> = {\n  SFD: \"Straight flush draw\",\n  FD: \"Flush draw (any)\",\n  NFD1: \"Nut flush draw\",\n  NFD2: \"Second-nut flush draw\",\n  FDNN: \"Flush draw below the second nut\",\n  DFD: \"Double flush draw (two suits)\",\n  SD: \"Straight draw (any)\",\n  OESD: \"Open-ender: two ranks complete a straight (8 outs)\",\n  NOESD: \"Nut open-ender: both ranks make the nut straight\",\n  GS: \"Gutshot: one rank completes a straight (4 outs)\",\n  NGS: \"Nut gutshot\",\n  WRAP: \"Wrap: three or more ranks complete a straight, none to the nuts\",\n  NWRAP: \"Nut wrap: three or more ranks, at least one to the nut straight\",\n  BDFD: \"Backdoor flush draw (any, flop only)\",\n  BDFD1: \"One backdoor flush draw\",\n  BDFD2: \"Two backdoor flush draws\",\n  FDB: \"Flush-draw blocker: a card of the suit with two on the board\",\n  SDB: \"Straight-draw blocker: a card whose rank would put a new straight on the board\",\n};\n\nexport const POSTFLOP_MACROS: MacroDoc[] = Object.entries(POSTFLOP_HELP).map(([name, help]) => ({ name, help }));\nexport const DRAW_MACROS: MacroDoc[] = Object.entries(DRAW_HELP).map(([name, help]) => ({ name, help }));\nconst BOARD_WORDS = new Set([...Object.keys(POSTFLOP_HELP), ...Object.keys(DRAW_HELP)]);\n\n// ── AST ─────────────────────────────────────────────────────────────────────\n\ninterface CardToken {\n  /** Allowed ranks (null = any), or a variable. */\n  ranks: Set<number> | null;\n  rankVar: string | null;\n  /** Allowed suits (null = any), or a variable. */\n  suits: Set<string> | null;\n  suitVar: string | null;\n  /** Exact cards from a bracket like [AsKd] (overrides ranks/suits when set). */\n  cards: ((rank: number, suit: string) => boolean) | null;\n}\n\ntype Node =\n  | { kind: \"union\"; items: Node[] }\n  | { kind: \"inter\"; a: Node; b: Node }\n  | { kind: \"diff\"; a: Node; b: Node }\n  | { kind: \"not\"; a: Node }\n  | { kind: \"pattern\"; tokens: CardToken[]; explicitRanks: Set<number> }\n  | { kind: \"pre\"; name: string }\n  | { kind: \"post\"; name: string }\n  | { kind: \"cmp\"; op: \">\" | \"<\"; cat: number };\n\nexport interface HandQuery {\n  source: string;\n  /** True when the query uses a postflop/draw macro or a `>`/`<` comparison. */\n  needsBoard: boolean;\n  /** True when the query names an exact suit (s, h, d, c). Suit-isomorphic\n   *  hand classes then have to be tested suit by suit. */\n  usesExactSuits: boolean;\n  /** Does this concrete hand match? `board` is needed for postflop macros\n   *  (without one they never match). */\n  test(hand: string[], board?: string[]): boolean;\n}\n\nexport type ParseResult = { ok: true; query: HandQuery } | { ok: false; error: string; index: number };\n\nclass ParseError extends Error {\n  constructor(\n    message: string,\n    public index: number,\n  ) {\n    super(message);\n  }\n}\n\n// ── Tokenizer ───────────────────────────────────────────────────────────────\n\ntype Tok = { t: \"op\"; v: string; i: number } | { t: \"word\"; v: string; i: number };\n\nconst OPS = new Set([\",\", \":\", \"!\", \"(\", \")\", \">\", \"<\"]);\n\nfunction tokenize(src: string): Tok[] {\n  const out: Tok[] = [];\n  let i = 0;\n  while (i < src.length) {\n    const ch = src[i];\n    if (/\\s/.test(ch)) {\n      i++;\n      continue;\n    }\n    if (OPS.has(ch)) {\n      out.push({ t: \"op\", v: ch, i });\n      i++;\n      continue;\n    }\n    const start = i;\n    let word = \"\";\n    while (i < src.length && !OPS.has(src[i]) && !/\\s/.test(src[i])) {\n      if (src[i] === \"[\") {\n        const close = src.indexOf(\"]\", i);\n        if (close < 0) throw new ParseError(\"Unclosed [ bracket\", i);\n        word += src.slice(i, close + 1);\n        i = close + 1;\n      } else {\n        word += src[i];\n        i++;\n      }\n    }\n    out.push({ t: \"word\", v: word, i: start });\n  }\n  return out;\n}\n\n// ── Pattern parser ──────────────────────────────────────────────────────────\n\nconst RANK_MAP: Record<string, number> = {};\n\"23456789TJQKA\".split(\"\").forEach((c, i) => {\n  RANK_MAP[c] = i;\n  RANK_MAP[c.toLowerCase()] = i;\n});\nconst SUITS = \"shdc\";\nconst SUIT_VARS = \"wxyz\";\nconst RANK_VARS: Record<string, string> = { R: \"R\", P: \"R\", O: \"O\", N: \"N\", r: \"R\", p: \"R\", o: \"O\", n: \"N\" };\n\nfunction parseBracket(body: string, at: number): { ranks: Set<number> | null; suits: Set<string> | null; cards: CardToken[\"cards\"] } {\n  const items = body.split(\",\").join(\"\");\n  const rankSet = new Set<number>();\n  const suitOnly = new Set<string>();\n  const exact = new Set<string>();\n  let i = 0;\n  if (!items.length) throw new ParseError(\"Empty [ ] list\", at);\n  while (i < items.length) {\n    const c = items[i];\n    if (c in RANK_MAP) {\n      const r = RANK_MAP[c];\n      if (items[i + 1] === \"-\" && items[i + 2] in RANK_MAP) {\n        const r2 = RANK_MAP[items[i + 2]];\n        for (let x = Math.min(r, r2); x <= Math.max(r, r2); x++) rankSet.add(x);\n        i += 3;\n        continue;\n      }\n      if (i + 1 < items.length && SUITS.includes(items[i + 1])) {\n        exact.add(`${r}${items[i + 1]}`);\n        i += 2;\n        continue;\n      }\n      rankSet.add(r);\n      i++;\n      continue;\n    }\n    if (SUITS.includes(c)) {\n      suitOnly.add(c);\n      i++;\n      continue;\n    }\n    throw new ParseError(`\"${c}\" can't go in a [ ] list`, at + 1 + i);\n  }\n  // Only suits: a suit list for the card (any rank).\n  if (rankSet.size === 0 && exact.size === 0) return { ranks: null, suits: suitOnly, cards: null };\n  if (exact.size === 0 && suitOnly.size === 0) return { ranks: rankSet, suits: null, cards: null };\n  // Mixed: any of the listed ranks, suits or exact cards.\n  return {\n    ranks: null,\n    suits: null,\n    cards: (r, s) => rankSet.has(r) || suitOnly.has(s) || exact.has(`${r}${s}`),\n  };\n}\n\nfunction parsePattern(word: string, at: number): Node {\n  const tokens: CardToken[] = [];\n  const explicitRanks = new Set<number>();\n  let nCount = 0;\n  let i = 0;\n  while (i < word.length) {\n    const c = word[i];\n    const tok: CardToken = { ranks: null, rankVar: null, suits: null, suitVar: null, cards: null };\n    if (c === \"*\") {\n      i++;\n    } else if (c in RANK_VARS) {\n      const v = RANK_VARS[c];\n      // Every N is its own unique rank.\n      tok.rankVar = v === \"N\" ? `N${nCount++}` : v;\n      i++;\n    } else if (c in RANK_MAP) {\n      tok.ranks = new Set([RANK_MAP[c]]);\n      explicitRanks.add(RANK_MAP[c]);\n      i++;\n    } else if (c === \"[\") {\n      const close = word.indexOf(\"]\", i);\n      const b = parseBracket(word.slice(i + 1, close), at + i);\n      tok.ranks = b.ranks;\n      tok.suits = b.suits;\n      tok.cards = b.cards;\n      i = close + 1;\n    } else if (c === \"$\") {\n      throw new ParseError(`Unknown macro \"${word}\"`, at);\n    } else {\n      throw new ParseError(\n        SUITS.includes(c) || SUIT_VARS.includes(c)\n          ? `Suit \"${c}\" needs a rank before it (use * for any rank)`\n          : `\"${c}\" isn't a rank, suit or operator`,\n        at + i,\n      );\n    }\n    // Optional suit.\n    const s = word[i];\n    if (s !== undefined) {\n      if (SUITS.includes(s)) {\n        tok.suits = intersectSuits(tok.suits, new Set([s]));\n        i++;\n      } else if (SUIT_VARS.includes(s)) {\n        tok.suitVar = s;\n        i++;\n      } else if (s === \"[\") {\n        const close = word.indexOf(\"]\", i);\n        const body = word.slice(i + 1, close).split(\",\").join(\"\");\n        if (body.length && [...body].every((ch) => SUITS.includes(ch))) {\n          tok.suits = intersectSuits(tok.suits, new Set(body));\n          i = close + 1;\n        }\n      }\n    }\n    tokens.push(tok);\n  }\n  if (tokens.length > 6) throw new ParseError(\"A hand pattern has at most 6 cards\", at);\n  return { kind: \"pattern\", tokens, explicitRanks };\n}\n\nfunction intersectSuits(a: Set<string> | null, b: Set<string>): Set<string> {\n  return a ? new Set([...a].filter((x) => b.has(x))) : b;\n}\n\n// ── Expression parser ───────────────────────────────────────────────────────\n\nfunction parse(src: string): Node {\n  const toks = tokenize(src);\n  let p = 0;\n  const peek = () => toks[p];\n  const isOp = (v: string) => peek()?.t === \"op\" && peek()!.v === v;\n\n  const parseUnion = (): Node => {\n    const items = [parseInter()];\n    while (isOp(\",\")) {\n      p++;\n      items.push(parseInter());\n    }\n    return items.length === 1 ? items[0] : { kind: \"union\", items };\n  };\n  const parseInter = (): Node => {\n    let a = parseUnary();\n    while (isOp(\":\") || isOp(\"!\")) {\n      const op = toks[p++].v;\n      const b = parseUnary();\n      a = op === \":\" ? { kind: \"inter\", a, b } : { kind: \"diff\", a, b };\n    }\n    return a;\n  };\n  const parseUnary = (): Node => {\n    if (isOp(\"!\")) {\n      p++;\n      return { kind: \"not\", a: parseUnary() };\n    }\n    return parsePrimary();\n  };\n  const parsePrimary = (): Node => {\n    const tok = peek();\n    if (!tok) throw new ParseError(\"Expected a hand, macro or (\", src.length);\n    if (tok.t === \"op\") {\n      if (tok.v === \"(\") {\n        p++;\n        const inner = parseUnion();\n        if (!isOp(\")\")) throw new ParseError(\"Missing )\", peek()?.i ?? src.length);\n        p++;\n        return inner;\n      }\n      if (tok.v === \">\" || tok.v === \"<\") {\n        p++;\n        const w = peek();\n        if (!w || w.t !== \"word\") throw new ParseError(`${tok.v} needs a hand category, e.g. ${tok.v}2P`, tok.i);\n        const cat = categoryIndex(w.v);\n        if (cat === undefined) {\n          throw new ParseError(`${tok.v} works with AIR, PAIR, 2P, SET, STR, FL, FH, QS, SF or RF`, w.i);\n        }\n        p++;\n        return { kind: \"cmp\", op: tok.v, cat };\n      }\n      throw new ParseError(`Unexpected \"${tok.v}\"`, tok.i);\n    }\n    p++;\n    if (tok.v.startsWith(\"$\")) {\n      const name = tok.v.slice(1).toLowerCase();\n      if (!(name in PREFLOP)) throw new ParseError(`Unknown macro \"${tok.v}\"`, tok.i);\n      return { kind: \"pre\", name };\n    }\n    if (BOARD_WORDS.has(tok.v)) return { kind: \"post\", name: tok.v };\n    return parsePattern(tok.v, tok.i);\n  };\n\n  if (toks.length === 0) throw new ParseError(\"Empty search\", 0);\n  const node = parseUnion();\n  if (p < toks.length) {\n    const t = toks[p];\n    throw new ParseError(\n      t.t === \"word\" ? `Missing operator before \"${t.v}\" (use , to combine)` : `Unexpected \"${t.v}\"`,\n      t.i,\n    );\n  }\n  return node;\n}\n\n// ── Evaluation ──────────────────────────────────────────────────────────────\n\ninterface Ctx {\n  hand: string[];\n  board: string[] | undefined;\n  facts: PostflopFacts | null | undefined;\n}\n\nfunction factsOf(ctx: Ctx): PostflopFacts | null {\n  if (ctx.facts === undefined) ctx.facts = ctx.board ? postflopFacts(ctx.hand, ctx.board) : null;\n  return ctx.facts;\n}\n\nfunction matchPattern(tokens: CardToken[], explicitRanks: Set<number>, hand: string[]): boolean {\n  if (tokens.length > hand.length) return false;\n  const counts = rankCounts(hand);\n  const used = new Array(hand.length).fill(false);\n  const rankVars = new Map<string, number>();\n  const suitVars = new Map<string, string>();\n\n  const fits = (tok: CardToken, card: string): (() => void) | null => {\n    const r = rankOf(card);\n    const s = suitOf(card);\n    if (tok.cards && !tok.cards(r, s)) return null;\n    if (tok.ranks && !tok.ranks.has(r)) return null;\n    if (tok.suits && !tok.suits.has(s)) return null;\n    let undoRank = false;\n    let undoSuit = false;\n    if (tok.rankVar) {\n      const bound = rankVars.get(tok.rankVar);\n      if (bound === undefined) {\n        if (explicitRanks.has(r)) return null;\n        for (const v of rankVars.values()) if (v === r) return null;\n        if (tok.rankVar.startsWith(\"N\") && counts[r] !== 1) return null;\n        rankVars.set(tok.rankVar, r);\n        undoRank = true;\n      } else if (bound !== r) return null;\n    }\n    if (tok.suitVar) {\n      const bound = suitVars.get(tok.suitVar);\n      if (bound === undefined) {\n        for (const v of suitVars.values()) {\n          if (v === s) {\n            if (undoRank) rankVars.delete(tok.rankVar!);\n            return null;\n          }\n        }\n        suitVars.set(tok.suitVar, s);\n        undoSuit = true;\n      } else if (bound !== s) {\n        if (undoRank) rankVars.delete(tok.rankVar!);\n        return null;\n      }\n    }\n    return () => {\n      if (undoRank) rankVars.delete(tok.rankVar!);\n      if (undoSuit) suitVars.delete(tok.suitVar!);\n    };\n  };\n\n  const go = (k: number): boolean => {\n    if (k === tokens.length) return true;\n    for (let i = 0; i < hand.length; i++) {\n      if (used[i]) continue;\n      const undo = fits(tokens[k], hand[i]);\n      if (!undo) continue;\n      used[i] = true;\n      const ok = go(k + 1);\n      used[i] = false;\n      undo();\n      if (ok) return true;\n    }\n    return false;\n  };\n  return go(0);\n}\n\nfunction evaluate(node: Node, ctx: Ctx): boolean {\n  switch (node.kind) {\n    case \"union\":\n      return node.items.some((n) => evaluate(n, ctx));\n    case \"inter\":\n      return evaluate(node.a, ctx) && evaluate(node.b, ctx);\n    case \"diff\":\n      return evaluate(node.a, ctx) && !evaluate(node.b, ctx);\n    case \"not\":\n      return !evaluate(node.a, ctx);\n    case \"pattern\":\n      return matchPattern(node.tokens, node.explicitRanks, ctx.hand);\n    case \"pre\":\n      return PREFLOP[node.name].test(ctx.hand);\n    case \"post\": {\n      const f = factsOf(ctx);\n      return !!f && f.tags.has(node.name);\n    }\n    case \"cmp\": {\n      const f = factsOf(ctx);\n      if (!f) return false;\n      return node.op === \">\" ? f.category >= node.cat : f.category < node.cat;\n    }\n  }\n}\n\nfunction walk(node: Node, fn: (n: Node) => void) {\n  fn(node);\n  if (node.kind === \"union\") node.items.forEach((n) => walk(n, fn));\n  else if (node.kind === \"inter\" || node.kind === \"diff\") {\n    walk(node.a, fn);\n    walk(node.b, fn);\n  } else if (node.kind === \"not\") walk(node.a, fn);\n}\n\nexport function parseHandQuery(source: string): ParseResult {\n  try {\n    const ast = parse(source);\n    let needsBoard = false;\n    let usesExactSuits = false;\n    walk(ast, (n) => {\n      if (n.kind === \"post\" || n.kind === \"cmp\") needsBoard = true;\n      if (n.kind === \"pattern\" && n.tokens.some((t) => t.suits || t.cards)) usesExactSuits = true;\n    });\n    return {\n      ok: true,\n      query: {\n        source,\n        needsBoard,\n        usesExactSuits,\n        test: (hand, board) => evaluate(ast, { hand, board, facts: undefined }),\n      },\n    };\n  } catch (err) {\n    if (err instanceof ParseError) return { ok: false, error: err.message, index: err.index };\n    throw err;\n  }\n}\n\n// ── Suit-isomorphic hand classes ────────────────────────────────────────────\n\nconst SUIT_PERMS: string[][] = (() => {\n  const out: string[][] = [];\n  const perm = (rest: string[], acc: string[]) => {\n    if (!rest.length) out.push(acc);\n    rest.forEach((s, i) => perm([...rest.slice(0, i), ...rest.slice(i + 1)], [...acc, s]));\n  };\n  perm(SUITS.split(\"\"), []);\n  return out;\n})();\n\n/**\n * Does a suit-isomorphism class match? `cards` is any one member of the class\n * (e.g. from `ploStringToCards`). When the query names exact suits, or a board\n * is given, every suit relabelling of the class is tried and the class matches\n * if any member does; otherwise the representative alone decides.\n */\nexport function matchesHandClass(query: HandQuery, cards: string[], board?: string[]): boolean {\n  if (!query.usesExactSuits && !board) return query.test(cards);\n  const seen = new Set<string>();\n  const blocked = new Set(board ?? []);\n  for (const perm of SUIT_PERMS) {\n    const mapped = cards.map((c) => c[0] + perm[SUITS.indexOf(c[1])]);\n    if (mapped.some((c) => blocked.has(c))) continue;\n    const key = [...mapped].sort().join(\"\");\n    if (seen.has(key)) continue;\n    seen.add(key);\n    if (query.test(mapped, board)) return true;\n  }\n  return false;\n}\n",
      "type": "registry:lib",
      "target": "lib/hand-search/index.ts"
    },
    {
      "path": "src/lib/hand-search/postflop.ts",
      "content": "/**\n * Board-aware hand facts for the hand-search language: made-hand category and\n * its sub-class (top pair, nut flush, ...), draws and blockers.\n *\n * Cards are two-char strings (\"As\", \"Td\"). Ranks are numbered 0 (deuce) to\n * 12 (ace). Omaha rules (exactly two hole cards and three board cards) apply\n * when the hand has four or more cards; with two hole cards any five of the\n * seven play, as in Hold'em.\n *\n * Pure and dependency-free so Train, the Explorer and pokerdata.io can share it.\n */\n\nexport const RANK_CHARS = \"23456789TJQKA\";\nexport const SUIT_CHARS = \"shdc\";\n\nexport function rankOf(card: string): number {\n  return RANK_CHARS.indexOf(card[0]);\n}\nexport function suitOf(card: string): string {\n  return card[1];\n}\n\n/** Top-level made-hand categories, weakest first. `>`/`<` compare on these. */\nexport const CATEGORIES = [\"AIR\", \"PAIR\", \"2P\", \"SET\", \"STR\", \"FL\", \"FH\", \"QS\", \"SF\", \"RF\"] as const;\nexport type Category = (typeof CATEGORIES)[number];\n\nconst CAT_INDEX: Record<string, number> = {\n  AIR: 0,\n  PAIR: 1,\n  \"2P\": 2,\n  SET: 3,\n  TRIPS: 3,\n  STR: 4,\n  FL: 5,\n  FH: 6,\n  QS: 7,\n  SF: 8,\n  RF: 9,\n};\n\n/** Index of a top-level category name (TRIPS and SET share three of a kind). */\nexport function categoryIndex(name: string): number | undefined {\n  return CAT_INDEX[name];\n}\n\n// ── Five-card evaluation ────────────────────────────────────────────────────\n\ninterface Five {\n  /** 0 high card … 8 straight flush (9 = royal, reported separately). */\n  cat: number;\n  value: number;\n  /** For straights: the high rank (3 = five-high wheel). */\n  straightHigh: number;\n  /** For flushes: the flush suit. */\n  flushSuit: string | null;\n  /** Ranks of the made combination (pair rank, trips rank, …), high first. */\n  groups: number[];\n}\n\n// High card, pair, two pair, trips, straight, flush, full house, quads, straight flush.\nconst C_HIGH = 0,\n  C_PAIR = 1,\n  C_2P = 2,\n  C_TRIPS = 3,\n  C_STR = 4,\n  C_FL = 5,\n  C_FH = 6,\n  C_QUADS = 7,\n  C_SF = 8;\n\nfunction straightHighOf(ranks: number[]): number {\n  const set = new Set(ranks);\n  if (set.size !== 5) return -1;\n  const s = [...set].sort((a, b) => b - a);\n  if (s[0] - s[4] === 4) return s[0];\n  // Wheel: A-5-4-3-2.\n  if (s[0] === 12 && s[1] === 3 && s[4] === 0) return 3;\n  return -1;\n}\n\nfunction evalFive(cards: string[]): Five {\n  const ranks = cards.map(rankOf);\n  const suits = cards.map(suitOf);\n  const flush = suits.every((s) => s === suits[0]);\n  const sh = straightHighOf(ranks);\n  const counts = new Map<number, number>();\n  for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);\n  // Groups ordered by count, then rank.\n  const groups = [...counts.entries()].sort((a, b) => b[1] - a[1] || b[0] - a[0]);\n  const shape = groups.map((g) => g[1]).join(\"\");\n  let cat: number;\n  if (sh >= 0 && flush) cat = C_SF;\n  else if (shape === \"41\") cat = C_QUADS;\n  else if (shape === \"32\") cat = C_FH;\n  else if (flush) cat = C_FL;\n  else if (sh >= 0) cat = C_STR;\n  else if (shape === \"311\") cat = C_TRIPS;\n  else if (shape === \"221\") cat = C_2P;\n  else if (shape === \"2111\") cat = C_PAIR;\n  else cat = C_HIGH;\n  const order = sh >= 0 && (cat === C_STR || cat === C_SF) ? [sh] : groups.map((g) => g[0]);\n  let value = cat;\n  for (let i = 0; i < 5; i++) value = value * 13 + (order[i] ?? 0);\n  return {\n    cat,\n    value,\n    straightHigh: cat === C_STR || cat === C_SF ? sh : -1,\n    flushSuit: flush ? suits[0] : null,\n    groups: groups.filter((g) => g[1] >= 2).map((g) => g[0]),\n  };\n}\n\nfunction combos<T>(items: T[], k: number): T[][] {\n  const out: T[][] = [];\n  const pick = (start: number, acc: T[]) => {\n    if (acc.length === k) {\n      out.push(acc);\n      return;\n    }\n    for (let i = start; i <= items.length - (k - acc.length); i++) pick(i + 1, [...acc, items[i]]);\n  };\n  pick(0, []);\n  return out;\n}\n\ninterface Best extends Five {\n  /** The hole cards the best five uses. */\n  holeUsed: string[];\n}\n\nfunction bestHand(hole: string[], board: string[]): Best | null {\n  const omaha = hole.length >= 4;\n  let best: Best | null = null;\n  const consider = (h: string[], b: string[]) => {\n    const f = evalFive([...h, ...b]);\n    if (!best || f.value > best.value) best = { ...f, holeUsed: h };\n  };\n  if (omaha) {\n    if (board.length < 3) return null;\n    for (const h of combos(hole, 2)) for (const b of combos(board, 3)) consider(h, b);\n  } else {\n    const all = [...hole, ...board];\n    if (all.length < 5) return null;\n    for (const five of combos(all, 5)) {\n      const h = five.filter((c) => hole.includes(c));\n      consider(h, five.filter((c) => !hole.includes(c)));\n    }\n  }\n  return best;\n}\n\n// ── Straights by rank only ──────────────────────────────────────────────────\n\n/** Five-rank windows, ace-high first, wheel last. */\nconst WINDOWS: { high: number; ranks: number[] }[] = (() => {\n  const out: { high: number; ranks: number[] }[] = [];\n  for (let high = 12; high >= 4; high--) out.push({ high, ranks: [high, high - 1, high - 2, high - 3, high - 4] });\n  out.push({ high: 3, ranks: [3, 2, 1, 0, 12] });\n  return out;\n})();\n\n/** Highest straight these hole ranks make with these board ranks, or -1. */\nfunction heroStraightHigh(hole: number[], board: number[], omaha: boolean): number {\n  const holeSet = new Set(hole);\n  const boardSet = new Set(board);\n  for (const w of WINDOWS) {\n    if (omaha) {\n      // Two hole ranks + three board ranks covering the window exactly.\n      const fromBoard = w.ranks.filter((r) => boardSet.has(r));\n      if (fromBoard.length < 3) continue;\n      for (const [a, b] of combos(w.ranks, 2)) {\n        if (!holeSet.has(a) || !holeSet.has(b)) continue;\n        if (w.ranks.filter((r) => r !== a && r !== b).every((r) => boardSet.has(r))) return w.high;\n      }\n    } else if (w.ranks.every((r) => holeSet.has(r) || boardSet.has(r))) {\n      // Hold'em: the board alone counts only if a hole card could be swapped in,\n      // which it always can, so any cover is a straight.\n      return w.high;\n    }\n  }\n  return -1;\n}\n\n/** Straight highs possible on a board for some holding, best first. */\nfunction possibleStraightHighs(board: number[]): number[] {\n  const boardSet = new Set(board);\n  return WINDOWS.filter((w) => w.ranks.filter((r) => boardSet.has(r)).length >= 3).map((w) => w.high);\n}\n\n// ── Facts ───────────────────────────────────────────────────────────────────\n\nexport interface PostflopFacts {\n  /** Index into CATEGORIES. */\n  category: number;\n  /** Every made-hand and draw macro this hand satisfies. */\n  tags: Set<string>;\n}\n\n/** Nut rank of a flush: 0 = nut, 1 = second nut, 2 = lower, by the hero's top\n *  hole card of the suit against the ranks of that suit not on the board. */\nfunction flushNutLevel(hole: string[], board: string[], suit: string): number {\n  const onBoard = new Set(board.filter((c) => suitOf(c) === suit).map(rankOf));\n  const available: number[] = [];\n  for (let r = 12; r >= 0; r--) if (!onBoard.has(r)) available.push(r);\n  const top = Math.max(-1, ...hole.filter((c) => suitOf(c) === suit).map(rankOf));\n  const idx = available.indexOf(top);\n  return idx < 0 ? 2 : Math.min(idx, 2);\n}\n\nexport function postflopFacts(hole: string[], board: string[]): PostflopFacts | null {\n  if (board.length < 3 || board.length > 5) return null;\n  const best = bestHand(hole, board);\n  if (!best) return null;\n  const omaha = hole.length >= 4;\n  const tags = new Set<string>();\n  const boardRanks = board.map(rankOf);\n  const distinctBoard = [...new Set(boardRanks)].sort((a, b) => b - a);\n  const top = distinctBoard[0];\n  const bottom = distinctBoard[distinctBoard.length - 1];\n  const holeHas = (r: number) => best.holeUsed.some((c) => rankOf(c) === r);\n\n  let category: number;\n  switch (best.cat) {\n    case C_SF:\n      category = best.straightHigh === 12 ? 9 : 8;\n      tags.add(\"SF\");\n      if (category === 9) tags.add(\"RF\");\n      break;\n    case C_QUADS:\n      category = 7;\n      tags.add(\"QS\");\n      break;\n    case C_FH:\n      category = 6;\n      tags.add(\"FH\");\n      break;\n    case C_FL: {\n      category = 5;\n      tags.add(\"FL\");\n      const lvl = flushNutLevel(best.holeUsed, board, best.flushSuit!);\n      tags.add(lvl === 0 ? \"FLN\" : lvl === 1 ? \"FLN2\" : \"FLNN\");\n      break;\n    }\n    case C_STR: {\n      category = 4;\n      tags.add(\"STR\");\n      const idx = possibleStraightHighs(boardRanks).indexOf(best.straightHigh);\n      tags.add(idx === 0 ? \"STRN\" : idx === 1 ? \"STR2\" : \"STRNN\");\n      break;\n    }\n    case C_TRIPS: {\n      category = 3;\n      const t = best.groups[0];\n      const fromHole = best.holeUsed.filter((c) => rankOf(c) === t).length;\n      if (fromHole >= 2) {\n        tags.add(\"SET\");\n        if (t === top) tags.add(\"SETT\");\n        else if (t === bottom) tags.add(\"SETB\");\n        else tags.add(\"SETM\");\n      } else if (fromHole === 1) {\n        tags.add(\"TRIPS\");\n      }\n      break;\n    }\n    case C_2P: {\n      category = 2;\n      tags.add(\"2P\");\n      const [hi, lo] = best.groups;\n      const made = (r: number) => boardRanks.includes(r) && holeHas(r);\n      const second = distinctBoard[1];\n      if (made(top) && second !== undefined && made(second) && (hi === top || lo === top) && (hi === second || lo === second)) {\n        tags.add(\"2PTT\");\n      }\n      if (made(top) && (hi === top || lo === top) && made(hi === top ? lo : hi)) tags.add(\"2PTB\");\n      else tags.add(\"2PB\");\n      break;\n    }\n    case C_PAIR: {\n      category = 1;\n      tags.add(\"PAIR\");\n      const p = best.groups[0];\n      const holeCount = best.holeUsed.filter((c) => rankOf(c) === p).length;\n      if (holeCount === 2 && !boardRanks.includes(p)) {\n        if (p > top) tags.add(\"OP\");\n        else if (p < bottom) tags.add(\"UP\");\n      } else if (holeCount >= 1) {\n        if (p === top) tags.add(\"TP\");\n        else if (p === bottom) tags.add(\"BP\");\n        else tags.add(\"MP\");\n      }\n      break;\n    }\n    default:\n      category = 0;\n      tags.add(\"AIR\");\n  }\n\n  // Draws only exist with cards to come.\n  if (board.length < 5) addDraws(hole, board, omaha, best, tags);\n  addBlockers(hole, board, tags);\n  return { category, tags };\n}\n\nfunction suitCount(cards: string[], s: string): number {\n  return cards.filter((c) => suitOf(c) === s).length;\n}\n\nfunction addDraws(hole: string[], board: string[], omaha: boolean, best: Best, tags: Set<string>) {\n  // Flush draws: one more card of the suit completes a flush.\n  let fdSuits = 0;\n  for (const s of SUIT_CHARS) {\n    const h = suitCount(hole, s);\n    const b = suitCount(board, s);\n    const isFd = omaha ? h >= 2 && b === 2 : h >= 1 && h + b === 4 && b <= 3;\n    if (!isFd) continue;\n    fdSuits++;\n    tags.add(\"FD\");\n    const lvl = flushNutLevel(hole, board, s);\n    tags.add(lvl === 0 ? \"NFD1\" : lvl === 1 ? \"NFD2\" : \"FDNN\");\n  }\n  if (fdSuits >= 2) tags.add(\"DFD\");\n\n  // Backdoor flush draws: flop only, two more of the suit needed.\n  if (board.length === 3) {\n    let bd = 0;\n    for (const s of SUIT_CHARS) {\n      const h = suitCount(hole, s);\n      const b = suitCount(board, s);\n      if (omaha ? h >= 2 && b === 1 : h >= 1 && h + b === 3) bd++;\n    }\n    if (bd >= 1) tags.add(\"BDFD\");\n    if (bd === 1) tags.add(\"BDFD1\");\n    if (bd >= 2) tags.add(\"BDFD2\");\n  }\n\n  const seen = new Set([...hole, ...board]);\n  const unseen: string[] = [];\n  for (const r of RANK_CHARS) for (const s of SUIT_CHARS) if (!seen.has(r + s)) unseen.push(r + s);\n\n  // Straight-flush draw: some card to come makes a straight flush.\n  if (best.cat < C_SF) {\n    for (const c of unseen) {\n      const nb = bestHand(hole, [...board, c]);\n      if (nb && nb.cat === C_SF) {\n        tags.add(\"SFD\");\n        break;\n      }\n    }\n  }\n\n  // Straight draws, by the ranks that complete one (no draw if already made).\n  const holeRanks = hole.map(rankOf);\n  const boardRanks = board.map(rankOf);\n  if (heroStraightHigh(holeRanks, boardRanks, omaha) >= 0) return;\n  const unseenByRank = new Array(13).fill(0);\n  for (const c of unseen) unseenByRank[rankOf(c)]++;\n  let outRanks = 0;\n  let nutRanks = 0;\n  for (let r = 0; r < 13; r++) {\n    if (unseenByRank[r] === 0) continue;\n    const nb = [...boardRanks, r];\n    const high = heroStraightHigh(holeRanks, nb, omaha);\n    if (high < 0) continue;\n    outRanks++;\n    if (possibleStraightHighs(nb)[0] === high) nutRanks++;\n  }\n  if (outRanks === 0) return;\n  tags.add(\"SD\");\n  if (outRanks === 1) {\n    tags.add(\"GS\");\n    if (nutRanks === 1) tags.add(\"NGS\");\n  } else if (outRanks === 2) {\n    tags.add(\"OESD\");\n    if (nutRanks === 2) tags.add(\"NOESD\");\n  } else {\n    tags.add(nutRanks > 0 ? \"NWRAP\" : \"WRAP\");\n  }\n}\n\nfunction addBlockers(hole: string[], board: string[], tags: Set<string>) {\n  if (board.length >= 5) return;\n  // Flush-draw blocker: a card of a suit with exactly two on the board.\n  for (const s of SUIT_CHARS) {\n    if (suitCount(board, s) === 2 && suitCount(hole, s) >= 1) {\n      tags.add(\"FDB\");\n      break;\n    }\n  }\n  // Straight-draw blocker: holds a rank that would let a new straight onto\n  // the board if it came (an out for the straight draws out there).\n  const boardRanks = board.map(rankOf);\n  const before = new Set(possibleStraightHighs(boardRanks));\n  for (const c of hole) {\n    const r = rankOf(c);\n    if (boardRanks.includes(r)) continue;\n    if (possibleStraightHighs([...boardRanks, r]).some((h) => !before.has(h))) {\n      tags.add(\"SDB\");\n      break;\n    }\n  }\n}\n",
      "type": "registry:lib",
      "target": "lib/hand-search/postflop.ts"
    },
    {
      "path": "src/lib/nl-ranges/range.ts",
      "content": "/**\n * A preflop range as the solver exports it: a map from 169 hand-classes\n * (\"AA\", \"AKs\", \"AKo\", …) to a weight in [0, 1] — the frequency with which a\n * given action is taken with that class.\n *\n * Stored on the 169-grid (not expanded to 1326 concrete combos). Combo math is\n * derived lazily: a pair is 6 combos, a suited class 4, an offsuit class 12.\n * If you ever need card-removal against known cards, expand at the call site.\n */\n\nconst RANKS = \"AKQJT98765432\";\n\n/** Concrete combos a 169-grid class represents, ignoring card removal. */\nexport function comboCount(hand: string): number {\n  if (hand.length === 2) {\n    // pair: two equal ranks, e.g. \"AA\", \"22\"\n    return hand[0] === hand[1] && RANKS.includes(hand[0]) ? 6 : 0;\n  }\n  if (hand.length === 3 && RANKS.includes(hand[0]) && RANKS.includes(hand[1])) {\n    if (hand[2] === \"s\") return 4; // suited: \"AKs\"\n    if (hand[2] === \"o\") return 12; // offsuit: \"AKo\"\n  }\n  return 0; // unrecognized label\n}\n\nexport class Range {\n  /** hand-class → weight in [0, 1]. Includes 0-weight entries verbatim. */\n  readonly weights: ReadonlyMap<string, number>;\n  /** hand-class → EV in small blinds, when the bundle carries it (v2+). */\n  readonly evs: ReadonlyMap<string, number>;\n  /** Original CSV exactly as stored (e.g. \"AA:1.0,A2s:0.0,…\"). */\n  readonly raw: string;\n\n  constructor(\n    weights: Map<string, number>,\n    raw: string,\n    evs: Map<string, number> = new Map(),\n  ) {\n    this.weights = weights;\n    this.evs = evs;\n    this.raw = raw;\n  }\n\n  /**\n   * Parse a stored range CSV. Each entry is \"hand:freq\" (v1 bundles) or\n   * \"hand:freq:ev\" (v2 bundles carry EV in small blinds). NL hand-classes\n   * (\"AA\", \"AKs\", \"AKo\") never contain `:`, so the first `:` splits the hand\n   * from its values and an optional second `:` splits freq from EV. Malformed\n   * pairs are skipped. Tolerant of both formats for safe rollout.\n   */\n  static parse(raw: string): Range {\n    const weights = new Map<string, number>();\n    const evs = new Map<string, number>();\n    for (const part of raw.split(\",\")) {\n      const s = part.trim();\n      if (!s) continue;\n      const i = s.indexOf(\":\");\n      if (i === -1) continue;\n      const hand = s.slice(0, i).trim();\n      const rest = s.slice(i + 1);\n      const j = rest.indexOf(\":\");\n      const w = Number(j === -1 ? rest : rest.slice(0, j));\n      if (!hand || Number.isNaN(w)) continue;\n      weights.set(hand, w);\n      if (j !== -1) {\n        const ev = Number(rest.slice(j + 1));\n        if (!Number.isNaN(ev)) evs.set(hand, ev);\n      }\n    }\n    return new Range(weights, raw, evs);\n  }\n\n  /** Build a range from an explicit weight map (no raw source). */\n  static from(weights: Map<string, number>): Range {\n    const raw = [...weights].map(([h, w]) => `${h}:${w}`).join(\",\");\n    return new Range(weights, raw);\n  }\n\n  /** Weight of a single class (0 if absent). */\n  freq(hand: string): number {\n    return this.weights.get(hand) ?? 0;\n  }\n\n  /** EV (small blinds) of a single class, or undefined if not carried. */\n  ev(hand: string): number | undefined {\n    return this.evs.get(hand);\n  }\n\n  /** Classes with weight strictly above `minFreq`, in stored order. */\n  hands(minFreq = 0): string[] {\n    const out: string[] = [];\n    for (const [hand, w] of this.weights) if (w > minFreq) out.push(hand);\n    return out;\n  }\n\n  /** Weighted concrete-combo count (Σ weight × comboCount). */\n  combos(): number {\n    let total = 0;\n    for (const [hand, w] of this.weights) total += w * comboCount(hand);\n    return total;\n  }\n\n  /** Plain object view (handy for JSON / snapshots). */\n  toObject(): Record<string, number> {\n    return Object.fromEntries(this.weights);\n  }\n\n  /**\n   * Combine ranges by summing per-class weights, clamped to [0, 1]. Used to\n   * collapse a node's non-fold actions into one \"continuing\" range: a class's\n   * continue frequency is the sum of its frequencies across each action.\n   */\n  static union(ranges: Range[]): Range {\n    const merged = new Map<string, number>();\n    for (const r of ranges) {\n      for (const [hand, w] of r.weights) {\n        merged.set(hand, Math.min(1, (merged.get(hand) ?? 0) + w));\n      }\n    }\n    return Range.from(merged);\n  }\n}\n",
      "type": "registry:lib",
      "target": "lib/nl-ranges/range.ts"
    },
    {
      "path": "src/lib/plo-ranges/combos.ts",
      "content": "/**\n * Expand MonkerSolver suit-grouping hand classes into the concrete four-card\n * combos the native solver's PLO range grammar expects.\n *\n * The PLO ranges store keeps weights on 16,432 suit-isomorphic hand classes\n * written in MonkerSolver notation (parentheses wrap cards sharing a suit), e.g.\n *\n *     AAAA       four aces, each a different suit          → 1 concrete combo\n *     (2A)AA     A-A-A-2, the 2 suited to one ace          → 12 concrete combos\n *     (KA)(KA)   A-A-K-K double-suited                     → 36 concrete combos\n *     AKQJ       four broadways, all different suits        → 256 concrete combos\n *\n * The solver engine (`solver-engine/src/range.rs::parse_plo`) only accepts\n * `random` or an explicit comma-list of concrete combos like `AhKhQsJs:0.5`. To\n * feed real preflop ranges to the solver we must expand each class into its\n * concrete combos.\n *\n * Doing this by reasoning about suit permutations per pattern is error-prone, so\n * instead we enumerate all C(52,4) = 270,725 concrete combos once, compute each\n * one's suit-isomorphism *signature* with the exact same algorithm used to parse\n * the MonkerSolver strings (ported from `mobile/src/lib/trainer/plo-hand.ts`),\n * and build a `signature → combos` index. Expanding a class is then a lookup:\n * its signature is computed the same way, so the mapping is correct by\n * construction. See `combos.test.ts` for the correctness gate.\n */\n\n// Ranks high→low so a lower index means a higher rank — matches the trainer's\n// `rankIndex` (mobile/src/lib/trainer/hand.ts). Within a group the canonical\n// order is ascending by index, i.e. highest rank written first (\"A2\", \"AKQJ\").\nconst RANKS = \"AKQJT98765432\";\nconst SUITS = [\"c\", \"d\", \"h\", \"s\"] as const;\n\nfunction rankIndex(r: string): number {\n  return RANKS.indexOf(r);\n}\n\n/** Sort rank chars ascending by index (highest rank first). */\nfunction sortRanks(ranks: string[]): string[] {\n  return [...ranks].sort((a, b) => rankIndex(a) - rankIndex(b));\n}\n\nfunction compareRankStr(a: string, b: string): number {\n  const n = Math.min(a.length, b.length);\n  for (let i = 0; i < n; i++) {\n    const d = rankIndex(a[i]) - rankIndex(b[i]);\n    if (d !== 0) return d;\n  }\n  return a.length - b.length;\n}\n\n/**\n * Order-independent signature of a hand's suit partition. Two hands are\n * suit-isomorphic iff their signatures match. Groups (cards sharing a suit) are\n * sorted by size desc, then by rank, so the form is canonical regardless of\n * which actual suits are used. Identical to the trainer's `signature`.\n */\nfunction signature(groups: string[][]): string {\n  return groups\n    .map((g) => g.join(\"\"))\n    .sort((a, b) => b.length - a.length || compareRankStr(a, b))\n    .join(\"/\");\n}\n\n/** Parse a MonkerSolver class string into suit groups (parens = same suit). */\nexport function parseHandString(s: string): string[][] {\n  const groups: string[][] = [];\n  let i = 0;\n  while (i < s.length) {\n    if (s[i] === \"(\") {\n      const j = s.indexOf(\")\", i);\n      if (j === -1) throw new Error(`unbalanced '(' in hand class \"${s}\"`);\n      groups.push(sortRanks(s.slice(i + 1, j).split(\"\")));\n      i = j + 1;\n    } else {\n      groups.push([s[i]]);\n      i += 1;\n    }\n  }\n  return groups;\n}\n\n/** Signature of a MonkerSolver class string. */\nexport function signatureOfClass(s: string): string {\n  return signature(parseHandString(s));\n}\n\n// ─── signature → concrete combos index ─────────────────────────────────────\n\n/** All 52 cards as \"<rank><suit>\" strings (e.g. \"Ah\"). */\nfunction allCards(): string[] {\n  const cards: string[] = [];\n  for (const r of RANKS) for (const s of SUITS) cards.push(`${r}${s}`);\n  return cards;\n}\n\n/** Signature of a concrete 4-card combo (group its cards by suit). */\nexport function signatureOfCombo(cards: string[]): string {\n  const bySuit = new Map<string, string[]>();\n  for (const c of cards) {\n    const arr = bySuit.get(c[1]);\n    if (arr) arr.push(c[0]);\n    else bySuit.set(c[1], [c[0]]);\n  }\n  const groups = [...bySuit.values()].map(sortRanks);\n  return signature(groups);\n}\n\nlet INDEX: Map<string, string[]> | null = null;\n\n/**\n * Build (once) the `signature → concrete-combo strings` index over all 270,725\n * four-card combos. Each combo string is the engine's explicit form, e.g.\n * \"AhKhQsJs\" (rank+suit per card). Cached for the lifetime of the process.\n */\nfunction comboIndex(): Map<string, string[]> {\n  if (INDEX) return INDEX;\n  const cards = allCards();\n  const index = new Map<string, string[]>();\n  const n = cards.length;\n  for (let a = 0; a < n; a++) {\n    for (let b = a + 1; b < n; b++) {\n      for (let c = b + 1; c < n; c++) {\n        for (let d = c + 1; d < n; d++) {\n          const combo = [cards[a], cards[b], cards[c], cards[d]];\n          const sig = signatureOfCombo(combo);\n          const bucket = index.get(sig);\n          const str = combo.join(\"\");\n          if (bucket) bucket.push(str);\n          else index.set(sig, [str]);\n        }\n      }\n    }\n  }\n  INDEX = index;\n  return index;\n}\n\n/** The concrete combos for a single MonkerSolver class, e.g. \"(2A)AA\". */\nexport function combosForClass(handClass: string): string[] {\n  return comboIndex().get(signatureOfClass(handClass)) ?? [];\n}\n\n/** Every four-card combo: C(52,4). The denominator for range percentages. */\nexport const TOTAL_PLO_COMBOS = 270725;\n\nlet COUNTS: Map<string, number> | null = null;\n\n/**\n * `signature → concrete-combo count`. Same enumeration as `comboIndex()` but\n * keeps only the counts (~16k numbers rather than 270,725 strings), which is\n * all the range-weighting math needs — a full index costs ~145MB of resident\n * memory in a function that only wants to divide by 270,725.\n */\nfunction comboCounts(): Map<string, number> {\n  if (COUNTS) return COUNTS;\n  const cards = allCards();\n  const counts = new Map<string, number>();\n  const n = cards.length;\n  for (let a = 0; a < n; a++) {\n    for (let b = a + 1; b < n; b++) {\n      for (let c = b + 1; c < n; c++) {\n        for (let d = c + 1; d < n; d++) {\n          const sig = signatureOfCombo([cards[a], cards[b], cards[c], cards[d]]);\n          counts.set(sig, (counts.get(sig) ?? 0) + 1);\n        }\n      }\n    }\n  }\n  COUNTS = counts;\n  return counts;\n}\n\n/**\n * How many concrete combos a MonkerSolver class covers, e.g. \"AAAA\" → 1,\n * \"(2A)AA\" → 12. Weighting a range's classes by this is what turns a class\n * count into a comparable \"% of all hands\" (the PLO analogue of NL's VPIP).\n */\nexport function comboCountForClass(handClass: string): number {\n  return comboCounts().get(signatureOfClass(handClass)) ?? 0;\n}\n\n/**\n * The same count as `comboCountForClass`, worked out from the class string\n * instead of by enumerating all 270,725 combos, so client code can weight by\n * combos without a half-second warm-up. Each suit group takes a distinct suit:\n * 4!/(4-g)! ways for g groups, divided by the orderings of identical groups\n * (\"(2A)AA\" → 24 / 2! = 12, \"AAAA\" → 24 / 4! = 1). `combos.test.ts` checks it\n * against the enumeration for every class.\n */\nexport function classComboCount(handClass: string): number {\n  let groups: string[][];\n  try {\n    groups = parseHandString(handClass);\n  } catch {\n    return 0;\n  }\n  const g = groups.length;\n  if (g === 0 || g > 4) return 0;\n  let ways = 1;\n  for (let i = 0; i < g; i++) ways *= 4 - i;\n  const same = new Map<string, number>();\n  for (const grp of groups) {\n    const k = grp.join(\"\");\n    same.set(k, (same.get(k) ?? 0) + 1);\n  }\n  for (const m of same.values()) for (let i = 2; i <= m; i++) ways /= i;\n  return ways;\n}\n\n// ─── range expansion ───────────────────────────────────────────────────────\n\n/** A token already in the engine's explicit form: 4 rank+suit pairs. */\nconst EXPLICIT_COMBO = /^[2-9TJQKA][cdhs][2-9TJQKA][cdhs][2-9TJQKA][cdhs][2-9TJQKA][cdhs]$/i;\n\n/**\n * Expand a PLO range expressed over MonkerSolver hand classes into the engine's\n * explicit-combo grammar.\n *\n * Input is a comma-list of `class[:weight]` tokens (the same CSV the ranges\n * store serves, e.g. `AAAA:1,(2A)AA:0.5`). `random`/`100` pass straight through.\n * Tokens already in explicit-combo form (`AhKhQsJs`) are passed through too, so\n * power users can hand-write combos. Every concrete combo of a class inherits\n * the class weight; weight-1 combos are emitted bare and weighted combos as\n * `combo:weight`. Unknown classes that expand to nothing are skipped.\n *\n * Returns the engine range string. Throws on a malformed weight.\n */\nexport function expandMonkerRange(spec: string): string {\n  const cleaned = spec.trim().toLowerCase();\n  if (cleaned === \"\" || cleaned === \"random\" || cleaned === \"100\" || cleaned === \"100%\") {\n    return \"random\";\n  }\n\n  const parts: string[] = [];\n  for (const raw of spec.split(\",\")) {\n    const tok = raw.trim();\n    if (!tok) continue;\n\n    const colon = tok.indexOf(\":\");\n    const body = colon === -1 ? tok : tok.slice(0, colon).trim();\n    let weight = 1;\n    if (colon !== -1) {\n      // A class CSV may carry \"class:freq:ev\"; only the first value is the weight.\n      const w = Number(tok.slice(colon + 1).split(\":\")[0].trim());\n      if (!Number.isFinite(w)) throw new Error(`invalid weight in \"${tok}\"`);\n      weight = w;\n    }\n    if (weight <= 0) continue;\n\n    if (EXPLICIT_COMBO.test(body)) {\n      parts.push(weight >= 0.999 ? body : `${body}:${round(weight)}`);\n      continue;\n    }\n\n    const combos = combosForClass(body);\n    for (const combo of combos) {\n      parts.push(weight >= 0.999 ? combo : `${combo}:${round(weight)}`);\n    }\n  }\n  return parts.join(\",\");\n}\n\nfunction round(w: number): number {\n  return Number(w.toFixed(3));\n}\n",
      "type": "registry:lib",
      "target": "lib/plo-ranges/combos.ts"
    },
    {
      "path": "src/lib/plo5-ranges/canonical.ts",
      "content": "/**\n * Five-card Omaha combos as this HydraSolver export stores them: 10 characters,\n * ranks then suits, cards sorted by rank (2–A) then suit (s, h, d, c).\n *\n * Sample stored spelling: `2s2h2d2c3s`. User input (`Ah Kd Kc Qs 2s`, `ahkd…`)\n * has to land on the same string, or a suit-isomorph of it, or a lookup misses\n * a hand that is actually in the tree.\n *\n * The pack is a 204k HDV bucket-map, not the 2.6M combinadic space. Preflop,\n * suit relabelings are the same game — `hdvOrbit` tries the user's spelling\n * first, then the other ≤23 suit permutations.\n */\n\nconst RANK_HI = \"AKQJT98765432\";\nconst RANK_ORDER = \"23456789TJQKA\";\nconst SUIT_ORDER = \"shdc\";\n\nconst RANK_VALUE: Record<string, number> = Object.fromEntries(\n  [...RANK_ORDER].map((r, i) => [r, i]),\n);\nconst SUIT_VALUE: Record<string, number> = Object.fromEntries(\n  [...SUIT_ORDER].map((s, i) => [s, i]),\n);\n\nexport function comboStrength(hand: string): number {\n  let s = 0;\n  for (let i = 0; i + 1 < hand.length; i += 2) {\n    s += RANK_VALUE[hand[i].toUpperCase()] ?? 0;\n  }\n  return s;\n}\n\nconst SUIT_CHARS = new Set([\"s\", \"h\", \"d\", \"c\", \"S\", \"H\", \"D\", \"C\"]);\n\n/**\n * Rank multiset from a typed filter. `AK222` and `AsKh2d2c2s` both become\n * {A:1, K:1, 2:3}. Returns null when the string isn't 1–5 ranks.\n */\nexport function parsePlo5RankFilter(input: string): Record<string, number> | null {\n  const compact = input.replace(/[\\s,]+/g, \"\");\n  if (!compact) return null;\n  const ranks: string[] = [];\n  let i = 0;\n  while (i < compact.length) {\n    const r = compact[i].toUpperCase();\n    if (RANK_VALUE[r] === undefined) return null;\n    ranks.push(r);\n    i++;\n    if (i < compact.length && SUIT_CHARS.has(compact[i])) i++;\n  }\n  if (ranks.length < 1 || ranks.length > 5) return null;\n  const counts: Record<string, number> = {};\n  for (const r of ranks) counts[r] = (counts[r] ?? 0) + 1;\n  return counts;\n}\n\nexport function handRankCounts(hand: string): Record<string, number> {\n  const compact = hand.replace(/[\\s,]+/g, \"\");\n  const counts: Record<string, number> = {};\n  for (let i = 0; i + 1 < compact.length; i += 2) {\n    const r = compact[i].toUpperCase();\n    counts[r] = (counts[r] ?? 0) + 1;\n  }\n  return counts;\n}\n\n/** Five ranks → exact bag. Fewer ranks → hand must include at least those counts. */\nexport function handMatchesRankFilter(hand: string, filter: Record<string, number>): boolean {\n  const have = handRankCounts(hand);\n  const needed = Object.values(filter).reduce((s, n) => s + n, 0);\n  if (needed >= 5) {\n    const keys = new Set([...Object.keys(have), ...Object.keys(filter)]);\n    for (const k of keys) if ((have[k] ?? 0) !== (filter[k] ?? 0)) return false;\n    return true;\n  }\n  for (const [r, n] of Object.entries(filter)) {\n    if ((have[r] ?? 0) < n) return false;\n  }\n  return true;\n}\n\nexport function encodePlo5RankFilter(filter: Record<string, number>): string {\n  return Object.entries(filter)\n    .sort((a, b) => RANK_HI.indexOf(a[0]) - RANK_HI.indexOf(b[0]))\n    .map(([r, n]) => r.repeat(n))\n    .join(\"\");\n}\n\n/** Canonical 10-char combo, or null if the string isn't five distinct cards. */\nexport function canonicalPlo5Hand(input: string): string | null {\n  const compact = input.replace(/[\\s,]+/g, \"\");\n  if (compact.length !== 10) return null;\n  const cards: string[] = [];\n  const seen = new Set<string>();\n  for (let i = 0; i < 10; i += 2) {\n    const rank = compact[i].toUpperCase();\n    const suit = compact[i + 1].toLowerCase();\n    if (RANK_VALUE[rank] === undefined || SUIT_VALUE[suit] === undefined) {\n      return null;\n    }\n    const card = rank + suit;\n    if (seen.has(card)) return null;\n    seen.add(card);\n    cards.push(card);\n  }\n  cards.sort((a, b) => {\n    const rd = RANK_VALUE[a[0]] - RANK_VALUE[b[0]];\n    return rd !== 0 ? rd : SUIT_VALUE[a[1]] - SUIT_VALUE[b[1]];\n  });\n  return cards.join(\"\");\n}\n\nfunction suitPerms(): string[][] {\n  const suits = [\"s\", \"h\", \"d\", \"c\"];\n  const out: string[][] = [];\n  const used = [false, false, false, false];\n  const cur: string[] = [];\n  const walk = () => {\n    if (cur.length === 4) {\n      out.push([...cur]);\n      return;\n    }\n    for (let i = 0; i < 4; i++) {\n      if (used[i]) continue;\n      used[i] = true;\n      cur.push(suits[i]);\n      walk();\n      cur.pop();\n      used[i] = false;\n    }\n  };\n  walk();\n  return out;\n}\n\nconst SUIT_PERMS = suitPerms();\n\n/** Suit-isomorphism orbit. Index 0 is the user's canonical cards. */\nexport function hdvOrbit(input: string): string[] | null {\n  const canon = canonicalPlo5Hand(input);\n  if (!canon) return null;\n  const ranks: string[] = [];\n  const suits: string[] = [];\n  for (let i = 0; i < 10; i += 2) {\n    ranks.push(canon[i]);\n    suits.push(canon[i + 1]);\n  }\n  const seen = new Set<string>([canon]);\n  for (const perm of SUIT_PERMS) {\n    const map: Record<string, string> = {\n      s: perm[0],\n      h: perm[1],\n      d: perm[2],\n      c: perm[3],\n    };\n    const remapped: string[] = [];\n    for (let i = 0; i < 5; i++) remapped.push(ranks[i] + map[suits[i]]);\n    const next = canonicalPlo5Hand(remapped.join(\"\"));\n    if (next) seen.add(next);\n  }\n  const rest = [...seen].filter((h) => h !== canon).sort();\n  return [canon, ...rest];\n}\n\nfunction compareRankStr(a: string, b: string): number {\n  const n = Math.min(a.length, b.length);\n  for (let i = 0; i < n; i++) {\n    const d = RANK_HI.indexOf(a[i]) - RANK_HI.indexOf(b[i]);\n    if (d !== 0) return d;\n  }\n  return a.length - b.length;\n}\n\n/** Monker-style grouping: parentheses wrap ranks that share a suit. */\nexport function plo5IsoClass(input: string): string | null {\n  const canon = canonicalPlo5Hand(input);\n  if (!canon) return null;\n  const bySuit = new Map<string, string[]>();\n  for (let i = 0; i < 10; i += 2) {\n    const r = canon[i];\n    const s = canon[i + 1];\n    const arr = bySuit.get(s);\n    if (arr) arr.push(r);\n    else bySuit.set(s, [r]);\n  }\n  const groups = [...bySuit.values()].map((g) =>\n    [...g].sort((a, b) => RANK_HI.indexOf(a) - RANK_HI.indexOf(b)).join(\"\"),\n  );\n  groups.sort((a, b) => b.length - a.length || compareRankStr(a, b));\n  return groups.map((g) => (g.length > 1 ? `(${g})` : g)).join(\"\");\n}\n",
      "type": "registry:lib",
      "target": "lib/plo5-ranges/canonical.ts"
    },
    {
      "path": "src/lib/plo5-ranges/categories.ts",
      "content": "/**\n * Preflop hand categories for five-card Omaha, the way a player sorts a\n * range: pairing and suitedness first (unpaired double suited, one pair\n * single suited, …), then the structure inside (rundowns, broadway counts,\n * the pair's rank). Pure functions of the ten-character combo, so the\n * server can fold a 204k-hand node into a tree and the explorer can filter\n * its lists by the same keys.\n */\n\nimport type { CsvRow } from \"./csv\";\n\nconst RANK_ORDER = \"23456789TJQKA\";\nconst BROADWAY_MIN = RANK_ORDER.indexOf(\"T\");\n\nexport type Pairing = \"unpaired\" | \"pair\" | \"two_pair\" | \"trips\" | \"quads\";\nexport type Suitedness = \"ds\" | \"ss\";\n\n/** A top-level row: pairing × suitedness, or quads on their own. */\nexport type TopKey = `${Exclude<Pairing, \"quads\">}_${Suitedness}` | \"quads\";\n\nexport type UnpairedShape = \"rundown5\" | \"rundown4\" | \"broadway3\" | \"broadway2\" | \"ragged\";\nexport type PairRank = \"AA\" | \"KK\" | \"QQ\" | \"JJ\" | \"TT\" | \"mid\" | \"low\";\n\nexport interface HandCategory {\n  top: TopKey;\n  /** The structure row under `top`; quads and trips have none. */\n  child: UnpairedShape | PairRank | null;\n}\n\nconst PAIRING_LABEL: Record<Pairing, string> = {\n  unpaired: \"Unpaired\",\n  pair: \"One pair\",\n  two_pair: \"Two pair\",\n  trips: \"Trips\",\n  quads: \"Quads\",\n};\nconst SUIT_LABEL: Record<Suitedness, string> = { ds: \"double suited\", ss: \"single suited\" };\n\nconst SHAPE_LABEL: Record<UnpairedShape, string> = {\n  rundown5: \"5-card rundown (≤2 gaps)\",\n  rundown4: \"4-card rundown (≤2 gaps)\",\n  broadway3: \"3 broadway\",\n  broadway2: \"2 broadway + 3 low\",\n  ragged: \"Ragged\",\n};\nconst PAIR_LABEL: Record<PairRank, string> = {\n  AA: \"Aces\",\n  KK: \"Kings\",\n  QQ: \"Queens\",\n  JJ: \"Jacks\",\n  TT: \"Tens\",\n  mid: \"Nines to sixes\",\n  low: \"Fives to deuces\",\n};\n\nconst UNPAIRED_SHAPES: readonly UnpairedShape[] = [\"rundown5\", \"rundown4\", \"broadway3\", \"broadway2\", \"ragged\"];\nconst PAIR_RANKS: readonly PairRank[] = [\"AA\", \"KK\", \"QQ\", \"JJ\", \"TT\", \"mid\", \"low\"];\n\n/** Top rows in display order. */\nexport const TOP_KEYS: readonly TopKey[] = [\n  \"unpaired_ds\",\n  \"unpaired_ss\",\n  \"pair_ds\",\n  \"pair_ss\",\n  \"two_pair_ds\",\n  \"two_pair_ss\",\n  \"trips_ds\",\n  \"trips_ss\",\n  \"quads\",\n];\n\nexport function topLabel(top: TopKey): string {\n  if (top === \"quads\") return PAIRING_LABEL.quads;\n  const [pairing, suit] = splitTop(top);\n  return `${PAIRING_LABEL[pairing]} ${SUIT_LABEL[suit]}`;\n}\n\nexport function childLabel(child: UnpairedShape | PairRank): string {\n  return child in SHAPE_LABEL ? SHAPE_LABEL[child as UnpairedShape] : PAIR_LABEL[child as PairRank];\n}\n\nfunction splitTop(top: Exclude<TopKey, \"quads\">): [Exclude<Pairing, \"quads\">, Suitedness] {\n  const i = top.lastIndexOf(\"_\");\n  return [top.slice(0, i) as Exclude<Pairing, \"quads\">, top.slice(i + 1) as Suitedness];\n}\n\n/** Children a top row can have, in display order. */\nexport function childrenOf(top: TopKey): readonly (UnpairedShape | PairRank)[] {\n  if (top === \"quads\") return [];\n  const [pairing] = splitTop(top);\n  if (pairing === \"unpaired\") return UNPAIRED_SHAPES;\n  if (pairing === \"trips\") return [];\n  return PAIR_RANKS;\n}\n\nfunction ranksOf(hand: string): number[] {\n  const out: number[] = [];\n  for (let i = 0; i + 1 < hand.length; i += 2) {\n    const r = RANK_ORDER.indexOf(hand[i].toUpperCase());\n    if (r >= 0) out.push(r);\n  }\n  return out;\n}\n\nfunction suitsOf(hand: string): string[] {\n  const out: string[] = [];\n  for (let i = 0; i + 1 < hand.length; i += 2) out.push(hand[i + 1].toLowerCase());\n  return out;\n}\n\n/** Fewest gaps across `n` of these distinct ranks (sorted); an ace counts low too. */\nfunction fewestGaps(distinct: readonly number[], n: number): number {\n  const sets = [distinct];\n  if (distinct.includes(12)) sets.push([-1, ...distinct.filter((r) => r !== 12)]);\n  let best = Infinity;\n  for (const ranks of sets) {\n    for (let i = 0; i + n - 1 < ranks.length; i++) {\n      const gaps = ranks[i + n - 1] - ranks[i] - (n - 1);\n      if (gaps < best) best = gaps;\n    }\n  }\n  return best;\n}\n\nfunction pairRank(rank: number): PairRank {\n  const r = RANK_ORDER[rank];\n  if (r === \"A\" || r === \"K\" || r === \"Q\" || r === \"J\" || r === \"T\") return `${r}${r}` as PairRank;\n  return rank >= RANK_ORDER.indexOf(\"6\") ? \"mid\" : \"low\";\n}\n\n/** Sort a five-card combo into its category. */\nexport function categorizePlo5Hand(hand: string): HandCategory {\n  const ranks = ranksOf(hand);\n  const counts = new Map<number, number>();\n  for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);\n  const multiplicities = [...counts.values()].sort((a, b) => b - a);\n  const suitCounts = new Map<string, number>();\n  for (const s of suitsOf(hand)) suitCounts.set(s, (suitCounts.get(s) ?? 0) + 1);\n  const suitedPairs = [...suitCounts.values()].filter((n) => n >= 2).length;\n  const suit: Suitedness = suitedPairs >= 2 ? \"ds\" : \"ss\";\n\n  if (multiplicities[0] >= 4) return { top: \"quads\", child: null };\n  if (multiplicities[0] === 3) return { top: `trips_${suit}`, child: null };\n  const paired = [...counts.entries()].filter(([, n]) => n >= 2).map(([r]) => r);\n  if (paired.length >= 2) {\n    return { top: `two_pair_${suit}`, child: pairRank(Math.max(...paired)) };\n  }\n  if (paired.length === 1) {\n    return { top: `pair_${suit}`, child: pairRank(paired[0]) };\n  }\n  const distinct = [...counts.keys()].sort((a, b) => a - b);\n  const broadway = distinct.filter((r) => r >= BROADWAY_MIN).length;\n  let child: UnpairedShape;\n  if (fewestGaps(distinct, 5) <= 2) child = \"rundown5\";\n  else if (fewestGaps(distinct, 4) <= 2) child = \"rundown4\";\n  // Four broadway cards always sit within a 4-card rundown, so 3 is the top count here.\n  else if (broadway === 3) child = \"broadway3\";\n  else if (broadway === 2) child = \"broadway2\";\n  else child = \"ragged\";\n  return { top: `unpaired_${suit}`, child };\n}\n\n/** Does a hand sit in a row? A top key matches its whole family; `top:child` one structure. */\nexport function matchesPlo5Category(hand: string, key: string): boolean {\n  const cat = categorizePlo5Hand(hand);\n  const colon = key.indexOf(\":\");\n  if (colon < 0) return cat.top === key;\n  return cat.top === key.slice(0, colon) && cat.child === key.slice(colon + 1);\n}\n\n/** Any of the keys; no keys means everything. */\nexport function matchesPlo5Categories(hand: string, keys: readonly string[]): boolean {\n  if (keys.length === 0) return true;\n  const cat = categorizePlo5Hand(hand);\n  return keys.some((key) => {\n    const colon = key.indexOf(\":\");\n    return colon < 0 ? cat.top === key : cat.top === key.slice(0, colon) && cat.child === key.slice(colon + 1);\n  });\n}\n\n/** Parse the `cats` query param: comma-separated keys, unknown ones dropped. */\nexport function parsePlo5CategoryKeys(raw: string | null | undefined): string[] {\n  if (!raw) return [];\n  const out: string[] = [];\n  for (const key of raw.split(\",\")) {\n    const k = key.trim();\n    if (!k) continue;\n    const colon = k.indexOf(\":\");\n    const top = (colon < 0 ? k : k.slice(0, colon)) as TopKey;\n    if (!TOP_KEYS.includes(top)) continue;\n    if (colon >= 0 && !(childrenOf(top) as readonly string[]).includes(k.slice(colon + 1))) continue;\n    out.push(k);\n  }\n  return out;\n}\n\nexport interface CategoryNode {\n  key: string;\n  label: string;\n  /** Share of the range's reach-weighted hands (0–1). */\n  share: number;\n  /** Reach-weighted action split inside the row, parallel to `actions`; null when nothing reaches. */\n  mix: number[] | null;\n  children: CategoryNode[];\n}\n\nexport interface CategoryTree {\n  /** The node's options, in the tree's own order; `mix` rows follow it. */\n  actions: string[];\n  /** Reach-weighted hand count of the range. */\n  combos: number;\n  nodes: CategoryNode[];\n}\n\n/**\n * Fold a node's hands into the tree. `freqs` is each option's hand→frequency\n * at the node (parallel to `actions`); `reach` is how much of a hand is\n * still in the actor's range here (1 at a first decision).\n */\nexport function buildPlo5CategoryTree(\n  actions: readonly string[],\n  freqs: readonly ReadonlyMap<string, number>[],\n  reach: (hand: string) => number,\n): CategoryTree {\n  type Acc = { w: number; mix: number[] };\n  const acc = new Map<string, Acc>();\n  const add = (key: string, w: number, f: readonly number[]) => {\n    let a = acc.get(key);\n    if (!a) acc.set(key, (a = { w: 0, mix: new Array<number>(actions.length).fill(0) }));\n    a.w += w;\n    for (let i = 0; i < actions.length; i++) a.mix[i] += w * f[i];\n  };\n  const hands = new Set<string>();\n  for (const m of freqs) for (const hand of m.keys()) hands.add(hand);\n  let total = 0;\n  const f = new Array<number>(actions.length);\n  for (const hand of hands) {\n    const w = reach(hand);\n    if (!(w > 0)) continue;\n    let fs = 0;\n    for (let i = 0; i < actions.length; i++) {\n      f[i] = freqs[i].get(hand) ?? 0;\n      fs += f[i];\n    }\n    if (fs > 0) for (let i = 0; i < actions.length; i++) f[i] /= fs;\n    const cat = categorizePlo5Hand(hand);\n    total += w;\n    add(cat.top, w, f);\n    if (cat.child) add(`${cat.top}:${cat.child}`, w, f);\n  }\n  const node = (key: string, label: string, children: CategoryNode[] = []): CategoryNode | null => {\n    const a = acc.get(key);\n    if (!a || !(a.w > 0)) return null;\n    const mixTotal = a.mix.reduce((s, x) => s + x, 0);\n    return {\n      key,\n      label,\n      share: total > 0 ? Math.round((a.w / total) * 1e4) / 1e4 : 0,\n      mix: mixTotal > 0 ? a.mix.map((x) => Math.round((x / mixTotal) * 1000) / 1000) : null,\n      children,\n    };\n  };\n  const nodes: CategoryNode[] = [];\n  for (const top of TOP_KEYS) {\n    const children = childrenOf(top)\n      .map((c) => node(`${top}:${c}`, childLabel(c)))\n      .filter((x): x is CategoryNode => !!x);\n    const n = node(top, topLabel(top), children);\n    if (n) nodes.push(n);\n  }\n  return { actions: [...actions], combos: Math.round(total * 100) / 100, nodes };\n}\n\nconst SUITS = \"shdc\";\nconst SUIT_PERMS: number[][] = [];\n(function walk(cur: number[], used: boolean[]) {\n  if (cur.length === 4) {\n    SUIT_PERMS.push([...cur]);\n    return;\n  }\n  for (let i = 0; i < 4; i++) {\n    if (used[i]) continue;\n    used[i] = true;\n    cur.push(i);\n    walk(cur, used);\n    cur.pop();\n    used[i] = false;\n  }\n})([], [false, false, false, false]);\n\n/**\n * How many dealt combos a stored bucket stands for. The pack lists one or\n * more suit-reduced spellings per suit-permutation orbit; the orbit's real\n * combos are split evenly across the spellings it does list. `hand` must be\n * canonical (cards sorted by rank, then s/h/d/c).\n */\nexport function storedComboWeight(hand: string, stored: ReadonlySet<string>): number {\n  const ranks: string[] = [];\n  const suits: number[] = [];\n  for (let i = 0; i + 1 < hand.length; i += 2) {\n    ranks.push(hand[i]);\n    suits.push(SUITS.indexOf(hand[i + 1]));\n  }\n  const n = ranks.length;\n  const orbit = new Set<string>();\n  let present = 0;\n  const mapped = new Array<number>(n);\n  for (const perm of SUIT_PERMS) {\n    for (let i = 0; i < n; i++) mapped[i] = perm[suits[i]];\n    // Ranks are already in order; only cards of one rank need re-sorting by suit.\n    let out = \"\";\n    for (let i = 0; i < n; ) {\n      let j = i + 1;\n      while (j < n && ranks[j] === ranks[i]) j++;\n      if (j - i === 1) out += ranks[i] + SUITS[mapped[i]];\n      else {\n        const run = mapped.slice(i, j).sort((a, b) => a - b);\n        for (const m of run) out += ranks[i] + SUITS[m];\n      }\n      i = j;\n    }\n    if (orbit.has(out)) continue;\n    orbit.add(out);\n    if (stored.has(out)) present++;\n  }\n  return orbit.size / Math.max(1, present);\n}\n\n/** Rows of one edge CSV as a hand→frequency map. */\nexport function freqMap(rows: readonly CsvRow[]): Map<string, number> {\n  const out = new Map<string, number>();\n  for (const r of rows) out.set(r.hand, r.freq);\n  return out;\n}\n",
      "type": "registry:lib",
      "target": "lib/plo5-ranges/categories.ts"
    },
    {
      "path": "src/lib/plo5-ranges/csv.ts",
      "content": "/**\n * Point-lookup over a PLO5 range CSV (`hand:freq`, `hand:freq:ev`, or\n * `hand:freq:ev:evSource:evStdErr` for an estimated EV and its standard error\n * in big blinds; see `scripts/hydra-json-to-plo5-csv.mjs`).\n * The PLO5 export stores EV in big blinds (folding the SB reads -0.5, the BB\n * -1), unlike the PLO6 HU export's small blinds. Every PLO5 reader returns it\n * in small blinds (`EV_SB_PER_FILE_UNIT`), the unit Explorer, coach and\n * grades expect (`ev_sb`, shown as `ev / 2`).\n * Records are newline-separated (the HDV dump), unlike PLO6's comma join.\n */\n\nimport { comboStrength } from \"./canonical\";\n\n/**\n * `evSource` / `evStdErr` (bb) are present only when the export marked the EV\n * as an estimate with a standard error; an exact EV carries neither.\n */\nexport type CsvHit = { freq: number; ev: number | null; evSource?: string; evStdErr?: number };\nexport type CsvRow = { hand: string; freq: number; ev: number | null; evSource?: string; evStdErr?: number };\n\n/** The file's EV unit (bb) in small blinds. */\nconst EV_SB_PER_FILE_UNIT = 2;\n\nfunction parseHit(rest: string): CsvHit {\n  const [freqField, evField, sourceField, stdErrField] = rest.split(\":\");\n  const freq = Number(freqField);\n  if (!Number.isFinite(freq)) return { freq: 0, ev: null };\n  if (evField === undefined) return { freq, ev: null };\n  const ev = Number(evField) * EV_SB_PER_FILE_UNIT;\n  if (!Number.isFinite(ev)) return { freq, ev: null };\n  const hit: CsvHit = { freq, ev };\n  if (sourceField) hit.evSource = sourceField;\n  const evStdErr = stdErrField === undefined ? NaN : Number(stdErrField);\n  if (Number.isFinite(evStdErr)) hit.evStdErr = evStdErr;\n  return hit;\n}\n\nfunction recordStart(csv: string, hand: string): number {\n  const needle = `${hand}:`;\n  if (csv.startsWith(needle)) return 0;\n  const nl = csv.indexOf(`\\n${needle}`);\n  if (nl >= 0) return nl + 1;\n  const comma = csv.indexOf(`,${needle}`);\n  if (comma >= 0) return comma + 1;\n  return -1;\n}\n\nfunction recordEnd(csv: string, start: number): number {\n  let end = csv.length;\n  for (let i = start; i < csv.length; i++) {\n    const c = csv[i];\n    if (c === \"\\n\" || c === \"\\r\" || c === \",\") {\n      end = i;\n      break;\n    }\n  }\n  return end;\n}\n\nexport function lookupCsv(csv: string, hand: string): CsvHit {\n  if (!hand || !csv) return { freq: 0, ev: null };\n  const start = recordStart(csv, hand);\n  if (start < 0) return { freq: 0, ev: null };\n  const rec = csv.slice(start, recordEnd(csv, start));\n  const first = rec.indexOf(\":\");\n  if (first < 0) return { freq: 0, ev: null };\n  return parseHit(rec.slice(first + 1));\n}\n\n/**\n * A fold's EV is the chips the actor already put in, the same for every hand,\n * so any row's EV is the node's fold EV. Null when the file stores no EV.\n */\nexport function foldEvOf(csv: string): number | null {\n  if (!csv) return null;\n  const rec = csv.slice(0, recordEnd(csv, 0));\n  const first = rec.indexOf(\":\");\n  return first < 0 ? null : parseHit(rec.slice(first + 1)).ev;\n}\n\nexport function csvHasHand(csv: string, hand: string): boolean {\n  if (!hand || !csv) return false;\n  return recordStart(csv, hand) >= 0;\n}\n\nexport function firstStoredHdv(csv: string, hands: readonly string[]): string | null {\n  if (!hands.length || !csv) return null;\n  if (csvHasHand(csv, hands[0])) return hands[0];\n  for (const hand of hands) {\n    if (csvHasHand(csv, hand)) return hand;\n  }\n  return null;\n}\n\nfunction walkCsv(csv: string, visit: (hand: string, hit: CsvHit) => void): void {\n  let i = 0;\n  while (i < csv.length) {\n    const end = recordEnd(csv, i);\n    const rec = csv.slice(i, end);\n    const colon = rec.indexOf(\":\");\n    if (colon > 0) visit(rec.slice(0, colon), parseHit(rec.slice(colon + 1)));\n    i = end + 1;\n    if (csv[end] === \"\\r\" && csv[i] === \"\\n\") i++;\n  }\n}\n\n/** Every nonzero (or above `minFreq`) row. Used to build Explorer breakdowns. */\nexport function parseCsvHands(csv: string, minFreq = 0): CsvRow[] {\n  const out: CsvRow[] = [];\n  if (!csv) return out;\n  walkCsv(csv, (hand, hit) => {\n    if (hit.freq > minFreq) out.push({ hand, ...hit });\n  });\n  return out;\n}\n\nfunction compareRows(a: CsvRow, b: CsvRow): number {\n  const ea = a.ev;\n  const eb = b.ev;\n  if (ea != null && eb != null && ea !== eb) return eb - ea;\n  if (ea != null && eb == null) return -1;\n  if (ea == null && eb != null) return 1;\n  if (a.freq !== b.freq) return b.freq - a.freq;\n  return comboStrength(b.hand) - comboStrength(a.hand);\n}\n\nexport function topCsvHands(\n  csv: string,\n  limit: number,\n  minFreq = 0,\n  match?: (hand: string) => boolean,\n): { rows: CsvRow[]; total: number } {\n  const all = match\n    ? parseCsvHands(csv, minFreq).filter((r) => match(r.hand))\n    : parseCsvHands(csv, minFreq);\n  all.sort(compareRows);\n  return { rows: limit > 0 ? all.slice(0, limit) : all, total: all.length };\n}\n\nexport function indexCsvNeedles(\n  csv: string,\n  needles: readonly string[],\n): Map<string, CsvHit> {\n  const want = new Set(needles.filter(Boolean));\n  const out = new Map<string, CsvHit>();\n  if (!csv || want.size === 0) return out;\n  let i = 0;\n  while (i < csv.length && out.size < want.size) {\n    const end = recordEnd(csv, i);\n    const rec = csv.slice(i, end);\n    const colon = rec.indexOf(\":\");\n    if (colon > 0) {\n      const hand = rec.slice(0, colon);\n      if (want.has(hand) && !out.has(hand)) {\n        out.set(hand, parseHit(rec.slice(colon + 1)));\n      }\n    }\n    i = end + 1;\n    if (csv[end] === \"\\r\" && csv[i] === \"\\n\") i++;\n  }\n  return out;\n}\n",
      "type": "registry:lib",
      "target": "lib/plo5-ranges/csv.ts"
    },
    {
      "path": "src/lib/plo6-ranges/canonical.ts",
      "content": "/**\n * Six-card Omaha combos as this HydraSolver export stores them: 12 characters,\n * ranks then suits, cards sorted by rank (2–A) then suit (s, h, d, c).\n *\n * The source `.rng` files use that order (`2s2h2d2c3s3h`), so user input\n * (`Ah Kd Kc Qs Qh 2s`, `ahkd…`) has to land on the same string or a lookup\n * misses a hand that is actually in the tree.\n *\n * HDV is not a fuzzy cluster: Hydra stores ~1.86M concrete suitings of the\n * 20.4M combinadic 6-card space. Preflop, suit relabelings of a hand are the\n * same game, and empirically every random 6-card deal has at least one\n * stored orbit member (orbit siblings share freq/EV). `hdvOrbit` is that\n * map — exact spelling first, then the other ≤23 suit permutations.\n */\n\nconst RANK_HI = \"AKQJT98765432\";\n\nconst RANK_ORDER = \"23456789TJQKA\";\nconst SUIT_ORDER = \"shdc\";\n\nconst RANK_VALUE: Record<string, number> = Object.fromEntries(\n  [...RANK_ORDER].map((r, i) => [r, i]),\n);\nconst SUIT_VALUE: Record<string, number> = Object.fromEntries(\n  [...SUIT_ORDER].map((s, i) => [s, i]),\n);\n\n/** Rank-sum used to pick the most interesting sample hands (aces-high first). */\nexport function comboStrength(hand: string): number {\n  let s = 0;\n  for (let i = 0; i + 1 < hand.length; i += 2) {\n    s += RANK_VALUE[hand[i].toUpperCase()] ?? 0;\n  }\n  return s;\n}\n\n/**\n * Canonical 12-char combo, or null if the string isn't six distinct cards.\n * Accepts spaced (`As Ah Kd Kc Qs Qh`) or concatenated form, any case.\n */\nexport function canonicalPlo6Hand(input: string): string | null {\n  const compact = input.replace(/[\\s,]+/g, \"\");\n  if (compact.length !== 12) return null;\n  const cards: string[] = [];\n  const seen = new Set<string>();\n  for (let i = 0; i < 12; i += 2) {\n    const rank = compact[i].toUpperCase();\n    const suit = compact[i + 1].toLowerCase();\n    if (RANK_VALUE[rank] === undefined || SUIT_VALUE[suit] === undefined) {\n      return null;\n    }\n    const card = rank + suit;\n    if (seen.has(card)) return null;\n    seen.add(card);\n    cards.push(card);\n  }\n  cards.sort((a, b) => {\n    const rd = RANK_VALUE[a[0]] - RANK_VALUE[b[0]];\n    return rd !== 0 ? rd : SUIT_VALUE[a[1]] - SUIT_VALUE[b[1]];\n  });\n  return cards.join(\"\");\n}\n\nfunction suitPerms(): string[][] {\n  const out: string[][] = [];\n  const s = [...SUIT_ORDER];\n  const rec = (i: number) => {\n    if (i === s.length) {\n      out.push([...s]);\n      return;\n    }\n    for (let j = i; j < s.length; j++) {\n      [s[i], s[j]] = [s[j], s[i]];\n      rec(i + 1);\n      [s[i], s[j]] = [s[j], s[i]];\n    }\n  };\n  rec(0);\n  return out;\n}\n\nconst SUIT_PERMS = suitPerms();\n\n/**\n * Suit-isomorphism orbit of a 6-card combo in Hydra spelling. Index 0 is the\n * user's own canonical cards; the rest are the other suit relabelings.\n */\nexport function hdvOrbit(input: string): string[] | null {\n  const canon = canonicalPlo6Hand(input);\n  if (!canon) return null;\n  const ranks: string[] = [];\n  const suits: string[] = [];\n  for (let i = 0; i < 12; i += 2) {\n    ranks.push(canon[i]);\n    suits.push(canon[i + 1]);\n  }\n  const seen = new Set<string>([canon]);\n  for (const perm of SUIT_PERMS) {\n    const map: Record<string, string> = {\n      s: perm[0],\n      h: perm[1],\n      d: perm[2],\n      c: perm[3],\n    };\n    const remapped: string[] = [];\n    for (let i = 0; i < 6; i++) remapped.push(ranks[i] + map[suits[i]]);\n    const next = canonicalPlo6Hand(remapped.join(\"\"));\n    if (next) seen.add(next);\n  }\n  const rest = [...seen].filter((h) => h !== canon).sort();\n  return [canon, ...rest];\n}\n\nfunction compareRankStr(a: string, b: string): number {\n  const n = Math.min(a.length, b.length);\n  for (let i = 0; i < n; i++) {\n    const d = RANK_HI.indexOf(a[i]) - RANK_HI.indexOf(b[i]);\n    if (d !== 0) return d;\n  }\n  return a.length - b.length;\n}\n\n/**\n * Suit-isomorphism class in Monker-style grouping: parentheses wrap ranks\n * that share a suit, ranks high-first, groups by size then rank.\n * `QsQhKdKcAsAh` → `(AQ)(AQ)KK`.\n */\nexport function plo6IsoClass(input: string): string | null {\n  const canon = canonicalPlo6Hand(input);\n  if (!canon) return null;\n  const bySuit = new Map<string, string[]>();\n  for (let i = 0; i < 12; i += 2) {\n    const r = canon[i];\n    const s = canon[i + 1];\n    const arr = bySuit.get(s);\n    if (arr) arr.push(r);\n    else bySuit.set(s, [r]);\n  }\n  const groups = [...bySuit.values()].map((g) =>\n    [...g].sort((a, b) => RANK_HI.indexOf(a) - RANK_HI.indexOf(b)).join(\"\"),\n  );\n  groups.sort((a, b) => b.length - a.length || compareRankStr(a, b));\n  return groups.map((g) => (g.length > 1 ? `(${g})` : g)).join(\"\");\n}\n\nconst SUIT_CHARS = new Set([\"s\", \"h\", \"d\", \"c\", \"S\", \"H\", \"D\", \"C\"]);\n\n/**\n * Rank multiset from a typed filter. `AAKKQJ` and `AsAhKdKcQsJh` both become\n * {A:2, K:2, Q:1, J:1}. Returns null when the string isn't 1–6 ranks.\n */\nexport function parsePlo6RankFilter(input: string): Record<string, number> | null {\n  const compact = input.replace(/[\\s,]+/g, \"\");\n  if (!compact) return null;\n  const ranks: string[] = [];\n  let i = 0;\n  while (i < compact.length) {\n    const r = compact[i].toUpperCase();\n    if (RANK_VALUE[r] === undefined) return null;\n    ranks.push(r);\n    i++;\n    if (i < compact.length && SUIT_CHARS.has(compact[i])) i++;\n  }\n  if (ranks.length < 1 || ranks.length > 6) return null;\n  const counts: Record<string, number> = {};\n  for (const r of ranks) counts[r] = (counts[r] ?? 0) + 1;\n  return counts;\n}\n\nexport function encodePlo6RankFilter(filter: Record<string, number>): string {\n  return Object.entries(filter)\n    .sort((a, b) => RANK_HI.indexOf(a[0]) - RANK_HI.indexOf(b[0]))\n    .map(([r, n]) => r.repeat(n))\n    .join(\"\");\n}\n\nfunction handRankCounts(hand: string): Record<string, number> {\n  const compact = hand.replace(/[\\s,]+/g, \"\");\n  const counts: Record<string, number> = {};\n  for (let i = 0; i + 1 < compact.length; i += 2) {\n    const r = compact[i].toUpperCase();\n    counts[r] = (counts[r] ?? 0) + 1;\n  }\n  return counts;\n}\n\n/** Six ranks → exact bag. Fewer ranks → hand must include at least those counts. */\nexport function handMatchesRankFilter(\n  hand: string,\n  filter: Record<string, number>,\n): boolean {\n  const have = handRankCounts(hand);\n  const needed = Object.values(filter).reduce((s, n) => s + n, 0);\n  if (needed >= 6) {\n    const keys = new Set([...Object.keys(have), ...Object.keys(filter)]);\n    for (const k of keys) if ((have[k] ?? 0) !== (filter[k] ?? 0)) return false;\n    return true;\n  }\n  for (const [r, n] of Object.entries(filter)) {\n    if ((have[r] ?? 0) < n) return false;\n  }\n  return true;\n}\n",
      "type": "registry:lib",
      "target": "lib/plo6-ranges/canonical.ts"
    },
    {
      "path": "src/lib/solver/client.ts",
      "content": "// Browser client for the solver, talking to the same-origin `/api/solver/*`\n// proxy. Because it's same-origin the Clerk session cookie rides along\n// automatically — no Authorization header, no CORS.\n//\n// We drive the job by *polling* `GET /api/solver/jobs/:id`, not a single\n// long-lived SSE stream. A flop tree solves for minutes; an SSE connection held\n// open that long is torn down by the serverless proxy once the solve outlives\n// the function's max duration (the browser sees `net::ERR_TIMED_OUT`, or the\n// read loop ends without a `done` event). The solve itself runs server-side in a\n// background task, independent of any connection, so short repeated polls\n// complete a solve of any length. Live `iter · expl` progress rides along on the\n// worker's `running` response when present.\n\nimport { explorerHost } from \"@/lib/explorer/host\";\nimport type { SolveRequest, SolverProgress, SolverResult } from \"./types\";\n\n/** The solver routes on this host; solving is off where the host has none. */\nfunction solverApi(): string {\n  const api = explorerHost().solver;\n  if (!api) throw new Error(\"Solving isn't available here.\");\n  return api;\n}\n\nexport interface SolveOutcome {\n  result: SolverResult;\n  /** True when the solve was cancelled — the result is the partial strategy. */\n  cancelled: boolean;\n}\n\nexport interface SolveHandle {\n  /** The worker's job id, once the POST has been accepted. */\n  jobId: Promise<string>;\n  /**\n   * True when the shared solve cache answered this request, so no worker job (and\n   * therefore no warm-start snapshot) exists. A caller that needs to chain off\n   * this solve — a locked re-solve does — must re-run it with `noCache: true`.\n   */\n  cached: Promise<boolean>;\n  /** Resolves with the final (or partial, if cancelled) strategy. */\n  promise: Promise<SolveOutcome>;\n  /** Cooperatively stop the solve; the worker returns the partial strategy. */\n  cancel: () => Promise<void>;\n}\n\n/** Kick off a solve and return a handle to track / cancel it. */\nexport function startSolve(\n  config: SolveRequest,\n  onProgress?: (p: SolverProgress) => void,\n): SolveHandle {\n  let resolveJob!: (id: string) => void;\n  let rejectJob!: (err: unknown) => void;\n  const jobId = new Promise<string>((res, rej) => {\n    resolveJob = res;\n    rejectJob = rej;\n  });\n  let resolveCached!: (cached: boolean) => void;\n  const cached = new Promise<boolean>((res) => {\n    resolveCached = res;\n  });\n  let cancelRequested = false;\n\n  const promise = (async (): Promise<SolveOutcome> => {\n    const created = await fetch(`${solverApi()}/jobs`, {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n      body: JSON.stringify(config),\n    });\n    if (!created.ok) {\n      const err = new Error(await errorText(created));\n      rejectJob(err);\n      resolveCached(false);\n      throw err;\n    }\n    const { job_id: id, cached: fromCache } = (await created.json()) as {\n      job_id: string;\n      cached?: boolean;\n    };\n    resolveJob(id);\n    resolveCached(Boolean(fromCache));\n\n    if (cancelRequested) await postCancel(id).catch(() => {});\n    return pollOutcome(id, onProgress);\n  })();\n  // Don't let an unobserved jobId rejection crash the page.\n  jobId.catch(() => {});\n\n  const cancel = async () => {\n    cancelRequested = true;\n    const id = await jobId.catch(() => null);\n    if (id) await postCancel(id).catch(() => {});\n  };\n\n  return { jobId, cached, promise, cancel };\n}\n\n/**\n * Re-attach to a solve that's already running (or finished) on the worker —\n * e.g. after a tab reload mid-flop-solve. The worker keeps jobs server-side,\n * so this is just the polling half of `startSolve` against a known job id.\n * A job the worker no longer knows (restart) rejects with its 404 message.\n */\nexport function resumeSolve(\n  jobId: string,\n  onProgress?: (p: SolverProgress) => void,\n): SolveHandle {\n  return {\n    jobId: Promise.resolve(jobId),\n    // A `cache-…` id is a cache hit being re-attached to; anything else is a\n    // real worker job.\n    cached: Promise.resolve(jobId.startsWith(\"cache-\")),\n    promise: pollOutcome(jobId, onProgress),\n    cancel: async () => {\n      await postCancel(jobId).catch(() => {});\n    },\n  };\n}\n\nfunction postCancel(jobId: string): Promise<Response> {\n  return fetch(`${solverApi()}/jobs/${jobId}/cancel`, { method: \"POST\" });\n}\n\n/** Shape of `GET /api/solver/jobs/:id` (proxied straight from the worker). */\ninterface PollBody {\n  status: \"running\" | \"done\";\n  cancelled?: boolean;\n  /** Latest tick while running; absent on older workers (graceful: no ticks). */\n  progress?: SolverProgress;\n  result?: SolverResult;\n}\n\n/**\n * Poll the job to completion and resolve with the terminal outcome. A cancelled\n * solve still resolves — the worker returns the partial (valid) strategy it\n * reached, flagged `cancelled`.\n *\n * Polls start snappy so a sub-second river solve resolves fast, then back off so\n * a multi-minute flop solve barely touches the network. Transient blips (a\n * dropped poll, a 502/504 from the proxy) are tolerated for a few attempts so\n * they don't abort a solve that's still running fine on the worker.\n */\nasync function pollOutcome(\n  jobId: string,\n  onProgress?: (p: SolverProgress) => void,\n): Promise<SolveOutcome> {\n  const MIN_INTERVAL = 400;\n  const MAX_INTERVAL = 3000;\n  const MAX_TRANSIENT_FAILURES = 5;\n\n  let interval = MIN_INTERVAL;\n  let transientFailures = 0;\n  const backoff = async () => {\n    await delay(interval);\n    interval = Math.min(Math.round(interval * 1.5), MAX_INTERVAL);\n  };\n  // A transient failure burns one of the retry budget, then backs off; throws\n  // (ending the solve) once the budget is exhausted.\n  const tolerate = async (message: string) => {\n    if (++transientFailures > MAX_TRANSIENT_FAILURES) throw new Error(message);\n    await backoff();\n  };\n\n  for (;;) {\n    let res: Response;\n    try {\n      res = await fetch(`${solverApi()}/jobs/${jobId}`, {\n        headers: { Accept: \"application/json\" },\n      });\n    } catch (err) {\n      // Network-level failure (offline, DNS, connection reset): retry.\n      await tolerate((err as Error)?.message || \"network error\");\n      continue;\n    }\n\n    // A gateway hiccup (proxy/worker briefly unreachable) is retryable; any\n    // other non-OK, non-202 status is a terminal error (404 job gone, 422 solve\n    // error, 401 auth).\n    if (res.status === 502 || res.status === 503 || res.status === 504) {\n      await tolerate(await errorText(res));\n      continue;\n    }\n    if (!res.ok && res.status !== 202) throw new Error(await errorText(res));\n\n    transientFailures = 0;\n    const body = (await res.json()) as PollBody;\n\n    if (body.status === \"done\") {\n      if (!body.result) throw new Error(\"solver returned a malformed result\");\n      return { result: body.result, cancelled: Boolean(body.cancelled) };\n    }\n\n    // Still running: surface the latest progress tick if the worker sent one.\n    if (body.progress) onProgress?.(body.progress);\n    await backoff();\n  }\n}\n\nfunction delay(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function errorText(res: Response): Promise<string> {\n  const text = await res.text().catch(() => \"\");\n  try {\n    const j = JSON.parse(text) as { error?: string };\n    if (j?.error) return j.error;\n  } catch {\n    /* not JSON */\n  }\n  return text.slice(0, 200) || `request failed (${res.status})`;\n}\n",
      "type": "registry:lib",
      "target": "lib/solver/client.ts"
    },
    {
      "path": "src/lib/solver/preflop.ts",
      "content": "// Preflop-tree walk for the solver's scenario selector.\n//\n// Ported from the desktop/mobile app (mobile/src/lib/trainer/parse-history.ts +\n// mobile/src/lib/solver/scenario.ts). The native solver is two-player, but the\n// NL preflop tree is 6-max; this module walks the tree one seat at a time and\n// collapses the line to heads-up the moment a raise is called, handing the two\n// survivors' ranges to the solver as OOP/IP.\n\nimport { ALL_HANDS, type RangeWeights } from \"@/lib/solver/range-model\";\nimport { notifyPlanRequired } from \"@/lib/access/plan-required\";\nimport { rangesUrl } from \"@/lib/explorer/host\";\nimport { ploRaisePotPct } from \"@/lib/explorer/bet-size\";\nimport type { CategoryTree } from \"@/lib/plo5-ranges/categories\";\n\nexport type Position =\n  | \"UTG\"\n  | \"UTG1\"\n  | \"UTG2\"\n  | \"LJ\"\n  | \"MP\"\n  | \"HJ\"\n  | \"CO\"\n  | \"BTN\"\n  | \"SB\"\n  | \"BB\";\n\n/** Datasets the Explorer can walk. */\nexport type ExplorerGame =\n  | \"nl\"\n  | \"plo\"\n  | \"plo4hu\"\n  | \"plo9\"\n  | \"plo5\"\n  | \"plo6hu\"\n  | \"nlmtt8\"\n  | IcmGame;\n\n/**\n * The 8-max tournament ICM sets, one per stage of the tournament. All three\n * read `/api/ranges/nlh8-icm`; a stage is the scenarios with that many\n * players left, and a scenario (one stack table) is picked inside it.\n */\nexport type IcmGame = \"icmft\" | \"icmbubble\" | \"icmbubble35\";\n\n/** Players left in the tournament for each ICM stage. */\nexport const ICM_PLAYERS_LEFT: Record<IcmGame, number> = {\n  icmft: 8,\n  icmbubble: 33,\n  icmbubble35: 35,\n};\n\nexport function isIcmGame(game: ExplorerGame): game is IcmGame {\n  return game in ICM_PLAYERS_LEFT;\n}\n\n/** Ante every seat posts on the ICM tables (8 × 0.125 = 1bb in the pot). */\nexport const ICM_ANTE_PER_SEAT_BB = 0.125;\nexport type ActionKind = \"fold\" | \"call\" | \"raise\" | \"allin\" | \"other\";\n\nexport interface NodeAction {\n  action: string;\n  kind: ActionKind;\n  /** hand → frequency in [0, 1] for this action. */\n  weights: Record<string, number>;\n  /** hand → EV in small blinds for this action (v2 bundles only). */\n  evs?: Record<string, number>;\n  sizePct?: number;\n  combos?: number;\n  /** Reach-weighted pool % (0–100). PLO5 nodes omit per-hand weights. */\n  poolPct?: number;\n  /** Hands that take this action at 100% (PLO5 HDV samples). */\n  always?: string[];\n  /** Mixed-strategy sample combos (PLO5). `freq` is 0–1. */\n  mixed?: { hand: string; freq: number }[];\n  /** Raise-to in bb, when the feed sizes the raise (NL MTT and ICM tokens). */\n  sizeBb?: number | null;\n}\n\nexport interface NodeResponse {\n  game: \"nl\";\n  stack: number;\n  history: string;\n  actor: Position;\n  actions: NodeAction[];\n  continuingCombos?: number;\n  /** Unit of `evs`: small blinds, or tournament dollars on the ICM sets. */\n  evUnit?: \"sb\" | \"usd\";\n}\n\n/** Wire shape from any ranges `/node` — PLO5 uses `hands` instead of `combos`. */\nexport interface ExplorerNodeRaw {\n  game?: string;\n  stack: number;\n  history: string;\n  actor: Position;\n  continuingCombos?: number;\n  evUnit?: string;\n  actions: Array<\n    NodeAction & {\n      hands?: number;\n    }\n  >;\n}\n\nexport interface Manifest {\n  game: \"nl\";\n  generatedAt: string;\n  stacks: number[];\n  positions: Position[];\n}\n\nexport interface SeatState {\n  position: Position;\n  action: string | null;\n  committed: number;\n  remaining: number;\n  folded: boolean;\n  isHero: boolean;\n  isDealer: boolean;\n}\n\nexport interface ParsedTable {\n  seats: Record<Position, SeatState>;\n  pot: number;\n  hero: Position;\n}\n\n// 6-max preflop play order (CW from UTG). MP isn't present in the dataset.\nexport const PLAY_ORDER: Position[] = [\"UTG\", \"HJ\", \"CO\", \"BTN\", \"SB\", \"BB\"];\n\n/**\n * Preflop play order (clockwise from UTG) per dataset. The 6-max datasets have\n * no MP; the 9-max PLO bundles name their early seats UTG1/UTG2/LJ.\n */\nexport const SEAT_ORDER: Record<ExplorerGame, Position[]> = {\n  nl: PLAY_ORDER,\n  plo: PLAY_ORDER,\n  // Heads-up: the SB is the button and acts first preflop.\n  plo4hu: [\"SB\", \"BB\"],\n  plo9: [\"UTG\", \"UTG1\", \"UTG2\", \"LJ\", \"HJ\", \"CO\", \"BTN\", \"SB\", \"BB\"],\n  nlmtt8: [\"UTG\", \"UTG1\", \"LJ\", \"HJ\", \"CO\", \"BTN\", \"SB\", \"BB\"],\n  icmft: [\"UTG\", \"UTG1\", \"LJ\", \"HJ\", \"CO\", \"BTN\", \"SB\", \"BB\"],\n  icmbubble: [\"UTG\", \"UTG1\", \"LJ\", \"HJ\", \"CO\", \"BTN\", \"SB\", \"BB\"],\n  icmbubble35: [\"UTG\", \"UTG1\", \"LJ\", \"HJ\", \"CO\", \"BTN\", \"SB\", \"BB\"],\n  // HydraSolver 6-max PLO5: first actor is LJ (HUD UTG).\n  plo5: [\"LJ\", \"HJ\", \"CO\", \"BTN\", \"SB\", \"BB\"],\n  plo6hu: [\"BTN\", \"BB\"],\n};\n\n// Postflop acting order (blinds first). The earlier player is out of position.\n// Early-position seats (UTG/UTG1/UTG2/LJ) keep clock order so 8-max / 9-max\n// assignOopIp does not treat a missing index as earliest-to-act.\nexport const POSTFLOP_ORDER: Position[] = [\n  \"SB\",\n  \"BB\",\n  \"UTG\",\n  \"UTG1\",\n  \"UTG2\",\n  \"LJ\",\n  \"HJ\",\n  \"CO\",\n  \"BTN\",\n];\n\n/** Dead ante on the HydraSolver PLO5 6-max 100bb tree. */\nexport const PLO5_ANTE_BB = 1.2;\n\n/** Dead ante on the HydraSolver PLO6 HU 100bb tree. */\nexport const PLO6HU_ANTE_BB = 0.4;\n\n/** BB-ante posted as dead chips on the 8-max MTT ladder. */\nexport const NLMTT8_ANTE_BB = 1;\n\nconst ROOT_HISTORY = \"UTG\";\n\n/** First actor on this dataset — UTG for the Monker 6/9-max packs, LJ for PLO5. */\nexport function rootHistory(game: ExplorerGame): string {\n  return SEAT_ORDER[game][0];\n}\n\n// ─── Ranges API client (same-origin /api/ranges/nl) ────────────────────────\n\nconst cache = new Map<string, Promise<unknown>>();\n\nasync function getJson<T>(path: string): Promise<T> {\n  const hit = cache.get(path) as Promise<T> | undefined;\n  if (hit) return hit;\n  const promise = (async () => {\n    const res = await fetch(path, { headers: { Accept: \"application/json\" } });\n    if (!res.ok) {\n      notifyPlanRequired(res.status);\n      const body = await res.text().catch(() => \"\");\n      throw new Error(`GET ${path} -> ${res.status}: ${body.slice(0, 200)}`);\n    }\n    return (await res.json()) as T;\n  })();\n  cache.set(path, promise);\n  promise.catch(() => cache.delete(path));\n  return promise;\n}\n\nexport function getManifest(): Promise<Manifest> {\n  return getJson<Manifest>(rangesUrl(\"nl\"));\n}\n\n/**\n * Route prefix per dataset. NL reads v2 because those bundles carry per-hand EV;\n * the PLO datasets already do.\n */\nconst GAME_PATH: Record<ExplorerGame, string> = {\n  nl: \"nl/v2\",\n  plo: \"plo\",\n  plo4hu: \"plo4hu\",\n  plo9: \"plo9\",\n  plo5: \"plo5\",\n  plo6hu: \"plo6hu\",\n  nlmtt8: \"nlmtt8\",\n  icmft: \"nlh8-icm\",\n  icmbubble: \"nlh8-icm\",\n  icmbubble35: \"nlh8-icm\",\n};\n\nfunction gameBase(game: ExplorerGame): string {\n  return rangesUrl(GAME_PATH[game]);\n}\n\nexport function getManifestForGame(game: ExplorerGame): Promise<Manifest> {\n  if (isIcmGame(game)) {\n    return getIcmTables(game).then((tables) => ({\n      game: \"nl\",\n      generatedAt: \"\",\n      stacks: [...new Set(tables.map((t) => t.stackBb))].sort((a, b) => a - b),\n      positions: SEAT_ORDER[game],\n    }));\n  }\n  return getJson<Manifest>(gameBase(game));\n}\n\n/** One ICM stack table (a scenario of `/api/ranges/nlh8-icm`). */\nexport interface IcmTable {\n  /** Scenario id, e.g. `33left-avg30-short-btn`. */\n  scenario: string;\n  /** The field's average stack: the depth the table is listed under. */\n  stackBb: number;\n  /** The table's label from the solve (`even`, `short-btn`, `mix-1`, …). */\n  label: string;\n  /** Each seat's starting stack in bb, before the ante. */\n  stacksBb: Partial<Record<Position, number>>;\n  /** Payouts, best place first, in tournament dollars. */\n  payouts: number[];\n  paidPlaces: number | null;\n  poolUsd: number | null;\n}\n\ninterface IcmDiscovery {\n  scenarios: {\n    scenario: string;\n    stackBb: number;\n    playersLeft: number;\n    table: {\n      label?: string;\n      stacksBb?: Partial<Record<Position, number>>;\n      icm?: { payouts?: number[]; paidPlaces?: number; poolUsd?: number };\n    } | null;\n  }[];\n}\n\n/** The stack tables of one ICM stage, shallowest first. */\nexport async function getIcmTables(game: IcmGame): Promise<IcmTable[]> {\n  const d = await getJson<IcmDiscovery>(gameBase(game));\n  const left = ICM_PLAYERS_LEFT[game];\n  return d.scenarios\n    .filter((s) => s.playersLeft === left)\n    .map((s) => ({\n      scenario: s.scenario,\n      stackBb: s.stackBb,\n      label: s.table?.label ?? s.scenario.replace(/^\\d+left-avg[\\d.]+-/, \"\"),\n      stacksBb: s.table?.stacksBb ?? {},\n      payouts: s.table?.icm?.payouts ?? [],\n      paidPlaces: s.table?.icm?.paidPlaces ?? null,\n      poolUsd: s.table?.icm?.poolUsd ?? null,\n    }))\n    .sort((a, b) => a.stackBb - b.stackBb);\n}\n\n/**\n * Raise-to sizes the feed has reported, per dataset (game plus ICM scenario):\n * `\"<history>_<token>\"` → bb. Filled as nodes load, read by `parseHistory`\n * to price tokens like `Open` / `3B` that don't encode their size.\n */\nconst raiseSizes = new Map<string, Record<string, number>>();\n\nfunction datasetKey(game: ExplorerGame, scenario?: string | null): string {\n  return scenario ? `${game}:${scenario}` : game;\n}\n\n/** The raise-to sizes seen so far on this dataset (a live, growing record). */\nexport function raiseSizesFor(game: ExplorerGame, scenario?: string | null): Record<string, number> {\n  const key = datasetKey(game, scenario);\n  let rec = raiseSizes.get(key);\n  if (!rec) {\n    rec = {};\n    raiseSizes.set(key, rec);\n  }\n  return rec;\n}\n\n/**\n * `getNodeV2OrNull` for any dataset — the Explorer's game-aware read. Same\n * contract: null at a history the dataset has no decision for (HTTP 404), i.e.\n * the preflop round closed on this line.\n */\nexport async function getNodeForGameOrNull(\n  game: ExplorerGame,\n  stack: number,\n  history: string,\n  /** ICM sets: the stack table to read (`33left-avg30-even`). */\n  scenario?: string | null,\n): Promise<NodeResponse | null> {\n  const params =\n    isIcmGame(game) && scenario\n      ? new URLSearchParams({ scenario, history })\n      : new URLSearchParams({ stack: String(stack), history });\n  const res = await fetch(`${gameBase(game)}/node?${params.toString()}`, {\n    headers: { Accept: \"application/json\" },\n  });\n  if (res.status === 404) return null;\n  if (!res.ok) {\n    notifyPlanRequired(res.status);\n    const body = await res.text().catch(() => \"\");\n    throw new Error(`GET node -> ${res.status}: ${body.slice(0, 200)}`);\n  }\n  const node = normalizeExplorerNode(game, (await res.json()) as ExplorerNodeRaw);\n  const sizes = raiseSizesFor(game, scenario);\n  for (const a of node.actions) {\n    if (a.sizeBb != null && a.sizeBb > 0) sizes[`${history}_${a.action}`] = a.sizeBb;\n  }\n  return node;\n}\n\n/** PLO5 nodes carry pool % + samples, not per-hand weights. Other games pass through. */\nexport function normalizeExplorerNode(_game: ExplorerGame, raw: ExplorerNodeRaw): NodeResponse {\n  return {\n    game: \"nl\",\n    stack: raw.stack,\n    history: raw.history,\n    actor: raw.actor,\n    continuingCombos: raw.continuingCombos,\n    ...(raw.evUnit === \"usd\" ? { evUnit: \"usd\" as const } : {}),\n    actions: (raw.actions ?? []).map((a) => ({\n      action: a.action,\n      kind: a.action === \"AI\" ? \"allin\" : a.kind,\n      weights: a.weights ?? {},\n      evs: a.evs,\n      sizePct: a.sizePct,\n      combos: a.combos ?? a.hands,\n      poolPct: a.poolPct,\n      always: a.always,\n      mixed: a.mixed,\n      ...(a.sizeBb != null ? { sizeBb: a.sizeBb } : {}),\n    })),\n  };\n}\n\nconst nodeCache = new Map<string, Promise<NodeResponse | null>>();\n\n/**\n * `getNodeForGameOrNull` memoized per (game, stack, history) — including the\n * null (404) answer. The Explorer prefetches a node for every seat the user\n * could skip ahead to, and those fold-through histories repeat constantly as\n * the walk moves back and forth, so they must not re-hit the network.\n */\nexport function getNodeForGameOrNullCached(\n  game: ExplorerGame,\n  stack: number,\n  history: string,\n  scenario?: string | null,\n): Promise<NodeResponse | null> {\n  const key = `${datasetKey(game, scenario)}:${stack}:${history}`;\n  const hit = nodeCache.get(key);\n  if (hit) return hit;\n  const promise = getNodeForGameOrNull(game, stack, history, scenario);\n  nodeCache.set(key, promise);\n  promise.catch(() => nodeCache.delete(key));\n  return promise;\n}\n\nexport function getNode(stack: number, history: string): Promise<NodeResponse> {\n  const params = new URLSearchParams({ stack: String(stack), history });\n  return getJson<NodeResponse>(`${rangesUrl(\"nl/node\")}?${params.toString()}`);\n}\n\n/**\n * Same decision node as `getNode`, read from the v2 dataset whose bundles also\n * carry per-hand EV (small blinds) on each action. v2 mirrors v1's coverage\n * (all stacks/positions), so the Explorer reads v2 to power its EV column.\n */\nexport function getNodeV2(stack: number, history: string): Promise<NodeResponse> {\n  const params = new URLSearchParams({ stack: String(stack), history });\n  return getJson<NodeResponse>(`${rangesUrl(\"nl/v2/node\")}?${params.toString()}`);\n}\n\n/**\n * Like `getNodeV2`, but returns null when the dataset has no decision at this\n * history (HTTP 404) — i.e. the preflop betting round has closed on this line.\n * The Explorer uses this to walk the full multiway tree and detect the end of\n * preflop, rather than assuming where the line stops. Throws on real failures.\n */\nexport async function getNodeV2OrNull(\n  stack: number,\n  history: string,\n): Promise<NodeResponse | null> {\n  const params = new URLSearchParams({ stack: String(stack), history });\n  const res = await fetch(`${rangesUrl(\"nl/v2/node\")}?${params.toString()}`, {\n    headers: { Accept: \"application/json\" },\n  });\n  if (res.status === 404) return null;\n  if (!res.ok) {\n    notifyPlanRequired(res.status);\n    const body = await res.text().catch(() => \"\");\n    throw new Error(`GET node -> ${res.status}: ${body.slice(0, 200)}`);\n  }\n  return (await res.json()) as NodeResponse;\n}\n\nexport { ROOT_HISTORY };\n\nexport interface Plo5HandStrategy {\n  hand: string;\n  hdvHand: string;\n  isoMapped: boolean;\n  actions: { action: string; kind: ActionKind; freq: number; ev_sb: number | null }[];\n}\n\nexport interface Plo5ListedHand {\n  hand: string;\n  freq: number;\n  ev: number | null;\n}\n\nexport interface Plo5ActionList {\n  action: string;\n  kind: ActionKind;\n  poolPct: number;\n  hands: number;\n  listed: Plo5ListedHand[];\n  listedTotal: number;\n}\n\n/** Per-action hand list for the Explorer breakdown (top by EV). */\nexport async function getPlo5NodeList(\n  stack: number,\n  history: string,\n  limit = 200,\n  ranks?: string,\n  minFreq?: number,\n  cats?: readonly string[],\n): Promise<Plo5ActionList[]> {\n  const params = new URLSearchParams({\n    stack: String(stack),\n    history,\n    list: \"1\",\n    limit: String(limit),\n  });\n  if (ranks) params.set(\"ranks\", ranks);\n  if (minFreq) params.set(\"minFreq\", String(minFreq));\n  if (cats?.length) params.set(\"cats\", cats.join(\",\"));\n  const res = await fetch(`${rangesUrl(\"plo5/node\")}?${params.toString()}`, {\n    headers: { Accept: \"application/json\" },\n  });\n  const data = (await res.json().catch(() => null)) as\n    | { error?: string; actions?: Plo5ActionList[] }\n    | null;\n  notifyPlanRequired(res.status);\n  if (!res.ok) throw new Error(data?.error || `GET plo5 list -> ${res.status}`);\n  return data?.actions ?? [];\n}\n\n/** Point-lookup one five-card combo at a PLO5 node. */\n/** The node's hand-category tree (shares + action splits), reach-weighted. */\nexport async function getPlo5Categories(stack: number, history: string): Promise<CategoryTree> {\n  const params = new URLSearchParams({ stack: String(stack), history });\n  const res = await fetch(`${rangesUrl(\"plo5/categories\")}?${params.toString()}`, {\n    headers: { Accept: \"application/json\" },\n  });\n  const data = (await res.json().catch(() => null)) as (CategoryTree & { error?: string }) | null;\n  notifyPlanRequired(res.status);\n  if (!res.ok) throw new Error(data?.error || `GET plo5 categories -> ${res.status}`);\n  if (!data) throw new Error(\"GET plo5 categories -> empty body\");\n  return data;\n}\n\nexport async function getPlo5HandStrategy(\n  stack: number,\n  history: string,\n  hand: string,\n): Promise<Plo5HandStrategy> {\n  const params = new URLSearchParams({ stack: String(stack), history, hand });\n  const res = await fetch(`${rangesUrl(\"plo5/node\")}?${params.toString()}`, {\n    headers: { Accept: \"application/json\" },\n  });\n  const data = (await res.json().catch(() => null)) as\n    | (Plo5HandStrategy & { error?: string })\n    | null;\n  notifyPlanRequired(res.status);\n  if (!res.ok) {\n    throw new Error(data?.error || `GET plo5 hand -> ${res.status}`);\n  }\n  if (!data) throw new Error(\"GET plo5 hand -> empty body\");\n  return data;\n}\n\n/** Per-action hand list for the PLO6 HU Explorer breakdown (top by EV). */\nexport async function getPlo6HuNodeList(\n  stack: number,\n  history: string,\n  limit = 200,\n  ranks?: string,\n): Promise<Plo5ActionList[]> {\n  const params = new URLSearchParams({\n    stack: String(stack),\n    history,\n    list: \"1\",\n    limit: String(limit),\n  });\n  if (ranks) params.set(\"ranks\", ranks);\n  const res = await fetch(`${rangesUrl(\"plo6hu/node\")}?${params.toString()}`, {\n    headers: { Accept: \"application/json\" },\n  });\n  const data = (await res.json().catch(() => null)) as\n    | { error?: string; actions?: Plo5ActionList[] }\n    | null;\n  notifyPlanRequired(res.status);\n  if (!res.ok) throw new Error(data?.error || `GET plo6hu list -> ${res.status}`);\n  return data?.actions ?? [];\n}\n\n/** Point-lookup one six-card combo at a PLO6 HU node. */\nexport async function getPlo6HuHandStrategy(\n  stack: number,\n  history: string,\n  hand: string,\n): Promise<Plo5HandStrategy> {\n  const params = new URLSearchParams({ stack: String(stack), history, hand });\n  const res = await fetch(`${rangesUrl(\"plo6hu/node\")}?${params.toString()}`, {\n    headers: { Accept: \"application/json\" },\n  });\n  const data = (await res.json().catch(() => null)) as\n    | (Plo5HandStrategy & { error?: string })\n    | null;\n  notifyPlanRequired(res.status);\n  if (!res.ok) {\n    throw new Error(data?.error || `GET plo6hu hand -> ${res.status}`);\n  }\n  if (!data) throw new Error(\"GET plo6hu hand -> empty body\");\n  return data;\n}\n\n// ─── History parsing (mirror of mobile parse-history.ts) ───────────────────\n\n// PLO raises are MonkerSolver depth tags, optionally size-disambiguated\n// (\"Open\", \"3B\", \"Open-40075\"). NL raises are always \"<pct>%\", so the two\n// namespaces can't collide.\nconst PLO_RAISE_RE = /^(Open|3B|4B|5B|6B|7B|8B)(?:-(\\d+))?$/;\n\nconst PLO_RAISE_LABEL: Record<string, string> = {\n  Open: \"Pot\",\n  \"3B\": \"3-Bet\",\n  \"4B\": \"4-Bet\",\n  \"5B\": \"5-Bet\",\n  \"6B\": \"6-Bet\",\n  \"7B\": \"7-Bet\",\n  \"8B\": \"8-Bet\",\n};\n\nconst PLO5_RAISE_RE = /^Raise-(\\d+(?:\\.\\d+)?)x$/i;\n\nfunction isAllInToken(token: string): boolean {\n  return token === \"AI\" || token === \"AllIn\";\n}\n\nfunction isRaiseToken(token: string): boolean {\n  return token.endsWith(\"%\") || PLO_RAISE_RE.test(token) || PLO5_RAISE_RE.test(token);\n}\n\nfunction displayAction(token: string): string {\n  if (token === \"Fold\") return \"Fold\";\n  if (token === \"Call\") return \"Call\";\n  if (token === \"Check\") return \"Check\";\n  if (isAllInToken(token)) return \"All-in\";\n  const plo5 = token.match(PLO5_RAISE_RE);\n  if (plo5) return `Raise ${plo5[1]}bb`;\n  const plo = token.match(PLO_RAISE_RE);\n  if (plo) return PLO_RAISE_LABEL[plo[1]] ?? token;\n  return token;\n}\n\nfunction sumCommitted(seats: Record<Position, SeatState>, order: Position[]): number {\n  let s = 0;\n  for (const p of order) s += seats[p].committed;\n  return s;\n}\n\n/**\n * Walk a preflop history into a table state. `order` selects the dataset's seat\n * ring (6-max by default, 9-max for the PLO 9-max bundles).\n */\nexport function parseHistory(\n  history: string,\n  stackBb: number,\n  order: Position[] = PLAY_ORDER,\n  anteBb = 0,\n  /**\n   * Raise-to in bb per line (`\"<history>_<token>\"` → bb), from the feed's\n   * `sizeBb` (see `raiseSizesFor`). A sized raise wins over decoding its\n   * token and is shown as a GTO Wizard pot percentage. Only the ICM sets pass it.\n   */\n  sizes?: Record<string, number>,\n  /** Per-seat stacks behind when they differ (ICM tables); else every seat has `stackBb`. */\n  seatStacks?: Partial<Record<Position, number>>,\n): ParsedTable {\n  const stackOf = (p: Position) => seatStacks?.[p] ?? stackBb;\n  const seats: Record<Position, SeatState> = Object.create(null);\n  for (const p of order) {\n    seats[p] = {\n      position: p,\n      action: null,\n      committed: 0,\n      remaining: stackOf(p),\n      folded: false,\n      isHero: false,\n      isDealer: p === \"BTN\",\n    };\n  }\n  if (seats.SB) seats.SB.committed = 0.5;\n  else if (seats.BTN && !seats.SB) seats.BTN.committed = 0.5;\n  if (seats.BB) seats.BB.committed = 1;\n\n  const tokens = history.split(\"_\");\n  let prevIdx = -1;\n  let toCall = 1;\n\n  for (let i = 0; i + 1 < tokens.length; i += 2) {\n    const pos = tokens[i] as Position;\n    const action = tokens[i + 1];\n    const posIdx = order.indexOf(pos);\n    if (posIdx === -1) continue;\n\n    if (prevIdx >= 0) {\n      let cur = (prevIdx + 1) % order.length;\n      while (cur !== posIdx) {\n        const s = seats[order[cur]];\n        if (!s.folded && s.action === null) {\n          s.folded = true;\n          s.action = \"Fold\";\n        }\n        cur = (cur + 1) % order.length;\n      }\n    }\n\n    seats[pos].action = displayAction(action);\n    const sized = sizes?.[`${tokens.slice(0, i + 1).join(\"_\")}_${action}`];\n    if (sized !== undefined && action !== \"Fold\" && action !== \"Call\" && action !== \"Limp\") {\n      // The feed's raise-to: GTO Wizard's percent is the chips beyond the\n      // call over the pot after the call.\n      const raiseTo = Math.min(stackOf(pos), sized);\n      const callExtra = Math.max(0, toCall - seats[pos].committed);\n      const potAfterCall = sumCommitted(seats, order) + anteBb + callExtra;\n      if (isAllInToken(action) || raiseTo >= stackOf(pos)) {\n        seats[pos].action = \"All-in\";\n      } else if (potAfterCall > 0) {\n        seats[pos].action = `Raise ${Math.round(((raiseTo - toCall) / potAfterCall) * 100)}%`;\n      }\n      seats[pos].committed = raiseTo;\n      toCall = Math.max(toCall, raiseTo);\n    } else if (action === \"Fold\") {\n      seats[pos].folded = true;\n    } else if (action === \"Call\" || action === \"Limp\" || action === \"Check\") {\n      seats[pos].committed = toCall;\n    } else if (isAllInToken(action)) {\n      seats[pos].committed = stackOf(pos);\n      toCall = Math.max(toCall, stackOf(pos));\n    } else if (action.endsWith(\"%\")) {\n      const potBefore = sumCommitted(seats, order);\n      const raiseTo = toCall + (parseFloat(action) / 100) * potBefore;\n      seats[pos].committed = raiseTo;\n      toCall = raiseTo;\n    } else if (PLO_RAISE_RE.test(action)) {\n      // Every PLO raise in these packs is pot-sized (capped by the stack):\n      // raise-to = call amount + pot after the call.\n      const potBefore = sumCommitted(seats, order);\n      const raiseTo = Math.min(stackBb, toCall + (potBefore + (toCall - seats[pos].committed)));\n      seats[pos].committed = raiseTo;\n      toCall = raiseTo;\n    } else {\n      const plo5 = action.match(PLO5_RAISE_RE);\n      if (plo5) {\n        // Hydra \"Raise-4.7x\" is raise-to in big blinds.\n        const raiseTo = Math.min(stackBb, parseFloat(plo5[1]));\n        seats[pos].committed = raiseTo;\n        toCall = raiseTo;\n      }\n    }\n    prevIdx = posIdx;\n  }\n\n  const rawHero = (tokens[tokens.length - 1] || order[0]) as Position;\n  const hero = (order.includes(rawHero) ? rawHero : order[0]) as Position;\n  const heroIdx = order.indexOf(hero);\n  if (seats[hero]) seats[hero].isHero = true;\n\n  if (prevIdx >= 0 && heroIdx !== -1) {\n    let cur = (prevIdx + 1) % order.length;\n    while (cur !== heroIdx) {\n      const s = seats[order[cur]];\n      if (!s.folded && s.action === null) {\n        s.folded = true;\n        s.action = \"Fold\";\n      }\n      cur = (cur + 1) % order.length;\n    }\n  }\n\n  for (const p of order) {\n    seats[p].remaining = Math.max(0, stackOf(p) - seats[p].committed);\n  }\n\n  return { seats, pot: sumCommitted(seats, order) + anteBb, hero };\n}\n\n/**\n * The last seat to raise or jam preflop — the aggressor who takes the betting\n * lead into the flop. `null` in an unraised pot (nobody has the lead). The\n * history may end with a bare actor position (no action yet); that trailing\n * token is ignored, so pass `${history}_${action}` to include a just-taken\n * action that isn't in the history string yet.\n */\nexport function lastPreflopAggressor(\n  history: string,\n  order: Position[] = PLAY_ORDER,\n): Position | null {\n  const tokens = history.split(\"_\");\n  let aggressor: Position | null = null;\n  for (let i = 0; i + 1 < tokens.length; i += 2) {\n    const pos = tokens[i] as Position;\n    const action = tokens[i + 1];\n    if (order.indexOf(pos) === -1) continue;\n    if (isAllInToken(action) || isRaiseToken(action)) aggressor = pos;\n  }\n  return aggressor;\n}\n\n/** The seat that acts after `action` is taken; null if the line terminates. */\nexport function nextActorAfter(\n  history: string,\n  action: string,\n  stackBb: number,\n  order: Position[] = PLAY_ORDER,\n): Position | null {\n  const { seats } = parseHistory(history, stackBb, order);\n  const tokens = history.split(\"_\");\n  const actor = tokens[tokens.length - 1] as Position;\n  const actorIdx = order.indexOf(actor);\n  if (actorIdx === -1) return null;\n\n  const liveAfter = new Set<Position>();\n  for (const p of order) if (!seats[p].folded) liveAfter.add(p);\n  if (action === \"Fold\") liveAfter.delete(actor);\n\n  for (let i = 1; i <= order.length; i++) {\n    const cand = order[(actorIdx + i) % order.length];\n    if (liveAfter.has(cand)) return cand;\n  }\n  return null;\n}\n\n// ─── Heads-up scenario resolution (mirror of mobile scenario.ts) ───────────\n\n/** Assign OOP/IP by postflop order — the earlier-acting seat is OOP. */\nexport function assignOopIp(a: Position, b: Position): { oop: Position; ip: Position } {\n  const ia = POSTFLOP_ORDER.indexOf(a);\n  const ib = POSTFLOP_ORDER.indexOf(b);\n  return ia <= ib ? { oop: a, ip: b } : { oop: b, ip: a };\n}\n\n/** Keep only known 169-grid classes, clamped to [0, 1] (drops zero/stray keys). */\nexport function clampWeights(weights: RangeWeights): RangeWeights {\n  const next: RangeWeights = {};\n  for (const hand of ALL_HANDS) {\n    const w = weights[hand];\n    if (w && w > 0) next[hand] = Math.min(w, 1);\n  }\n  return next;\n}\n\n/** The highest-committed non-folded seat other than `actor` (blinds count). */\nfunction mostRecentRaiser(\n  seats: Record<Position, SeatState>,\n  actor: Position,\n): { position: Position; committed: number } | null {\n  let best: { position: Position; committed: number } | null = null;\n  for (const p of PLAY_ORDER) {\n    if (p === actor) continue;\n    const s = seats[p];\n    if (s.folded) continue;\n    if (!best || s.committed > best.committed) best = { position: p, committed: s.committed };\n  }\n  return best;\n}\n\nexport type ResolveResult =\n  | { kind: \"walk\"; nextHistory: string }\n  | { kind: \"headsup\"; survivors: [Position, Position]; oop: Position; ip: Position }\n  | { kind: \"terminal\" };\n\n/**\n * Given the current history (ending in the actor) and the action they took,\n * return the next state of the heads-up walk. See the mobile module for the\n * precise fold/call/re-raise routing rules.\n */\nexport function resolveAfterAction(\n  history: string,\n  action: string,\n  actionKind: string,\n  stack: number,\n): ResolveResult {\n  const { seats } = parseHistory(history, stack);\n  const tokens = history.split(\"_\");\n  const actor = tokens[tokens.length - 1] as Position;\n\n  const agg = mostRecentRaiser(seats, actor);\n  const facingRaise = !!agg && agg.committed > 1;\n\n  if (actionKind === \"fold\") {\n    let live = 0;\n    for (const p of PLAY_ORDER) if (!seats[p].folded && p !== actor) live++;\n    if (live <= 1) return { kind: \"terminal\" };\n    const next = nextActorAfter(history, action, stack);\n    if (!next) return { kind: \"terminal\" };\n    return { kind: \"walk\", nextHistory: `${history}_${action}_${next}` };\n  }\n\n  if (actionKind === \"call\") {\n    if (facingRaise && agg) {\n      const { oop, ip } = assignOopIp(agg.position, actor);\n      return { kind: \"headsup\", survivors: [agg.position, actor], oop, ip };\n    }\n    const next = nextActorAfter(history, action, stack);\n    if (!next) return { kind: \"terminal\" };\n    return { kind: \"walk\", nextHistory: `${history}_${action}_${next}` };\n  }\n\n  // raise or allin\n  if (facingRaise && agg) {\n    return {\n      kind: \"walk\",\n      nextHistory: buildReturnHistory(history, action, seats, actor, agg.position),\n    };\n  }\n  const next = nextActorAfter(history, action, stack);\n  if (!next) return { kind: \"terminal\" };\n  return { kind: \"walk\", nextHistory: `${history}_${action}_${next}` };\n}\n\n/** After a re-raise, route action back to `responder`, folding seats in between. */\nfunction buildReturnHistory(\n  history: string,\n  action: string,\n  seats: Record<Position, SeatState>,\n  actor: Position,\n  responder: Position,\n): string {\n  const parts = [history, action];\n  const actorIdx = PLAY_ORDER.indexOf(actor);\n  for (let i = 1; i <= PLAY_ORDER.length; i++) {\n    const seat = PLAY_ORDER[(actorIdx + i) % PLAY_ORDER.length];\n    if (seat === responder) break;\n    if (!seats[seat].folded) parts.push(seat, \"Fold\");\n  }\n  parts.push(responder);\n  return parts.join(\"_\");\n}\n\n// ─── Display helpers ───────────────────────────────────────────────────────\n\nconst KIND_ORDER: Record<string, number> = { fold: 0, call: 1, raise: 2, allin: 3, other: 4 };\n\nexport function sortActionsForDisplay(actions: NodeAction[]): NodeAction[] {\n  return [...actions].sort((a, b) => {\n    const ka = KIND_ORDER[a.kind] ?? 99;\n    const kb = KIND_ORDER[b.kind] ?? 99;\n    if (ka !== kb) return ka - kb;\n    return (a.sizePct ?? a.sizeBb ?? 0) - (b.sizePct ?? b.sizeBb ?? 0);\n  });\n}\n\n/** Where the actor stands, for labelling a sized raise as a pot percentage. */\nexport interface RaiseContext {\n  /** Pot before the actor acts, antes included. */\n  potBb: number;\n  /** The amount to call to (the largest commitment so far). */\n  toCallBb: number;\n  /** What the actor has in already. */\n  committedBb: number;\n  /** The actor's stack, all in (committed + behind). */\n  stackBb: number;\n}\n\n/**\n * GTO Wizard's label for a raise the feed sized (`sizeBb`): the chips beyond\n * the call over the pot after the call (\"Raise 29%\"); a raise to the whole\n * stack is \"All-in <stack>\". Null when the action isn't a sized raise.\n */\nexport function sizedRaiseLabel(action: NodeAction, ctx: RaiseContext): string | null {\n  if (action.kind !== \"raise\" && action.kind !== \"allin\") return null;\n  if (action.sizeBb == null || action.sizeBb <= 0) return null;\n  const to = Math.min(action.sizeBb, ctx.stackBb);\n  if (action.kind === \"allin\" || action.action === \"AI\" || to >= ctx.stackBb - 1e-6) {\n    return `All-in ${formatBb(to)}`;\n  }\n  const potAfterCall = ctx.potBb + Math.max(0, ctx.toCallBb - ctx.committedBb);\n  if (potAfterCall <= 0) return null;\n  return `Raise ${Math.round(((to - ctx.toCallBb) / potAfterCall) * 100)}%`;\n}\n\n/** The actor's `RaiseContext` from a parsed walk. */\nexport function raiseContextAt(table: ParsedTable): RaiseContext {\n  const seat = table.seats[table.hero];\n  let toCall = 0;\n  for (const p of Object.keys(table.seats) as Position[]) {\n    toCall = Math.max(toCall, table.seats[p].committed);\n  }\n  return {\n    potBb: table.pot,\n    toCallBb: toCall,\n    committedBb: seat?.committed ?? 0,\n    stackBb: (seat?.committed ?? 0) + (seat?.remaining ?? 0),\n  };\n}\n\nexport function labelForAction(action: NodeAction, stack: number): string {\n  if (action.kind === \"fold\") return \"Fold\";\n  if (action.action === \"Limp\") return \"Limp\";\n  if (action.action === \"Check\") return \"Check\";\n  if (action.kind === \"call\") return \"Call\";\n  if (action.kind === \"allin\" || action.action === \"AI\") return `All-in ${stack}`;\n  if (action.action === \"Open\") return \"Open\";\n  const plo5 = action.action.match(PLO5_RAISE_RE);\n  if (plo5) return `Raise ${plo5[1]}bb`;\n  if (action.kind === \"raise\") return `Raise ${action.action}`;\n  return action.action;\n}\n\n/**\n * `labelForAction` for the MonkerSolver PLO packs: raises read as a percentage\n * of the pot, GTO Wizard style (\"Open\" and \"3B\" are pot raises, \"Raise 100%\";\n * \"Open-40075\" is \"Raise 75%\"). Not for NL, whose \"Open\" token isn't pot-sized.\n */\nexport function ploLabelForAction(action: NodeAction, stack: number): string {\n  if (action.kind === \"raise\") {\n    const pct = ploRaisePotPct(action.action);\n    if (pct !== null) return `Raise ${pct}%`;\n  }\n  return labelForAction(action, stack);\n}\n\nexport function formatBb(v: number): string {\n  if (v < 100) return v.toFixed(v % 1 === 0 ? 0 : 1);\n  return Math.round(v).toString();\n}\n",
      "type": "registry:lib",
      "target": "lib/solver/preflop.ts"
    },
    {
      "path": "src/lib/solver/range-model.ts",
      "content": "// Range model shared by the solver's scenario selector and the solve call.\n//\n// A range is a 169-class map (hand → weight in [0, 1]) — the same shape the NL\n// ranges API returns (NodeAction.weights). At solve time we serialize it to the\n// solver-engine grammar (see solver-engine/src/range.rs), which parses `AA`,\n// `AKs`, `AKo`, and `hand:weight` tokens, plus `random` for a full range.\n\nimport { comboCount } from \"@/lib/nl-ranges/range\";\n\nexport type RangeWeights = Record<string, number>;\nexport type RangePlayer = \"oop\" | \"ip\";\n\nconst RANKS = \"AKQJT98765432\";\n\n/**\n * Every 169 hand-class in grid order: suited upper-right, offsuit lower-left,\n * pairs on the diagonal (\"AA\", \"AKs\", …, \"32o\"). Higher rank is written first.\n */\nexport const ALL_HANDS: string[] = (() => {\n  const hands: string[] = [];\n  for (let r = 0; r < 13; r++) {\n    for (let c = 0; c < 13; c++) {\n      const hi = RANKS[Math.min(r, c)];\n      const lo = RANKS[Math.max(r, c)];\n      if (r === c) hands.push(`${RANKS[r]}${RANKS[r]}`);\n      else if (r < c) hands.push(`${hi}${lo}s`);\n      else hands.push(`${hi}${lo}o`);\n    }\n  }\n  return hands;\n})();\n\n/** Concrete combos a class represents, ignoring card removal (pair 6, suited 4, offsuit 12). */\nexport function comboCountOf(hand: string): number {\n  return comboCount(hand);\n}\n\n/** Weighted concrete-combo count (Σ weight × comboCount). */\nexport function totalCombos(weights: RangeWeights): number {\n  let total = 0;\n  for (const hand of ALL_HANDS) {\n    const w = weights[hand] ?? 0;\n    if (w > 0) total += w * comboCountOf(hand);\n  }\n  return total;\n}\n\n/** A full range — every class at weight 1 (equivalent to the engine's `random`). */\nexport function fullRange(): RangeWeights {\n  const weights: RangeWeights = {};\n  for (const hand of ALL_HANDS) weights[hand] = 1;\n  return weights;\n}\n\nexport function isEmptyRange(weights: RangeWeights): boolean {\n  return ALL_HANDS.every((hand) => (weights[hand] ?? 0) <= 0);\n}\n\nexport function isFullRange(weights: RangeWeights): boolean {\n  return ALL_HANDS.every((hand) => (weights[hand] ?? 0) >= 0.999);\n}\n\n/**\n * Serialize to the solver-engine range grammar. A full range collapses to\n * `random`; otherwise we emit `hand` for full-weight classes and `hand:weight`\n * for partial ones, comma-joined. Zero-weight classes are omitted.\n */\nexport function weightsToEngineString(weights: RangeWeights): string {\n  if (isFullRange(weights)) return \"random\";\n  const parts: string[] = [];\n  for (const hand of ALL_HANDS) {\n    const w = weights[hand] ?? 0;\n    if (w <= 0) continue;\n    parts.push(w >= 0.999 ? hand : `${hand}:${Number(w.toFixed(3))}`);\n  }\n  return parts.join(\",\");\n}\n",
      "type": "registry:lib",
      "target": "lib/solver/range-model.ts"
    },
    {
      "path": "src/lib/solver/types.ts",
      "content": "// Solver wire types — mirror the `solve` engine's JSON schema (solver-engine\n// `src/api.rs`) and the `/api/solver/*` proxy responses. Kept in sync by hand\n// with the Rust `Config`/`Output` structs.\n\n/** Game variant. NLHE uses the 169-class grid; PLO uses 4-card combos. */\nexport type SolverVariant = \"nlhe\" | \"plo\";\n\nexport interface SolverConfig {\n  /** Game variant. Omitted = \"nlhe\" (the engine default). */\n  variant?: SolverVariant;\n  /** Board cards, e.g. \"Qs Jh 2h\" (3/4/5 cards → flop/turn/river). */\n  board: string;\n  start_street?: \"flop\" | \"turn\" | \"river\";\n  /** Dead money in the middle at the start. */\n  pot: number;\n  /** Chips behind each player. */\n  effective_stack: number;\n  /** Bet/raise sizes as pot fractions, e.g. [0.5, 1]. */\n  bet_sizes: number[];\n  /** Always offer a shove. */\n  add_allin: boolean;\n  /** Max bets+raises per street. */\n  max_aggressions: number;\n  /** River-only bet sizes (pot fractions) — a coarser river action abstraction\n   *  (#220) that keeps flop trees solvable. Empty/omitted = use `bet_sizes`. */\n  river_bet_sizes?: number[];\n  /** River-only aggression cap. Omitted = `max_aggressions` on the river too. */\n  river_max_aggressions?: number;\n  /** GTO-Wizard-style per-street, per-player tree overrides. Unset fields fall\n   *  back to the flat fields above; `[]` is meaningful (no bets/raises for\n   *  that player on that street). HU postflop only. */\n  sizing?: TreeSizingConfig;\n  /** Betting limit: \"nolimit\" (default) or \"pot\" (required for PLO). */\n  limit?: \"nolimit\" | \"pot\";\n  /** OOP (player 0) range; \"random\" = full. */\n  oop_range: string;\n  /** IP (player 1) range. */\n  ip_range: string;\n  /** Max DCFR iterations. */\n  iterations: number;\n  /** Optional early stop: exploitability as a percent of the pot. */\n  target_exploitability?: number;\n  /** Optional early stop: end once a progress chunk improves exploitability\n   *  by less than this relative fraction (engine convergence plateau, #243). */\n  convergence_plateau?: number;\n  /** CFR variant: \"dcfr\" (engine default) or \"pcfr+\" (predictive CFR+ —\n   *  ~1.9× fewer iterations to a given exploitability, #253). */\n  cfr_variant?: \"dcfr\" | \"pcfr+\";\n  /** Keep this job's accumulator snapshot on the worker so a follow-up solve\n   *  can warm-start from it (#262). Worker holds the last few, LRU. */\n  keep_snapshot?: boolean;\n  /** Warm-start from a previous job's snapshot (same tree geometry + ranges —\n   *  the engine fingerprint-rejects any mismatch). Job id, never a path. */\n  warm_start_from?: string;\n  /** Iterations between progress ticks (0 = none). */\n  log_interval: number;\n  /** Also return per-combo EV (expected chips) at the root. */\n  dump_ev?: boolean;\n  /** With `dump_nodes`, also return each dumped node's per-action EV, for that\n   *  node's own acting player. Roughly doubles the numeric payload of a\n   *  dump, so it is opt-in per solve rather than on everywhere. */\n  dump_action_evs?: boolean;\n  /** Walk and return every action node's strategy (the full betting tree). */\n  dump_nodes?: boolean;\n  /** When dumping nodes, stop the walk after this many chance deals past the\n   *  start street (0 = start-street decisions only). Caps the dumped tree size. */\n  dump_max_deals?: number;\n  /** Node locks (#268): each listed action node plays its given strategy\n   *  verbatim while the rest of the tree re-equilibrates against it. Locked\n   *  re-solves must ALWAYS pair with `warm_start_from` (the unlocked base\n   *  job): a lock that zeroes an action leaves its subtree with zero\n   *  counterfactual reach, so a COLD locked solve can never train the\n   *  response there and reads silently wrong (PR #269). */\n  locked_nodes?: LockedNode[];\n  /** CFR-D re-solving gadget (#233). Present = this solve is a *safe* subgame\n   *  re-solve: the opponent's root behavior becomes the augmented game (per\n   *  combo, Terminate and collect the carried CFV, or Follow into the\n   *  subgame), so the answer stays consistent with the parent equilibrium\n   *  instead of assuming the opponent always enters. NLHE only. The engine\n   *  rejects it together with `cfr_variant: \"pcfr+\"` (the gadget stays DCFR)\n   *  and with snapshot warm starts (gadget state lives outside the\n   *  accumulators). */\n  resolve?: ResolveConfig;\n  /** Bootstrap carry (#233): on a plain (non-gadget) solve, also return\n   *  `SolverResult.resolve` holding the opponent CFV promises for the given\n   *  resolver (0 = OOP, 1 = IP) — the seed for the first re-solve below this\n   *  node. Ignored by the engine when `resolve` is set. */\n  emit_carry_for?: 0 | 1;\n}\n\n/**\n * CFR-D gadget input (#233), mirroring the engine's `ResolveConfig`.\n *\n * `opponent_cfvs` are the promises produced by the parent solve — one entry per\n * opponent combo, in chips. They come from `SolverResult.resolve.carry[i]` of\n * the parent, where `i` indexes the resolver's root action that was taken.\n * Never hand-authored: a wrong promise silently biases the whole subgame.\n */\nexport interface ResolveConfig {\n  /** 0 = re-solve for OOP (IP is the constrained opponent), 1 = the reverse. */\n  resolver: 0 | 1;\n  /** `[combo, cfv]` pairs — the opponent's counterfactual value promises. */\n  opponent_cfvs: [string, number][];\n}\n\n/** CFR-D gadget output (#233), mirroring the engine's `ResolveOutput`. */\nexport interface ResolveOutput {\n  /** Per-combo average Follow frequency — the opponent's reconstructed entry\n   *  probability. Multiply by their base range for the range this re-solve\n   *  believes they actually bring in. */\n  avg_follow: [string, number][];\n  /** Per resolver root action (same order as `root.actions`): the opponent's\n   *  per-combo CFVs, i.e. the promises to carry into the next re-solve after\n   *  taking that action. Empty when the root isn't the resolver's decision. */\n  carry: [string, number][][];\n}\n\n/** One street's sizing overrides — mirror of the engine's `StreetSizingConfig`\n *  (api.rs). All pot fractions. */\nexport interface StreetSizingConfig {\n  oop_bet_sizes?: number[];\n  ip_bet_sizes?: number[];\n  /** Raise (2nd+ aggression) sizes. Omitted = mirror the player's street bet\n   *  sizes when set, else the legacy raise chain. */\n  oop_raise_sizes?: number[];\n  ip_raise_sizes?: number[];\n  /** Offer a shove on this street. Omitted = global `add_allin`. */\n  oop_allin?: boolean;\n  ip_allin?: boolean;\n  /** Street aggression cap. Omitted = the legacy cap chain. */\n  max_aggressions?: number;\n}\n\n/** One node-specific override (GTOW deep tree editing) — mirror of the\n *  engine's `NodeSizingConfig`. `path` uses the `dump_nodes` encoding\n *  (\"Check\", \"Bet 4\", \"Call 4\", amounts 1-decimal; chance steps \"deal\" =\n *  every runout card). The engine rejects a path that matches no node. */\nexport interface NodeSizingConfig {\n  path: string[];\n  /** Pot-fraction sizes for this node's bets/raises; `[]` = none. */\n  sizes?: number[];\n  allin?: boolean;\n}\n\n/** Per-street sizing overrides — mirror of the engine's `SizingConfig`. */\nexport interface TreeSizingConfig {\n  flop?: StreetSizingConfig;\n  turn?: StreetSizingConfig;\n  river?: StreetSizingConfig;\n  /** Node-specific overrides; win over the street rules. */\n  nodes?: NodeSizingConfig[];\n}\n\n/**\n * One locked node (#268), mirroring the engine's `LockedNode` (api.rs).\n * Exactly one of `hands` / `all_hands` must be present.\n */\nexport interface LockedNode {\n  /** Action path from the root in the `dump_nodes` encoding — \"Check\",\n   *  \"Bet 3.2\" (amounts rounded to 1 decimal), \"deal:Td\"; `[]` = the root. */\n  path: string[];\n  /** Per-combo lock: combo string (\"AhKs\") → one frequency per action,\n   *  parallel to the node's action list (dump order). Unlisted live combos\n   *  lock to uniform unless `default: \"reject\"`. */\n  hands?: Record<string, number[]>;\n  /** Aggregate lock: one frequency vector applied to every combo of the\n   *  acting player's range. Mutually exclusive with `hands`. */\n  all_hands?: number[];\n  /** What live combos not listed in `hands` play: \"uniform\" (default) or\n   *  \"reject\" (error unless every live combo is listed). */\n  default?: \"uniform\" | \"reject\";\n}\n\n/** A reference to a stored PLO preflop range, resolved server-side. */\nexport interface PloRangeRef {\n  stack: number;\n  /** Range spot path ending in an action, e.g. \"UTG_Fold_…_BTN_Open\". */\n  spot: string;\n}\n\n/**\n * The body POSTed to `/api/solver/jobs`. Extends the engine config with optional\n * PLO range references: when present (PLO only), the server resolves them to full\n * ranges and overrides `oop_range` / `ip_range`, so huge ranges never ship to the\n * browser. The ref fields are stripped before the config reaches the worker.\n */\nexport interface SolveRequest extends SolverConfig {\n  oop_range_ref?: PloRangeRef;\n  ip_range_ref?: PloRangeRef;\n  /**\n   * \"AI solve\": ask the server for a depth-limited flop solve that terminates\n   * at the turn boundary with the value net (GTO-Wizard-AI-style — fast but\n   * approximate). Translated server-side to `depth_limited` + the deployment's\n   * net path; the raw engine fields are never client-settable.\n   */\n  aiSolve?: boolean;\n  /**\n   * Skip the shared solve cache and run this on the worker even if a stored\n   * result would have answered it. Needed when the *job* matters and not just\n   * the strategy: a locked re-solve warm-starts from the base job's worker\n   * snapshot (#269), which a cached answer doesn't have. Proxy-level — stripped\n   * before the config reaches the worker.\n   */\n  noCache?: boolean;\n}\n\n/** One streamed progress tick from a running solve. */\nexport interface SolverProgress {\n  iter: number;\n  chips: number;\n  percent: number;\n  elapsed_seconds: number;\n}\n\nexport type SolverActionLabel = \"Fold\" | \"Check\" | \"Call\" | \"Bet\" | \"Raise\" | \"AllIn\";\n\nexport interface SolverActionInfo {\n  label: SolverActionLabel;\n  /** Chips added by taking this action. */\n  add: number;\n}\n\nexport interface SolverHandStrategy {\n  /** Combo string: 4 chars for NLHE (\"AsAh\"), 8 chars for PLO (\"AsAhKsKd\"). */\n  combo: string;\n  /** Frequency per action, parallel to `root.actions`. */\n  freqs: number[];\n  /** Per-combo EV in chips (present only when the solve set `dump_ev`). */\n  ev?: number;\n  /** Chips this combo gives up by taking each action instead of the best action\n   *  the solved profile actually plays, parallel to `freqs` and never negative\n   *  (present only when the solve set `dump_action_evs`). The best played action\n   *  is exactly 0. Already measured from the acting player's own seat — no sign\n   *  flip on the consumer side.\n   *\n   *  A loss rather than an absolute EV because it is what a trainer needs and it\n   *  is the smaller of the two on the wire (measured on a converged flop pack:\n   *  15.4MB vs 16.4MB gzipped per board). */\n  ev_loss?: number[];\n}\n\n/**\n * One action node from the engine's `dump_nodes` walk (see `api.rs`). The\n * `path` is the action labels from the root to this node, e.g. [\"Bet 5.6\",\n * \"Call\"]; runout deals appear as \"deal:Td\" segments.\n */\nexport interface SolverNode {\n  path: string[];\n  player: 0 | 1 | 2;\n  /** Total pot at this node before the player acts (chips = bb here). */\n  pot: number;\n  actions: SolverActionInfo[];\n  hands: SolverHandStrategy[];\n  /** True when this node was locked in the solve (#268) — `hands` is the\n   *  locked strategy verbatim, not a CFR average. Serde-skipped when false. */\n  locked?: boolean;\n}\n\nexport interface SolverResult {\n  exploitability: { chips: number; percent: number };\n  iterations_run: number;\n  elapsed_seconds: number;\n  tree: {\n    action_nodes: number;\n    chance_nodes: number;\n    terminal_nodes: number;\n    strategy_floats: number;\n  };\n  root: {\n    player: 0 | 1 | 2;\n    actions: SolverActionInfo[];\n    hands: SolverHandStrategy[];\n  };\n  /** Every action node's strategy — present only when the solve set `dump_nodes`. */\n  nodes?: SolverNode[];\n  /** CFR-D output (#233) — present when the solve set `emit_carry_for` (the\n   *  bootstrap promises) or ran the gadget via `resolve`. */\n  resolve?: ResolveOutput;\n}\n",
      "type": "registry:lib",
      "target": "lib/solver/types.ts"
    },
    {
      "path": "src/lib/trainer/auth.ts",
      "content": "\"use client\";\n\n/**\n * Clerk session-token provider for the trainer's API calls.\n *\n * On pokerstudy.ai, `/api/trainer/*` is deliberately excluded from the Clerk\n * middleware matcher (see proxy.ts): it is the CORS-open bridge the mobile app\n * talks to, and those handlers verify a Bearer JWT themselves. `auth()`\n * therefore cannot read the session cookie on those routes — so the web trainer\n * authenticates the same way mobile does, with a Bearer token. pokerdata.io\n * (which installs this file from the registry with the shared Explorer) sends\n * the same token to its own same-origin routes. `<TrainerApp/>` registers the\n * getter from Clerk's `useAuth()` before mounting the drill loops.\n */\n\ntype TokenGetter = (options?: { skipCache?: boolean }) => Promise<string | null>;\n\nlet getToken: TokenGetter | null = null;\n/**\n * First `getToken()` call, kicked off the moment a provider registers. Clerk\n * answers `null` — not a promise that waits — while it is still minting the\n * session's first token, so without this warm-up the opening deal of a session\n * goes out unauthenticated and eats a 401 + retry.\n */\nlet primer: Promise<string | null> | null = null;\n\nexport function setTrainerTokenProvider(fn: TokenGetter | null): void {\n  getToken = fn;\n  if (!fn) {\n    primer = null;\n    return;\n  }\n  // Registration re-runs on every render of the host; only warm once.\n  primer ??= fn().catch(() => null);\n}\n\n/**\n * The current session token, or null when signed out / not yet registered.\n * `skipCache` forces Clerk to mint a fresh one, which is what a 401 retry wants.\n */\nexport async function trainerToken(options?: { skipCache?: boolean }): Promise<string | null> {\n  if (!getToken) return null;\n  try {\n    // Let the warm-up settle first: it means Clerk has a token to hand back\n    // rather than the `null` it returns mid-mint.\n    if (primer) await primer;\n    const token = await getToken(options);\n    if (token) return token;\n    // Still nothing (a session restore that outran the warm-up) — one short\n    // wait beats an unauthenticated request, which the server answers with a\n    // 401 the user sees as a failed deal.\n    await new Promise((resolve) => setTimeout(resolve, 250));\n    return await getToken(options);\n  } catch {\n    return null;\n  }\n}\n",
      "type": "registry:lib",
      "target": "lib/trainer/auth.ts"
    },
    {
      "path": "src/lib/trainer/hand.ts",
      "content": "import type { HandClass } from '@/lib/trainer/types';\n\nexport const RANKS = 'AKQJT98765432';\nexport const SUITS = ['c', 'd', 'h', 's'] as const;\n\nexport type Suit = (typeof SUITS)[number];\nexport type Rank = (typeof RANKS)[number];\nexport type Card = `${Rank}${Suit}`;\n\nexport function rankIndex(r: Rank): number {\n  return RANKS.indexOf(r);\n}\n\nexport function cardsToClass(c1: Card, c2: Card): HandClass {\n  const r1 = c1[0] as Rank;\n  const r2 = c2[0] as Rank;\n  const s1 = c1[1];\n  const s2 = c2[1];\n  if (r1 === r2) return `${r1}${r2}`;\n  const [hi, lo] = rankIndex(r1) < rankIndex(r2) ? [r1, r2] : [r2, r1];\n  return `${hi}${lo}${s1 === s2 ? 's' : 'o'}`;\n}\n\nexport function dealHand(rng: () => number = Math.random): [Card, Card] {\n  const deck: Card[] = [];\n  for (const r of RANKS) for (const s of SUITS) deck.push(`${r}${s}` as Card);\n  const i = Math.floor(rng() * deck.length);\n  const first = deck[i];\n  deck.splice(i, 1);\n  const j = Math.floor(rng() * deck.length);\n  const second = deck[j];\n  return [first, second];\n}\n\nexport function cardSuitColor(suit: Suit): 'red' | 'black' {\n  return suit === 'h' || suit === 'd' ? 'red' : 'black';\n}\n\n/**\n * Four-color deck: a distinct, vivid color per suit so suits read at a glance\n * (used as a solid card-tile background with white text). Spades use a slate\n * rather than near-black so the tile stays visible on the dark app background.\n */\nexport const SUIT_COLOR_4: Record<Suit, string> = {\n  s: '#39414f', // spades — slate\n  h: '#FF3366', // hearts — red\n  d: '#20A4F3', // diamonds — blue\n  c: '#1f9d57', // clubs — green\n};\n\n// Each glyph carries the text-presentation variation selector (U+FE0E) so\n// Android renders it as monochrome text that respects our white `color` style,\n// instead of substituting a fixed-color emoji glyph (which ignored the color and\n// showed up dark). No-op on iOS, where these already render as text.\nexport function suitGlyph(suit: Suit): string {\n  switch (suit) {\n    case 's':\n      return '♠︎';\n    case 'h':\n      return '♥︎';\n    case 'd':\n      return '♦︎';\n    case 'c':\n      return '♣︎';\n  }\n}\n",
      "type": "registry:lib",
      "target": "lib/trainer/hand.ts"
    },
    {
      "path": "src/lib/trainer/plo-hand.ts",
      "content": "/**\n * PLO (4-card) hand engine for the trainer.\n *\n * MonkerSolver names each starting hand with suit-grouping notation over the\n * 16,432 suit-isomorphism classes — parentheses wrap cards sharing a suit, e.g.\n *\n *     AAAA       four aces (each a different suit)\n *     (2A)AA     A-A-A-2 with the 2 suited to one ace\n *     (KA)(KA)   AAKK double-suited\n *     AKQJ       four broadways, all different suits (rainbow)\n *\n * We don't reproduce MonkerSolver's exact output ordering. Instead we parse the\n * 16,432 known strings into an order-independent *signature* (ranks grouped by\n * suit) and build a signature → string lookup. A dealt 4-card hand computes the\n * same signature (group its cards by suit) and looks up the canonical string —\n * validated as an exact bijection + deal-side roundtrip against the live data.\n */\n\nimport { PLO_HAND_STRINGS } from './plo-hands';\nimport { RANKS, SUITS, type Card, type Rank, type Suit, rankIndex } from './hand';\n\nexport type HandCategory =\n  | 'Unpaired Double Suited'\n  | 'Unpaired Single Suited'\n  | 'Unpaired Rainbow'\n  | 'One Pair Double Suited'\n  | 'One Pair Single Suited'\n  | 'One Pair Rainbow'\n  | 'Two Pair Double Suited'\n  | 'Two Pair Single Suited'\n  | 'Two Pair Rainbow'\n  | 'Trips Single Suited'\n  | 'Trips Rainbow'\n  | 'Quads Rainbow';\n\n/** A group of ranks sharing one suit, sorted ascending by rank. */\ntype Group = Rank[];\n\n/** Parse a canonical string into suit groups (parens = same-suit group). */\nexport function parseHandString(s: string): Group[] {\n  const groups: Group[] = [];\n  let i = 0;\n  while (i < s.length) {\n    if (s[i] === '(') {\n      const j = s.indexOf(')', i);\n      const ranks = s.slice(i + 1, j).split('') as Rank[];\n      groups.push(sortRanks(ranks));\n      i = j + 1;\n    } else {\n      groups.push([s[i] as Rank]);\n      i += 1;\n    }\n  }\n  return groups;\n}\n\nfunction sortRanks(ranks: Rank[]): Rank[] {\n  return [...ranks].sort((a, b) => rankIndex(a) - rankIndex(b));\n}\n\n/**\n * Order-independent signature of a hand's suit partition. Two hands are\n * suit-isomorphic iff their signatures match. Groups are sorted by (size desc,\n * ranks) so the representation is canonical regardless of suit labelling.\n */\nfunction signature(groups: Group[]): string {\n  return groups\n    .map((g) => g.join(''))\n    .map((g) => ({ g, key: g }))\n    .sort((a, b) => b.g.length - a.g.length || compareRankStr(a.g, b.g))\n    .map((x) => x.g)\n    .join('/');\n}\n\nfunction compareRankStr(a: string, b: string): number {\n  for (let i = 0; i < Math.min(a.length, b.length); i++) {\n    const d = rankIndex(a[i] as Rank) - rankIndex(b[i] as Rank);\n    if (d !== 0) return d;\n  }\n  return a.length - b.length;\n}\n\n// Built once: signature → canonical MonkerSolver string.\nlet SIG_TO_STRING: Map<string, string> | null = null;\nfunction sigToString(): Map<string, string> {\n  if (SIG_TO_STRING) return SIG_TO_STRING;\n  const map = new Map<string, string>();\n  for (const s of PLO_HAND_STRINGS) map.set(signature(parseHandString(s)), s);\n  SIG_TO_STRING = map;\n  return map;\n}\n\n/** Group 4 dealt cards by suit and return the canonical MonkerSolver string. */\nexport function cardsToPloString(cards: [Card, Card, Card, Card]): string {\n  const bySuit = new Map<Suit, Rank[]>();\n  for (const c of cards) {\n    const r = c[0] as Rank;\n    const su = c[1] as Suit;\n    const arr = bySuit.get(su);\n    if (arr) arr.push(r);\n    else bySuit.set(su, [r]);\n  }\n  const groups = [...bySuit.values()].map(sortRanks);\n  const sig = signature(groups);\n  const str = sigToString().get(sig);\n  if (!str) {\n    // Should never happen — the 16,432 set is exhaustive. Fall back to a stable\n    // string so the UI degrades instead of crashing.\n    return cards.map((c) => c[0]).join('');\n  }\n  return str;\n}\n\n/** Deal a random 4-card PLO hand and its canonical string. */\nexport function dealPloHand(rng: () => number = Math.random): {\n  cards: [Card, Card, Card, Card];\n  hand: string;\n} {\n  const deck: Card[] = [];\n  for (const r of RANKS) for (const s of SUITS) deck.push(`${r}${s}` as Card);\n  const picked: Card[] = [];\n  for (let k = 0; k < 4; k++) {\n    const idx = Math.floor(rng() * deck.length);\n    picked.push(deck[idx]);\n    deck.splice(idx, 1);\n  }\n  const cards = picked as [Card, Card, Card, Card];\n  return { cards, hand: cardsToPloString(cards) };\n}\n\n/** Classify a parsed hand into the viewer's category buckets. */\nexport function categorizeGroups(groups: Group[]): HandCategory {\n  const counts = new Map<Rank, number>();\n  for (const g of groups) for (const r of g) counts.set(r, (counts.get(r) ?? 0) + 1);\n  const values = [...counts.values()];\n  const pairs = values.filter((v) => v >= 2).length;\n  const maxOfRank = Math.max(...values);\n\n  let pairing: string;\n  if (maxOfRank >= 4) pairing = 'Quads';\n  else if (maxOfRank === 3) pairing = 'Trips';\n  else if (pairs >= 2) pairing = 'Two Pair';\n  else if (pairs === 1) pairing = 'One Pair';\n  else pairing = 'Unpaired';\n\n  const suited = groups.filter((g) => g.length >= 2).length;\n  const suitedness = suited >= 2 ? 'Double Suited' : suited === 1 ? 'Single Suited' : 'Rainbow';\n\n  return `${pairing} ${suitedness}` as HandCategory;\n}\n\n/** Classify a canonical hand string. */\nexport function categorizeHand(hand: string): HandCategory {\n  return categorizeGroups(parseHandString(hand));\n}\n\n/**\n * Expand a canonical string into 4 concrete display cards, assigning a distinct\n * suit per group so the parenthesised cards visibly share a suit. Deterministic\n * (for stable rendering); suits are cosmetic since ranges are suit-isomorphic.\n */\nexport function ploStringToCards(hand: string): Card[] {\n  const groups = parseHandString(hand);\n  const cards: Card[] = [];\n  groups.forEach((g, gi) => {\n    const suit = SUITS[gi % SUITS.length];\n    for (const r of g) cards.push(`${r}${suit}` as Card);\n  });\n  return cards;\n}\n",
      "type": "registry:lib",
      "target": "lib/trainer/plo-hand.ts"
    }
  ],
  "type": "registry:block"
}