// A PERSON'S CORRECTION OF A FRAME READING (release 32, lane R3): a scan can // be fixed with no model. A vision model read each kept frame into a reading; // where it read a field wrong (a stack off by a digit, the wrong players-left // number, a blinds line misread), a person sets the field to what the frame // shows, or sets the whole reading aside as a misread. The correction is kept // BESIDE the model's readings in the sidecar (`corrections`), never written // over them, and the derivation reads the readings with the corrections laid // over them — the person's value wins. The derivation's own rules are // unchanged (P2's guarantees: a flagged reading makes no event, one // tournament until a confirmed bust), so a corrected value goes through the // same smoothing a read one does. // // Pure: types, the per-profile field table, the check and the overlay. import { POKER_FRAME_EVENTS, POKER_PHASES } from "./poker"; export type CorrectionValue = number | string | string[] | null; export type ReadingCorrection = { // The grid second of the reading (a read frame's, or a duplicate's). t: number; // When the person saved it (ISO). at: string; by: "person"; // The whole reading set aside: the derivation never sees it (nor a // duplicate that copies it). misread?: true; // Field path → the value the frame shows; null: the frame does not show it. set?: Record; note?: string; }; export type CorrectableField = { path: string; label: string; kind: "whole" | "number" | "text" | "lines" | "cards" | "enum"; options?: readonly string[]; // phase is the one a reading must have. required?: boolean; }; // The fields a person may correct, per profile, in the order a form shows them. export const CORRECTABLE_FIELDS: Readonly> = { poker: [ { path: "phase", label: "Phase", kind: "enum", options: POKER_PHASES, required: true }, { path: "tournament.name", label: "Tournament", kind: "text" }, { path: "tournament.level", label: "Level", kind: "whole" }, { path: "tournament.blinds.sb", label: "Small blind", kind: "number" }, { path: "tournament.blinds.bb", label: "Big blind", kind: "number" }, { path: "tournament.blinds.ante", label: "Ante", kind: "number" }, { path: "tournament.playersLeft", label: "Players left", kind: "whole" }, { path: "tournament.totalPlayers", label: "Field", kind: "whole" }, { path: "tournament.position", label: "Position", kind: "whole" }, { path: "tournament.averageStack", label: "Average stack", kind: "whole" }, { path: "tournament.prizePool", label: "Prize pool", kind: "number" }, { path: "tournament.payout", label: "Payout", kind: "number" }, { path: "hero.stack", label: "Hero stack", kind: "whole" }, { path: "hero.bb", label: "Hero stack (big blinds)", kind: "number" }, { path: "hero.bounty", label: "Hero bounty", kind: "number" }, { path: "hero.cards", label: "Hero cards", kind: "cards" }, { path: "hand.pot", label: "Pot", kind: "whole" }, { path: "hand.action", label: "Action", kind: "text" }, { path: "event", label: "Event", kind: "enum", options: POKER_FRAME_EVENTS }, { path: "log", label: "Log lines", kind: "lines" }, ], }; export function correctableFields(profile: string): readonly CorrectableField[] { return CORRECTABLE_FIELDS[profile] ?? []; } export class CorrectionInputError extends Error { constructor(message: string) { super(message); this.name = "CorrectionInputError"; } } const CARD = /^(?:[2-9TJQKA])[shdc]$/; const MAX_NUMBER = 1e12; // One field's value, checked against its kind. null clears the field (not shown). export function checkCorrectionValue(field: CorrectableField, v: unknown): CorrectionValue { const fail = (m: string): never => { throw new CorrectionInputError(`${field.label}: ${m}`); }; if (v === null || v === undefined || v === "") { if (field.required) fail("is required"); return null; } switch (field.kind) { case "whole": case "number": { const n = typeof v === "number" ? v : typeof v === "string" ? Number(v.replace(/[,\s]/g, "")) : NaN; if (!Number.isFinite(n) || n < 0 || n > MAX_NUMBER) fail("a number, 0 or more"); if (field.kind === "whole" && !Number.isInteger(n)) fail("a whole number"); return n; } case "text": { if (typeof v !== "string") fail("text"); const s = (v as string).replace(/\s+/g, " ").trim().slice(0, 200); return s || null; } case "enum": { if (typeof v !== "string" || !(field.options ?? []).includes(v)) fail(`one of ${(field.options ?? []).join(", ")}`); return v as string; } case "lines": { const list = Array.isArray(v) ? v : typeof v === "string" ? v.split("\n") : null; if (!list || list.some((l) => typeof l !== "string")) fail("lines of text"); const out = (list as string[]).map((l) => l.replace(/\s+/g, " ").trim().slice(0, 300)).filter(Boolean); if (out.length > 40) fail("at most 40 lines"); return out.length ? out : null; } case "cards": { const list = Array.isArray(v) ? v : typeof v === "string" ? v.split(/[\s,]+/) : null; if (!list || list.some((c) => typeof c !== "string")) fail("cards like As Kd"); const out = (list as string[]).filter(Boolean).map((c) => (c.length === 2 ? c[0].toUpperCase() + c[1].toLowerCase() : c)); const bad = out.find((c) => !CARD.test(c)); if (bad) fail(`"${bad}" is not a card (rank then suit: As, Td, 9c)`); if (new Set(out).size !== out.length) fail("a card twice"); if (out.length > 6) fail("at most 6 cards"); return out.length ? out : null; } } } // The `set` of a correction, checked: only the profile's fields, each value by // its kind. Empty → undefined. export function checkCorrectionSet(profile: string, raw: unknown): Record | undefined { if (raw === undefined || raw === null) return undefined; if (typeof raw !== "object" || Array.isArray(raw)) throw new CorrectionInputError(`"set" is an object of field → value`); const fields = new Map(correctableFields(profile).map((f) => [f.path, f])); const out: Record = {}; for (const [k, v] of Object.entries(raw as Record)) { const f = fields.get(k); if (!f) throw new CorrectionInputError(`"${k}" is not a field a ${profile} reading has (${[...fields.keys()].join(", ")})`); out[k] = checkCorrectionValue(f, v); } return Object.keys(out).length ? out : undefined; } /** A reading's value at a dotted path (undefined when absent). */ export function readField(reading: Record, p: string): unknown { let cur: unknown = reading; for (const k of p.split(".")) { if (!cur || typeof cur !== "object" || Array.isArray(cur)) return undefined; cur = (cur as Record)[k]; } return cur; } // A copy of `reading` with `p` set (or, for null, removed — and an object left // empty removed with it). function writeField>(reading: T, p: string, v: CorrectionValue): T { const keys = p.split("."); const root: Record = { ...reading }; const chain: Record[] = [root]; let cur = root; for (const k of keys.slice(0, -1)) { const next = cur[k]; const copy = next && typeof next === "object" && !Array.isArray(next) ? { ...(next as Record) } : {}; cur[k] = copy; cur = copy; chain.push(cur); } const last = keys[keys.length - 1]!; if (v === null) delete cur[last]; else cur[last] = Array.isArray(v) ? [...v] : v; // Prune objects the clear left empty, innermost first. for (let i = chain.length - 1; i > 0; i--) { if (Object.keys(chain[i]!).length === 0) delete chain[i - 1]![keys[i - 1]!]; } return root as T; } /** One reading with a correction laid over it; null when it is set aside. */ export function correctedReading(reading: T, c: ReadingCorrection | undefined): T | null { if (!c) return reading; if (c.misread) return null; let out = reading; for (const [p, v] of Object.entries(c.set ?? {})) out = writeField(out, p, v); return out; } /** * Readings with the person's corrections laid over them (by `t`): a misread is * dropped, a set field takes the person's value. Idempotent — applying the * same corrections again changes nothing — so a scan can apply them before * and after it expands its duplicates. */ export function applyCorrections(readings: readonly T[], corrections: readonly ReadingCorrection[] | undefined): T[] { if (!corrections?.length) return [...readings]; const byT = new Map(corrections.map((c) => [c.t, c])); const out: T[] = []; for (const r of readings) { const c = correctedReading(r, byT.get(r.t)); if (c) out.push(c); } return out; } /** Corrections as stored: well-formed ones only, one per t (the newest), sorted. */ export function coerceCorrections(v: unknown): ReadingCorrection[] { if (!Array.isArray(v)) return []; const byT = new Map(); for (const c of v) { if (!c || typeof c !== "object" || typeof (c as ReadingCorrection).t !== "number" || !Number.isFinite((c as ReadingCorrection).t)) continue; const x = c as ReadingCorrection; const set = x.set && typeof x.set === "object" && !Array.isArray(x.set) ? x.set : undefined; if (!x.misread && !set) continue; byT.set(x.t, { t: x.t, at: typeof x.at === "string" ? x.at : "", by: "person", ...(x.misread ? { misread: true as const } : {}), ...(set ? { set } : {}), ...(typeof x.note === "string" && x.note ? { note: x.note } : {}), }); } return [...byT.values()].sort((a, b) => a.t - b.t); } /** The corrections with `c` in place of any at its t (or, for `null` at t, without it). */ export function upsertCorrection(list: readonly ReadingCorrection[] | undefined, t: number, c: ReadingCorrection | null): ReadingCorrection[] { const rest = (list ?? []).filter((x) => x.t !== t); return (c ? [...rest, c] : rest).sort((a, b) => a.t - b.t); }