Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 2c814650e6b3505915d244cd085ee3954434854e
parent 01706cdb62466ee0c09c73c51b66e15f3e609b28
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 20:43:36 -0400

Merge r30/frame-derive: a frame scan's derivation holds to evidence (one tournament until a confirmed bust, dips set aside, players left from the header only, blinds from the log, flagged readings make no event) and re-derives from stored readings with no model call

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 3++-
Mcommon/bin/archilyzer.ts | 10++++++++++
Acommon/bin/frames-rederive.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/frameScan.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/frameScan-server.ts | 2++
Mcommon/lib/frames/poker.test.ts | 36+++++++++++++++++++++++-------------
Mcommon/lib/frames/poker.ts | 488+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Acommon/lib/frames/pokerDerive.test.ts | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/frames/scan.test.ts | 3++-
Mcommon/lib/frames/scan.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/lib/frames/series.test.ts | 12++++++++++++
Mcommon/lib/frames/series.ts | 33+++++++++++++++++++++++++++++++++
Acommon/testing/frames/pokerReadings.d.mts | 8++++++++
Acommon/testing/frames/pokerReadings.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/frames/syntheticPoker.mjs | 15++++++++-------
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/_frameScan.test.ts | 24+++++++++++++++++++++++-
Meditor/app/api/ops/frame-scan/route.ts | 8++++++--
Meditor/app/channels/[slug]/videos/[id]/frameScanActions.ts | 2+-
Mplans/FACTS.md | 7+++++++
Aplans/release-30/frame-derive.md | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 13+++++++++----
22 files changed, 916 insertions(+), 194 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -38,6 +38,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports delete` | `<articleId> [--iteration <n>] [--apply] [--force] [--json]` | delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration) | | `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage) | | `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) | +| `archilyzer frames rederive` | `<slug>/<id> [--profile poker] [--hero <name>] [--dry] [--json]` | work a frame scan's derived timeline (tournaments, series, events, flags) out again from the readings frame-scan.&lt;profile&gt;.json already holds and the video's cues — no model, no frame, no editor — and write it back (--dry: print what would change, write nothing). Not while a scan of the video is running (it writes the same file): with an editor up, `pnpm ops frame-scan --json '{"slug","id","rederive":true}'` checks that (exit 1 when there is no sidecar; 2 for usage) | | `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers | | `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) | | `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube, social) | @@ -151,7 +152,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | | `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "verdict", "at", "note"?} -&gt; {proposal}. "verdict" and "at" are the proposal you were shown (its verdicts.proposed.json entry): a compare-and-set, refused (409) when the proposal was replaced or reviewed since, its claim changed (the proposal is stale) or was ruled meanwhile. approve sets the claim's verdict to it (through the registry); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'` | | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | -| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?} -&gt; {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.&lt;profile&gt;.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'` | +| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -&gt; {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.&lt;profile&gt;.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -&gt; {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -&gt; {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | ### Usage, flags and environment diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -427,6 +427,16 @@ export const COMMANDS: Command[] = [ flags: { apply: "boolean", runs: "string", only: "string", "move-projects": "boolean", generation: "string" }, run: async ({ flags }) => (await import("./reports-import-local-runs")).importRow(flags as Parameters<typeof import("./reports-import-local-runs").importRow>[0]), }, + // The frame scan (release 30): a sidecar's derived timeline worked out again + // from its stored readings, with no editor and no model. + { + path: ["frames", "rederive"], + usage: + "<slug>/<id> [--profile poker] [--hero <name>] [--dry] [--json] work a frame scan's derived timeline (tournaments, series, events, flags) out again from the readings frame-scan.<profile>.json already holds and the video's cues — no model, no frame, no editor — and write it back (--dry: print what would change, write nothing). Not while a scan of the video is running (it writes the same file): with an editor up, `pnpm ops frame-scan --json '{\"slug\",\"id\",\"rederive\":true}'` checks that (exit 1 when there is no sidecar; 2 for usage)", + flags: { profile: "string", hero: "string", dry: "boolean", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./frames-rederive")).framesRederiveRow({ positionals, flags }), + }, // The generation balance (release 27 S9; bin/gen.ts): settings.generation // through the editor's ops API, or settings.json when no editor answers. { diff --git a/common/bin/frames-rederive.ts b/common/bin/frames-rederive.ts @@ -0,0 +1,45 @@ +// `archilyzer frames rederive <slug>/<id>` (release 30): a frame scan's +// `derived` worked out again from the readings its sidecar holds — zero model +// calls, no frame, no editor. The same rederiveRecord the editor's +// `frame-scan {rederive: true}` runs; this one cannot see the editor's jobs, so +// it is not for a video whose scan is running. + +import path from "node:path"; +import { getPaths } from "../lib/paths"; +import { frameScanSidecar } from "../lib/frameScan-server"; +import { isFrameProfile } from "../lib/frames/profiles"; +import { rederiveRecord } from "../lib/frames/scan"; +import { loadCues, rederivedSummary } from "../controller/frameScan"; +import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments"; + +export async function framesRederiveRow({ positionals, flags }: { positionals: string[]; flags: Record<string, string | boolean | undefined> }): Promise<number> { + const [ref] = positionals; + const [slug, id] = (ref ?? "").split("/"); + const profile = typeof flags.profile === "string" ? flags.profile : "poker"; + if (!isSafeChannelSegment(slug) || !isSafeIdSegment(id) || !isFrameProfile(profile)) { + console.error("frames rederive: give <slug>/<id> [--profile poker] [--hero <name>] [--dry]"); + return 2; + } + const videoDir = path.join(getPaths().channelsDir, slug, "data", id); + const sidecar = frameScanSidecar(profile); + const rec = await sidecar.load(videoDir); + if (!rec) { + console.error(`frames rederive: ${slug}/${id} has no ${sidecar.filename}`); + return 1; + } + const cues = await loadCues(videoDir); + const hero = typeof flags.hero === "string" && flags.hero.trim() ? flags.hero.trim() : undefined; + const out = rederiveRecord(rec, { ...(cues ? { cues } : {}), ...(hero ? { hero } : {}) }); + const summary = rederivedSummary(rec, out, sidecar.filename); + if (flags.dry !== true) await sidecar.write(videoDir, out); + if (flags.json === true) console.log(JSON.stringify({ ...summary, written: flags.dry !== true })); + else { + const b = summary.before; + const a = summary.after; + console.log(`${slug}/${id} ${sidecar.filename}: ${summary.readings} readings${flags.dry === true ? " (dry: nothing written)" : ""}`); + console.log(` tournaments ${b.tournaments} → ${a.tournaments}, events ${b.events} → ${a.events}, flags ${b.flags} → ${a.flags}, misreads ${b.misreads} → ${a.misreads}`); + for (const t of summary.tournaments) console.log(` ${t.key}${t.name ? ` (${t.name})` : ""} ${Math.round(t.from)}–${Math.round(t.to)} s`); + console.log(` events: ${Object.entries(summary.eventsByKind).map(([k, n]) => `${k} ${n}`).join(", ") || "none"}`); + } + return 0; +} diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts @@ -16,6 +16,10 @@ // fresh read every frame again (another model or prompt): the // readings so far are dropped, the runs and the spend kept // evict remove the frame cache and answer at once (no job) +// rederive work `derived` out again from the stored readings (and the +// cues' spoken numbers) and answer at once: no job, no model, +// no frame (refused while a scan of this video is queued or +// running); `hero` may be given with it // // THE QUEUE: on the API a scan runs on `frames`, one at a time and apart from // the generation lanes; on a local model it runs on `draft:local`, every ollama @@ -41,14 +45,16 @@ import { resolveSavedVideo } from "../lib/savedVideo-server"; import { frameCacheDirOf, frameScanSidecar } from "../lib/frameScan-server"; import { frameCacheBytes, isCrop, removeFrameCache, type Crop } from "../lib/frames/sample-server"; import { isFrameProfile, FRAME_PROFILE_IDS } from "../lib/frames/profiles"; -import { DEFAULT_MAX_FRAMES, runFrameScan, type FrameScanOutcome } from "../lib/frames/scan"; +import { DEFAULT_MAX_FRAMES, rederiveRecord, runFrameScan, type FrameScanOutcome } from "../lib/frames/scan"; +import { getRegistry } from "../jobs/registry"; +import type { FrameScanRecord } from "../lib/frameScan-server"; import type { Cue } from "../lib/frames/types"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { llmConfigOf } from "./reportDraft"; export const FRAME_SCAN_JOB_KIND = "frame-scan"; export const FRAME_SCAN_RESULT_MARKER = "@@frame-scan "; -export const FRAME_SCAN_BODY_KEYS = ["slug", "id", "profile", "everySeconds", "from", "to", "maxFrames", "model", "maxUsd", "hero", "framesPerAsk", "crop", "fresh", "evict"] as const; +export const FRAME_SCAN_BODY_KEYS = ["slug", "id", "profile", "everySeconds", "from", "to", "maxFrames", "model", "maxUsd", "hero", "framesPerAsk", "crop", "fresh", "evict", "rederive"] as const; export class FrameScanInputError extends Error { constructor(message: string) { @@ -72,6 +78,7 @@ export type FrameScanBody = { crop?: Crop; fresh?: boolean; evict?: boolean; + rederive?: boolean; }; const fail = (msg: string): never => { @@ -128,6 +135,11 @@ export function parseFrameScanBody(b: Record<string, unknown>): FrameScanBody { if (typeof b.evict !== "boolean") fail(`"evict" is true or false`); out.evict = b.evict as boolean; } + if (b.rederive !== undefined) { + if (typeof b.rederive !== "boolean") fail(`"rederive" is true or false`); + out.rederive = b.rederive as boolean; + } + if (out.rederive && out.evict) fail(`"rederive" and "evict" are two different asks — one at a time`); return out; } @@ -157,9 +169,35 @@ export type FrameScanDepsIn = { export type FrameScanEnqueued = | { result: StreamActionResult; model: string; queueKey: string } | { result: StreamActionResult & { ok: false } } - | { evicted: { dir: string; removed: boolean; bytes: number } }; + | { evicted: { dir: string; removed: boolean; bytes: number } } + | { rederived: FrameScanRederived }; + +/** What a re-derive changed, in counts: before → after. */ +export type FrameScanRederived = { + file: string; + readings: number; + before: { tournaments: number; events: number; flags: number; misreads: number }; + after: { tournaments: number; events: number; flags: number; misreads: number }; + tournaments: { key: string; name?: string; from: number; to: number }[]; + eventsByKind: Record<string, number>; +}; -async function loadCues(videoDir: string): Promise<Cue[] | undefined> { +export function rederivedSummary(before: FrameScanRecord, after: FrameScanRecord, file: string): FrameScanRederived { + const counts = (r: FrameScanRecord) => ({ tournaments: r.derived.tournaments.length, events: r.derived.events.length, flags: r.derived.flags.length, misreads: r.derived.misreads.length }); + const eventsByKind: Record<string, number> = {}; + for (const e of after.derived.events) eventsByKind[e.kind] = (eventsByKind[e.kind] ?? 0) + 1; + return { + file, + readings: after.readings.length, + before: counts(before), + after: counts(after), + tournaments: after.derived.tournaments.map((t) => ({ key: t.key, ...(t.name ? { name: t.name } : {}), from: t.from, to: t.to })), + eventsByKind, + }; +} + +/** A video's cues (`transcript.cues.json`), sorted, or undefined. */ +export async function loadCues(videoDir: string): Promise<Cue[] | undefined> { try { const doc = JSON.parse(await readFile(path.join(videoDir, "transcript.cues.json"), "utf8")) as { cues?: unknown }; if (!Array.isArray(doc.cues)) return undefined; @@ -186,6 +224,19 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame const bytes = await frameCacheBytes(cacheDir); return { evicted: { dir: cacheDir, removed: await removeFrameCache(cacheDir), bytes } }; } + if (body.rederive) { + const busy = getRegistry() + .list() + .some((j) => j.kind === FRAME_SCAN_JOB_KIND && j.channelSlug === body.slug && j.videoId === body.id && (j.status === "queued" || j.status === "running")); + if (busy) return refuse(`a frame scan of ${body.slug}/${body.id} is queued or running — re-derive when it is done (it writes the sidecar)`); + const sidecar = frameScanSidecar(body.profile); + const rec = await sidecar.load(videoDir); + if (!rec) return refuse(`${body.slug}/${body.id} has no ${sidecar.filename} to re-derive — scan it first`); + const cues = await loadCues(videoDir); + const out = rederiveRecord(rec, { ...(cues ? { cues } : {}), ...(body.hero ? { hero: body.hero } : {}), ...(deps.now ? { now: deps.now } : {}) }); + await sidecar.write(videoDir, out); + return { rederived: rederivedSummary(rec, out, sidecar.filename) }; + } const source = await resolveSavedVideo(videoDir); if (!source) { return refuse( diff --git a/common/lib/frameScan-server.ts b/common/lib/frameScan-server.ts @@ -50,6 +50,8 @@ export type FrameScanRecord = { spoken: SpokenReading[]; derived: Derived; updatedAt: string; + // When `derived` was last worked out again from the readings (no model). + rederivedAt?: string; }; const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v); diff --git a/common/lib/frames/poker.test.ts b/common/lib/frames/poker.test.ts @@ -8,7 +8,8 @@ type R = PokerReading & { t: number }; const table = (t: number, stack: number | undefined, more: Partial<NonNullable<PokerReading["tournament"]>> = {}, extra: Partial<PokerReading> = {}): R => ({ t, phase: "table", - tournament: { name: "Main Event", playersLeft: 85, totalPlayers: 120, level: 3, blinds: { sb: 100, bb: 200 }, ...more }, + // A stats header's "position 1 of 85": players left is the field's only beside a position. + tournament: { name: "Main Event", playersLeft: 85, position: 1, totalPlayers: 120, level: 3, blinds: { sb: 100, bb: 200 }, ...more }, ...(stack !== undefined ? { hero: { stack } } : {}), ...extra, }); @@ -125,23 +126,23 @@ test("phase segments: a one-frame blip between two of another phase is absorbed" assert.equal(d.segments[1].tournament, "main event"); }); -test("two tournaments in one stream never share a series", () => { - const viewer = (t: number, stack: number): R => ({ t, phase: "table", tournament: { name: "Viewer $1000", playersLeft: 30, totalPlayers: 40 }, hero: { stack } }); - const d = derive([table(0, 20000), table(10, 21000), { t: 20, phase: "lobby" }, viewer(30, 1500), viewer(40, 3100), viewer(50, 3200)]); +test("two tournaments in one stream never share a series: the second starts after a confirmed bust", () => { + const viewer = (t: number, stack: number): R => ({ t, phase: "table", tournament: { name: "Viewer $1000", playersLeft: 30, position: 5, totalPlayers: 40 }, hero: { stack } }); + const d = derive([table(0, 20000), table(10, 21000), table(15, 0, {}, { event: "eliminated" }), { t: 20, phase: "lobby" }, viewer(30, 1500), viewer(40, 3100), viewer(50, 3200)]); assert.deepEqual(d.tournaments.map((t) => [t.key, t.name, t.from]), [["main event", "Main Event", 0], ["viewer $1000", "Viewer $1000", 30]]); - assert.deepEqual(series(d, "stack", "main event"), [[0, 20000], [10, 21000]]); + assert.deepEqual(series(d, "stack", "main event"), [[0, 20000], [10, 21000], [15, 0]]); assert.deepEqual(series(d, "stack", "viewer $1000"), [[30, 1500], [40, 3100], [50, 3200]]); // The viewer tournament's double-up is its own. assert.ok(d.events.some((e) => e.kind === "double-up" && e.tournament === "viewer $1000")); }); -test("unnamed readings take the name before them; a field that changes size is another tournament", () => { +test("unnamed readings are the tournament they sit in; a misread field size is not another tournament", () => { const d = derive([ table(0, 1000, { totalPlayers: 1200 }), { t: 10, phase: "table", tournament: { totalPlayers: 1200 }, hero: { stack: 1100 } }, - { t: 20, phase: "table", tournament: { totalPlayers: 40 }, hero: { stack: 50 } }, + { t: 20, phase: "table", tournament: { totalPlayers: 40 }, hero: { stack: 1150 } }, ]); - assert.deepEqual(d.tournaments.map((t) => t.key), ["main event", "main event#2"]); + assert.deepEqual(d.tournaments.map((t) => t.key), ["main event"]); }); test("a spoken number that disagrees with a nearby frame is flagged, never trusted; one that agrees is quiet", () => { @@ -150,14 +151,14 @@ test("a spoken number that disagrees with a nearby frame is flagged, never trust { t: 22, field: "playersLeft", value: 40, text: "forty players left" }, ]; const d = derive([table(0, 1000), table(10, 1000), table(20, 1000)], spoken); - assert.deepEqual(d.flags, [{ t: 22, field: "playersLeft", spoken: 40, frame: 85, frameT: 0, tournament: "main event" }]); + assert.deepEqual(d.flags, [{ t: 22, field: "playersLeft", spoken: 40, frame: 85, frameT: 20, tournament: "main event" }]); }); test("a spoken number where no frame read the field fills the series, marked spoken, and makes no event", () => { - const spoken: SpokenReading[] = [{ t: 400, field: "stack", value: 60000, text: "I have sixty thousand" }]; + const spoken: SpokenReading[] = [{ t: 400, field: "stack", value: 24000, text: "I have twenty four thousand" }]; const rs = [table(0, 20000), ...Array.from({ length: 59 }, (_, i) => table(10 + i * 10, undefined)), table(600, 20500)]; const d = derive(rs, spoken); - assert.deepEqual(series(d, "stack"), [[0, 20000], [400, 60000, "spoken"], [600, 20500]]); + assert.deepEqual(series(d, "stack"), [[0, 20000], [400, 24000, "spoken"], [600, 20500]]); assert.equal(d.events.filter((e) => e.kind === "double-up").length, 0); }); @@ -220,7 +221,7 @@ test("a knockout and a bust from the log; the blinds from 'Blinds are now' when }); test("after the hero is out, the next table with chips is another tournament, whatever its name", () => { - const d = derive([table(0, 5000), table(10, 0), { t: 20, phase: "lobby" }, table(30, 1500, { playersLeft: 40, totalPlayers: 40 }), table(40, 1600, { playersLeft: 39, totalPlayers: 40 })]); + const d = derive([table(0, 5000), table(10, 0, {}, { event: "eliminated" }), { t: 20, phase: "lobby" }, table(30, 1500, { playersLeft: 40, totalPlayers: 40 }), table(40, 1600, { playersLeft: 39, totalPlayers: 40 })]); assert.deepEqual(d.tournaments.map((t) => [t.key, t.from]), [["main event", 0], ["main event#2", 30]]); assert.deepEqual(series(d, "stack", "main event#2"), [[30, 1500], [40, 1600]]); }); @@ -237,5 +238,14 @@ test("players left from the log's finishing places when the frame did not show t { t: 10, phase: "table", tournament: { name: "Main Event", playersLeft: 80 }, hero: { stack: 1000 }, log: ["SynthB has finished the tournament in 87th"] }, ]; const d = derivePoker(rs, [], { everySeconds: 10 }); - assert.deepEqual(d.tournaments[0].series.playersLeft, [[0, 86], [10, 80]]); + // The second frame's 80 has no position beside it (not the header): the log's 87th says 86. + assert.deepEqual(d.tournaments[0].series.playersLeft, [[0, 86]]); +}); + +test("a spoken number that fits neither reading either side of a gap is flagged, not drawn", () => { + const spoken: SpokenReading[] = [{ t: 400, field: "stack", value: 60000, text: "sixty thousand" }]; + const rs = [table(0, 20000), ...Array.from({ length: 59 }, (_, i) => table(10 + i * 10, undefined)), table(600, 20500)]; + const d = derive(rs, spoken); + assert.deepEqual(series(d, "stack"), [[0, 20000], [600, 20500]]); + assert.deepEqual(d.flags.map((f) => [f.t, f.field, f.spoken, f.frame]), [[400, "stack", 60000, 20500]]); }); diff --git a/common/lib/frames/poker.ts b/common/lib/frames/poker.ts @@ -11,7 +11,7 @@ // trusted from the prompt. import { pokerSpoken } from "./pokerSpoken"; -import { agree, changesOnly, dropMisreads, nearest, type AgreeRule, type Pt } from "./series"; +import { agree, changesOnly, dropExcursions, dropMisreads, ratioOf, type AgreeRule, type Pt } from "./series"; import { clock, fmtNum, @@ -234,133 +234,307 @@ const SPOKEN_WINDOW_S = 90; const FINAL_TABLE = 9; const normName = (s: string) => s.toLowerCase().replace(/[^a-z0-9$]+/g, " ").trim(); +const squash = (s: string) => normName(s).replace(/ /g, ""); -// Which tournament each reading belongs to. A name read on screen keys it; -// readings with none take the name before them (or, before any, the first -// one). Within a name, the field changing size by more than half is another -// tournament of the same name (a re-run, a satellite). -function keyReadings(rs: readonly R[]): { keys: (string | null)[]; names: Map<string, string> } { - const names = new Map<string, string>(); - const first = rs.find((r) => r.tournament?.name)?.tournament?.name; - let current = first ? normName(first) : null; - let currentName = first ?? null; - const field = new Map<string, number>(); - const generation = new Map<string, number>(); - const keys: (string | null)[] = []; - // After the hero is out (a stack of 0, a bust on screen), the next table - // with chips in front of the hero is another tournament, whatever its name. - let out = false; - let awayAfterOut = false; - for (const r of rs) { - const named = r.tournament?.name; - if (named) { - current = normName(named); - currentName = named; +// ─── Which tournament a reading is in ─── +// +// A name read off the screen is NOT evidence of another tournament: the model +// puts a hand description from the log ("Three of a Kind Eights"), a seat's +// name or a misread of the title ("VENOM NLH10", "NLHKAO") in the field now +// and then. So a tournament changes only where the hero's own chips say so — +// after a CONFIRMED bust (a stack of 0 held, or with a bust banner or the +// hero's "has finished the tournament" line beside it), a screen away from the +// table, and chips in front of the hero again. Between two such points every +// reading is one tournament, and its name is the title most of its readings +// agree on (below). + +const HAND_WORDS = /\b(pair|two pair|three of a kind|four of a kind|full house|flush|straight|royal|high card|kicker|high|with|takes|pot|wins|chips?)\b/i; + +/** Levenshtein distance (small strings). */ +function editDistance(a: string, b: string): number { + const row = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i++) { + let prev = row[0]; + row[0] = i; + for (let j = 1; j <= b.length; j++) { + const cur = row[j]; + row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); + prev = cur; } - if (r.phase !== "table") awayAfterOut = true; - if (r.phase !== "table" && r.phase !== "lobby") { - keys.push(null); - continue; + } + return row[b.length]; +} + +/** How alike two names are, 0..1 (1 − edit distance over the longer, on letters and digits only). */ +export function nameSimilarity(a: string, b: string): number { + const x = squash(a); + const y = squash(b); + if (!x || !y) return 0; + return 1 - editDistance(x, y) / Math.max(x.length, y.length); +} + +// Every player name a log shows ("Dealer: X takes the pot…", "X has finished +// the tournament…", "X knocked out Y"): a name read as the title that matches +// one of them is a seat, not the tournament. +function speakersOf(rs: readonly R[]): string[] { + const out = new Set<string>(); + for (const r of rs) + for (const line of r.log ?? []) { + const m = /^(?:dealer:\s*)?(.+?) (?:takes the|has finished the tournament|knocked out|knocks out|wins|is eliminated|was eliminated)\b/i.exec(line); + if (m && m[1].length <= 40) out.add(m[1]); } - const base = current ?? "tournament"; - if (out && r.phase === "table" && (r.hero?.stack ?? 0) > 0) { - // Only after a screen that is not the table: chips again on the very - // next table frame mean the 0 was a misread. - if (awayAfterOut) { - generation.set(base, (generation.get(base) ?? 1) + 1); - field.delete(base); - } + return [...out]; +} + +/** Whether a name read as the tournament's could be a title: not a hand, a seat or the hero. */ +export function looksLikeTitle(name: string, o: { hero?: string; speakers?: readonly string[] } = {}): boolean { + const n = normName(name); + if (!/[a-z]/.test(n) || n.length < 2) return false; + if (HAND_WORDS.test(name)) return false; + if (o.hero && nameSimilarity(name, o.hero) >= 0.75) return false; + if ((o.speakers ?? []).some((sp) => nameSimilarity(name, sp) >= 0.75)) return false; + return true; +} + +/** + * The title a set of names agrees on: names clustered (one's words the start + * of the other's — "VENOM" and "VENOM NLH PKO" — or 75% alike as letters), + * the cluster read most often wins if read at least `min` times (or it is the + * only one), and it is named by its most frequent spelling. Null when no + * cluster is read enough. + */ +export function canonicalTitle(names: readonly string[], min = 3): string | null { + // Spellings that differ only in case and punctuation are one name, shown + // as its most frequent spelling. + const counts = new Map<string, number>(); + const spellings = new Map<string, Map<string, number>>(); + for (const n of names) { + const k = normName(n); + counts.set(k, (counts.get(k) ?? 0) + 1); + const sp = spellings.get(k) ?? new Map<string, number>(); + sp.set(n, (sp.get(n) ?? 0) + 1); + spellings.set(k, sp); + } + const shown = (k: string) => [...(spellings.get(k) ?? new Map())].sort((a, b) => b[1] - a[1])[0]?.[0] ?? k; + const byCount = [...counts].sort((a, b) => b[1] - a[1] || a[0].length - b[0].length); + const clusters: { members: [string, number][] }[] = []; + const joins = (a: string, b: string) => { + const x = normName(a); + const y = normName(b); + return x === y || x.startsWith(`${y} `) || y.startsWith(`${x} `) || nameSimilarity(a, b) >= 0.75; + }; + for (const [n, c] of byCount) { + const home = clusters.find((cl) => cl.members.some(([m]) => joins(m, n))); + if (home) home.members.push([n, c]); + else clusters.push({ members: [[n, c]] }); + } + const scored = clusters.map((cl) => ({ total: cl.members.reduce((s, [, c]) => s + c, 0), top: cl.members[0][0] })).sort((a, b) => b.total - a.total); + // Read enough times, or the only title read at all. + return scored[0] && (scored[0].total >= min || scored.length === 1) ? shown(scored[0].top) : null; +} + +const HERO_FINISHED = (hero: string) => new RegExp(`^(?:dealer:\\s*)?${hero.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} has finished the tournament`, "i"); + +// The confirmed busts: the index of the reading where the hero is out. +function confirmedBusts(rs: readonly R[], hero?: string): Set<number> { + const out = new Set<number>(); + const finished = hero ? HERO_FINISHED(hero) : null; + rs.forEach((r, i) => { + if (r.hero?.stack !== 0) return; + // The readings either side: a 0 held on the next or the last, or a bust + // banner on it or beside it; or the hero's own finishing line within a minute. + const beside = [rs[i - 1], rs[i + 1]].filter((x): x is R => !!x); + const held = beside.some((x) => x.hero?.stack === 0); + const banner = [r, ...beside].some((x) => x.event === "bust" || x.event === "eliminated"); + const said = finished ? rs.some((x) => Math.abs(x.t - r.t) <= 60 && (x.log ?? []).some((l) => finished.test(l))) : false; + if (held || banner || said) out.add(i); + }); + return out; +} + +function keyReadings(rs: readonly R[], hero?: string): { keys: (string | null)[]; names: Map<string, string> } { + const busts = confirmedBusts(rs, hero); + // Generations: a new one after a confirmed bust, a screen away from the + // table, and chips in front of the hero again. + const gen: (number | null)[] = []; + let g = 1; + let out = false; + let away = false; + rs.forEach((r, i) => { + if (r.phase !== "table") away = true; + if (out && away && r.phase === "table" && (r.hero?.stack ?? 0) > 0) { + g++; out = false; } - if (r.hero?.stack === 0 || r.event === "bust" || r.event === "eliminated") { + if (busts.has(i)) { out = true; - awayAfterOut = false; + away = false; } - const total = r.tournament?.totalPlayers; - if (total !== undefined) { - const was = field.get(base); - if (was !== undefined && !agree(was, total, { ratio: 1.5 })) generation.set(base, (generation.get(base) ?? 1) + 1); - field.set(base, total); + gen.push(r.phase === "table" || r.phase === "lobby" ? g : null); + }); + const speakers = speakersOf(rs); + const names = new Map<string, string>(); + const keyOfGen = new Map<number, string>(); + const used = new Set<string>(); + for (const n of [...new Set(gen.filter((x): x is number => x !== null))]) { + const titles = rs.filter((_, i) => gen[i] === n).map((r) => r.tournament?.name).filter((x): x is string => !!x && looksLikeTitle(x, { hero, speakers })); + const title = canonicalTitle(titles); + let key = title ? normName(title) : "tournament"; + if (used.has(key)) { + let k = 2; + while (used.has(`${key}#${k}`)) k++; + key = `${key}#${k}`; } - const g = generation.get(base) ?? 1; - const key = g > 1 ? `${base}#${g}` : base; - if (currentName && !names.has(key)) names.set(key, currentName); - keys.push(key); + used.add(key); + keyOfGen.set(n, key); + if (title) names.set(key, title); } - return { keys, names }; + return { keys: gen.map((n) => (n === null ? null : keyOfGen.get(n)!)), names }; +} + +// ─── What a reading's fields may be taken as ─── + +// Players left is the tournament's only from the stats header ("Your position +// N of M": both numbers on one reading, the position within the field) or from +// the log's finishing places. A count beside a table's seats ("7 of 7") or a +// number with no position beside it is not the field. +function headerPlayersLeft(r: R): number | undefined { + const t = r.tournament; + if (t?.playersLeft === undefined || t.position === undefined) return undefined; + if (t.position > t.playersLeft) return undefined; + if (t.totalPlayers !== undefined && t.totalPlayers <= 10 && t.playersLeft <= 10) return undefined; + return t.playersLeft; +} + +function finishedPlayersLeft(r: R): number | undefined { + const places = (r.log ?? []).map((l) => FINISHED_LINE.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => Number(m[1])); + const low = places.length ? Math.min(...places) : 0; + return low > 1 ? low - 1 : undefined; +} + +const logBlindsOf = (r: R): { sb: number; bb: number } | null => { + for (let i = (r.log?.length ?? 0) - 1; i >= 0; i--) { + const m = BLINDS_LINE.exec(r.log![i]); + if (!m) continue; + const sb = digits(m[1]); + const bb = digits(m[2]); + return sb > 0 && bb >= sb ? { sb, bb } : null; + } + return null; +}; + +// Players left never rise (a late registration adds a few, not half the +// field): a reading followed within ten minutes by one more than 1.5× and 3 +// larger is a misread (a table's seats, a rank read as the field). +function fieldOnlyFalls(points: readonly Pt[], misreads: Derived["misreads"]): Pt[] { + return points.filter((p, i) => { + const later = points.slice(i + 1).some((q) => q.t - p.t <= 600 && q.v > p.v * 1.5 && q.v - p.v > 3); + if (later) misreads.push({ t: p.t, field: "playersLeft", value: p.v }); + return !later; + }); } -const FIELDS: { field: string; of: (r: R) => number | undefined }[] = [ - { field: "stack", of: (r) => r.hero?.stack }, - { - field: "stackBB", - // Shown by the client, else the stack over the big blind on the same frame. - of: (r) => { - if (r.hero?.bb !== undefined) return r.hero.bb; - const s = r.hero?.stack; - const bb = r.tournament?.blinds?.bb; - return s !== undefined && bb ? Math.round((s / bb) * 10) / 10 : undefined; - }, - }, - { field: "playersLeft", of: (r) => r.tournament?.playersLeft }, - { field: "level", of: (r) => r.tournament?.level }, - { field: "position", of: (r) => r.tournament?.position }, - { field: "averageStack", of: (r) => r.tournament?.averageStack }, - { field: "bigBlind", of: (r) => r.tournament?.blinds?.bb }, -]; -const pts = (s: readonly SeriesPoint[]): Pt[] => s.map(([t, v]) => ({ t, v })); +// Stack changes judged against: a level left and returned to within this +// window is not a change (a mid-hand reading, a misread). +const EXCURSION = { returnRatio: 1.1, windowS: 90 }; +// A double-up's or a big loss's new level is held by the reading after it. +const HELD: AgreeRule = { ratio: 1.25 }; /** * Readings (and spoken numbers) to tournaments with series, events, phase - * segments and flags. Pure; heavily tested (poker.test.ts). + * segments and flags. Pure; heavily tested (poker.test.ts, pokerDerive.test.ts). */ export function derivePoker(readingsIn: readonly R[], spoken: readonly SpokenReading[], o: { everySeconds: number; durationSeconds?: number; hero?: string }): Derived { - const rs = [...readingsIn].sort((a, b) => a.t - b.t).map(withLogBlinds); + const rs = [...readingsIn].sort((a, b) => a.t - b.t); const segments = phaseSegments(rs, o); - const { keys, names } = keyReadings(rs); + const { keys, names } = keyReadings(rs, o.hero); const misreads: Derived["misreads"] = []; - const byKey = new Map<string, R[]>(); - // The blinds hold until they change: a frame that did not show them takes - // its tournament's last (so a stack in big blinds is known on every frame). - const lastBB = new Map<string, { sb?: number; bb: number }>(); - rs.forEach((r0, i) => { + const byKey = new Map<string, number[]>(); + rs.forEach((_, i) => { const k = keys[i]; if (!k) return; - let r = r0; - const b = r.tournament?.blinds; - if (b?.bb !== undefined) lastBB.set(k, { ...(b.sb !== undefined ? { sb: b.sb } : {}), bb: b.bb }); - else if (lastBB.has(k)) r = { ...r, tournament: { ...(r.tournament ?? {}), blinds: { ...(b ?? {}), ...lastBB.get(k)! } } }; if (!byKey.has(k)) byKey.set(k, []); - byKey.get(k)!.push(r); + byKey.get(k)!.push(i); }); const tournaments: DerivedTournament[] = []; // Every kept point per tournament and field (not collapsed to changes): the // events judge a change by the reading after it. const full = new Map<string, Record<string, Pt[]>>(); - for (const [key, list] of byKey) { - const series: Record<string, SeriesPoint[]> = {}; - const points: Record<string, Pt[]> = {}; - for (const f of FIELDS) { - const raw: Pt[] = []; - for (const r of list) { - const v = f.of(r); - if (v !== undefined) raw.push({ t: r.t, v }); + for (const [key, idx] of byKey) { + const list = idx.map((i) => rs[i]); + const raw: Record<string, Pt[]> = { stack: [], playersLeft: [], level: [], position: [], averageStack: [], bigBlind: [], shownBB: [] }; + // THE BLINDS: the log's "Blinds are now a/b" is the truth and holds until + // the next one; a big blind read off the table that disagrees with it by + // more than 2× is a misread. Before the log has said any, the reads. + // Blinds only go up within a tournament: before the log has said any, a + // read lower than the last one kept, or higher than the first the log + // will say, is a misread (an ante or a small blind read as the big). + let logged: { sb: number; bb: number } | null = null; + const firstLogged = list.map(logBlindsOf).find((b) => b !== null)?.bb; + let lastRead = 0; + for (const r of list) { + logged = logBlindsOf(r) ?? logged; + const read = r.tournament?.blinds?.bb; + if (logged) { + if (read !== undefined && ratioOf(read, logged.bb) > 2) misreads.push({ t: r.t, field: "bigBlind", value: read }); + raw.bigBlind.push({ t: r.t, v: logged.bb }); + } else if (read !== undefined) { + if (read < lastRead || (firstLogged !== undefined && read > firstLogged)) misreads.push({ t: r.t, field: "bigBlind", value: read }); + else { + raw.bigBlind.push({ t: r.t, v: read }); + lastRead = read; + } } - const { kept, dropped } = dropMisreads(raw, MISREAD[f.field]); - for (const d of dropped) misreads.push({ t: d.t, field: f.field, value: d.v }); - points[f.field] = kept; - series[f.field] = changesOnly(kept).map((p) => [p.t, p.v] as SeriesPoint); + if (r.hero?.stack !== undefined) raw.stack.push({ t: r.t, v: r.hero.stack }); + if (r.hero?.bb !== undefined) raw.shownBB.push({ t: r.t, v: r.hero.bb }); + const left = headerPlayersLeft(r) ?? finishedPlayersLeft(r); + if (left !== undefined) raw.playersLeft.push({ t: r.t, v: left }); + if (r.tournament?.level !== undefined) raw.level.push({ t: r.t, v: r.tournament.level }); + if (r.tournament?.position !== undefined && headerPlayersLeft(r) !== undefined) raw.position.push({ t: r.t, v: r.tournament.position }); + if (r.tournament?.averageStack !== undefined) raw.averageStack.push({ t: r.t, v: r.tournament.averageStack }); } + const points: Record<string, Pt[]> = {}; + const keep = (field: string, ps: Pt[], excursions = false) => { + let cur = ps; + if (excursions) { + const ex = dropExcursions(cur, EXCURSION); + for (const d of ex.dropped) misreads.push({ t: d.t, field, value: d.v }); + cur = ex.kept; + } + const { kept, dropped } = dropMisreads(cur, MISREAD[field]); + for (const d of dropped) misreads.push({ t: d.t, field, value: d.v }); + points[field] = kept; + }; + keep("stack", raw.stack, true); + keep("bigBlind", raw.bigBlind); + keep("playersLeft", fieldOnlyFalls(raw.playersLeft, misreads)); + keep("level", raw.level); + keep("position", raw.position); + keep("averageStack", raw.averageStack); + // Stack in big blinds: the client's own figure where it shows one, else + // the kept stack over the big blind of its moment. + const shown = new Map(raw.shownBB.map((p) => [p.t, p.v])); + points.stackBB = points.stack + .map((p) => { + const s = shown.get(p.t); + if (s !== undefined) return { t: p.t, v: s }; + const bb = nearestBefore(points.bigBlind, p.t); + return bb ? { t: p.t, v: Math.round((p.v / bb) * 10) / 10 } : null; + }) + .filter((p): p is Pt => p !== null); + const series: Record<string, SeriesPoint[]> = {}; + for (const f of ["stack", "stackBB", "playersLeft", "level", "position", "averageStack", "bigBlind"]) series[f] = changesOnly(points[f] ?? []).map((p) => [p.t, p.v] as SeriesPoint); full.set(key, points); const facts: Record<string, number> = {}; for (const r of list) { const t = r.tournament; - if (t?.totalPlayers !== undefined) facts.totalPlayers = t.totalPlayers; + // The field at the start, when shown apart and larger than a table. + if (t?.totalPlayers !== undefined && t.totalPlayers > 10) facts.totalPlayers = t.totalPlayers; if (t?.prizePool !== undefined) facts.prizePool = t.prizePool; if (t?.payout !== undefined) facts.payout = t.payout; - if (t?.position !== undefined) facts.position = t.position; + if (t?.position !== undefined && headerPlayersLeft(r) !== undefined) facts.position = t.position; } const tour: DerivedTournament = { key, from: list[0].t, to: list[list.length - 1].t + o.everySeconds, series, facts }; const name = names.get(key); @@ -369,14 +543,19 @@ export function derivePoker(readingsIn: readonly R[], spoken: readonly SpokenRea } tournaments.sort((a, b) => a.from - b.from); - const flags = crossCheck(tournaments, spoken); + const { flags, flagged } = crossCheck(tournaments, full, spoken); // Segments say which tournament they are in, when one covers them. for (const s of segments) { const tour = tournaments.find((t) => s.from >= t.from && s.from < t.to); if (tour && (s.phase === "table" || s.phase === "lobby")) s.tournament = tour.key; } - const events = [...frameEvents(rs, keys), ...seriesEvents(tournaments, full), ...logEvents(rs, keys, full, o.hero), ...spokenEvents(spoken)].sort((a, b) => a.t - b.t || a.kind.localeCompare(b.kind)); - return { tournaments, events, segments, flags, misreads: misreads.sort((a, b) => a.t - b.t) }; + const events = [ + ...frameEvents(rs, keys, full), + ...seriesEvents(tournaments, full, flagged), + ...logEvents(rs, keys, full, o.hero), + ...spokenEvents(spoken), + ].sort((a, b) => a.t - b.t || a.kind.localeCompare(b.kind)); + return { tournaments, events, segments, flags, misreads: misreads.sort((a, b) => a.t - b.t || a.field.localeCompare(b.field)) }; } // Phase segments: a phase seen on ONE frame between two frames of another @@ -398,42 +577,53 @@ function phaseSegments(rs: readonly R[], o: { everySeconds: number; durationSeco return out; } -// The model's own events (a banner on screen), one per run: the same kind -// again within a minute is the same moment. -function frameEvents(rs: readonly R[], keys: readonly (string | null)[]): DerivedEvent[] { +// The model's own events (a banner on screen), checked against the rest of +// what was read, one per run (the same kind within a minute is one moment): +// - `won` is dropped: the model says it for any player's hand. A hand the +// hero takes is the log's `pot`/`big-pot`; the tournament won is the +// players-left series reaching one. +// - `bust` / `eliminated` stand only when no table frame in the next two +// minutes shows chips in front of the hero. +// - `final-table` stands only beside a stats header of 9 or fewer left. +function frameEvents(rs: readonly R[], keys: readonly (string | null)[], full: ReadonlyMap<string, Record<string, Pt[]>>): DerivedEvent[] { const out: DerivedEvent[] = []; + const headerLeft = [...full.values()].flatMap((p) => p.playersLeft ?? []); rs.forEach((r, i) => { - if (!r.event) return; - const prev = out.filter((e) => e.kind === r.event).pop(); + const kind = r.event; + if (!kind || kind === "won") return; + if ((kind === "bust" || kind === "eliminated") && rs.some((x) => x.t > r.t && x.t - r.t <= 120 && x.phase === "table" && (x.hero?.stack ?? 0) > 0)) return; + if (kind === "final-table" && !headerLeft.some((p) => Math.abs(p.t - r.t) <= 120 && p.v <= FINAL_TABLE)) return; + const prev = out.filter((e) => e.kind === kind).pop(); if (prev && r.t - prev.t <= 60) return; - const e: DerivedEvent = { t: r.t, kind: r.event, detail: `shown on screen at ${clock(r.t)}`, source: "frame" }; + const e: DerivedEvent = { t: r.t, kind, detail: `shown on screen at ${clock(r.t)}`, source: "frame" }; if (keys[i]) e.tournament = keys[i]!; out.push(e); }); return out; } -// Events the series show: a double-up (×1.8 or more, held by the next point — -// a change at a tournament's last point is not judged), a big loss (half or -// more gone, held), a bust (the stack at 0 and no later -// chips in that tournament), the final table (players left first ≤ 9 in a -// field that was larger), a win (one player left, the hero with chips). -function seriesEvents(tournaments: readonly DerivedTournament[], full: ReadonlyMap<string, Record<string, Pt[]>>): DerivedEvent[] { +// Events the series show, on the kept points (excursions and misreads set +// aside) and never on a flagged point: +// - a double-up (×1.8 or more) or a big loss (half or more gone), its new +// level held by the reading after it (two readings at least); +// - a bust (the stack at 0 and no later chips in that tournament); +// - the final table: players left first at 9 or fewer (not 1) after a +// reading of more than 9 EARLIER in the tournament; +// - a win: one player left, the hero with chips. +function seriesEvents(tournaments: readonly DerivedTournament[], full: ReadonlyMap<string, Record<string, Pt[]>>, flagged: ReadonlySet<string>): DerivedEvent[] { const out: DerivedEvent[] = []; + const ok = (field: string) => (p: Pt) => !flagged.has(`${field}@${p.t}`); for (const tour of tournaments) { - // Frame points only (a spoken number fills a gap, it does not make an - // event), every one of them: a change is judged by the reading after it. - const stack = full.get(tour.key)?.stack ?? []; + const stack = (full.get(tour.key)?.stack ?? []).filter(ok("stack")); for (let i = 1; i < stack.length; i++) { const a = stack[i - 1]; const b = stack[i]; if (a.v === b.v) continue; const after = stack[i + 1]; - // Held: the point after agrees, so one late misread cannot make an event. - if (!after) continue; - if (a.v > 0 && b.v / a.v >= 1.8 && after.v / a.v >= 1.6) { + if (!after || !agree(after.v, b.v, HELD)) continue; + if (a.v > 0 && b.v / a.v >= 1.8) { out.push({ t: b.t, kind: "double-up", detail: `${fmtNum(a.v)} → ${fmtNum(b.v)} chips (${(b.v / a.v).toFixed(1)}×)`, source: "series", tournament: tour.key }); - } else if (a.v > 0 && b.v > 0 && b.v / a.v <= 0.5 && after.v / a.v <= 0.6) { + } else if (a.v > 0 && b.v > 0 && b.v / a.v <= 0.5) { out.push({ t: b.t, kind: "big-loss", detail: `${fmtNum(a.v)} → ${fmtNum(b.v)} chips`, source: "series", tournament: tour.key }); } } @@ -442,10 +632,9 @@ function seriesEvents(tournaments: readonly DerivedTournament[], full: ReadonlyM const before = stack[zero - 1]; out.push({ t: stack[zero].t, kind: "bust", detail: before ? `out from ${fmtNum(before.v)} chips` : "out", source: "series", tournament: tour.key }); } - const left = full.get(tour.key)?.playersLeft ?? []; - const larger = (tour.facts.totalPlayers ?? 0) > FINAL_TABLE || left.some((p) => p.v > FINAL_TABLE); - const ft = left.find((p) => p.v <= FINAL_TABLE && p.v > 1); - if (larger && ft) out.push({ t: ft.t, kind: "final-table", detail: `${ft.v} players left`, source: "series", tournament: tour.key }); + const left = (full.get(tour.key)?.playersLeft ?? []).filter(ok("playersLeft")); + const ftIdx = left.findIndex((p, i) => p.v <= FINAL_TABLE && p.v > 1 && left.slice(0, i).some((q) => q.v > FINAL_TABLE)); + if (ftIdx >= 0) out.push({ t: left[ftIdx].t, kind: "final-table", detail: `${left[ftIdx].v} players left`, source: "series", tournament: tour.key }); const one = left.find((p) => p.v === 1); const lastStack = stack[stack.length - 1]; if (one && lastStack && lastStack.v > 0 && lastStack.t >= one.t - 120) out.push({ t: one.t, kind: "won", detail: "one player left", source: "series", tournament: tour.key }); @@ -461,28 +650,6 @@ const POT_LINE = /^dealer:\s*(.+?) takes the (?:(main|side) )?pot ([\d,]+)(?: wi const FINISHED_LINE = /\bhas finished the tournament in (\d+)(?:st|nd|rd|th)?\b/i; -// What a frame's log says that the frame did not show: the last "Blinds are -// now a/b" (the log holds the change for a while after it), and the players -// left from the lowest "<name> has finished the tournament in Nth" (N - 1). -function withLogBlinds(r0: R): R { - let r = r0; - if (r.tournament?.playersLeft === undefined && r.log?.length) { - const places = r.log.map((l) => FINISHED_LINE.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => Number(m[1])); - const low = places.length ? Math.min(...places) : 0; - if (low > 1) r = { ...r, tournament: { ...(r.tournament ?? {}), playersLeft: low - 1 } }; - } - if (r.tournament?.blinds?.bb !== undefined || !r.log?.length) return r; - for (let i = r.log.length - 1; i >= 0; i--) { - const m = BLINDS_LINE.exec(r.log[i]); - if (!m) continue; - const sb = digits(m[1]); - const bb = digits(m[2]); - if (!(sb > 0 && bb >= sb)) return r; - return { ...r, tournament: { ...(r.tournament ?? {}), blinds: { ...(r.tournament?.blinds ?? {}), sb, bb } } }; - } - return r; -} - const sameName = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase(); // The hero's moments in the log, each line once: a line seen again within @@ -535,12 +702,15 @@ function spokenEvents(spoken: readonly SpokenReading[]): DerivedEvent[] { .map((s) => ({ t: s.t, kind: "buy-in", detail: `$${fmtNum(s.value)} buy-in said: "${s.text}"`, source: "spoken" as const })); } -// A spoken number beside a frame reading of the same field: agree, or a flag. -// With no frame reading within the window, it fills the series of the -// tournament the moment is in (marked "spoken"). Facts (buy-in, prize, field) -// go to the tournament's facts when a frame did not read them. -function crossCheck(tournaments: DerivedTournament[], spoken: readonly SpokenReading[]): DerivedFlag[] { +// A spoken number beside the frame readings of its field: when no frame point +// within the window agrees with it, every one of them is FLAGGED (and makes no +// event); the flag names the nearest. With no frame point within the window, +// the number fills the series of the tournament the moment is in (marked +// "spoken") when it fits the readings either side, else it is flagged. Facts +// (buy-in, prize, field) go to the tournament's facts when no frame read them. +function crossCheck(tournaments: DerivedTournament[], full: ReadonlyMap<string, Record<string, Pt[]>>, spoken: readonly SpokenReading[]): { flags: DerivedFlag[]; flagged: Set<string> } { const flags: DerivedFlag[] = []; + const flagged = new Set<string>(); const at = (t: number) => tournaments.find((x) => t >= x.from - SPOKEN_WINDOW_S && t <= x.to + SPOKEN_WINDOW_S) ?? null; const fills: { tour: DerivedTournament; field: string; t: number; v: number }[] = []; for (const s of spoken) { @@ -550,17 +720,35 @@ function crossCheck(tournaments: DerivedTournament[], spoken: readonly SpokenRea continue; } if (!tour) continue; - const frame = nearest(pts((tour.series[s.field] ?? []).filter((p) => p.length === 2)), s.t, SPOKEN_WINDOW_S); - if (frame) { - if (!agree(s.value, frame.v, SPOKEN_AGREE[s.field])) flags.push({ t: s.t, field: s.field, spoken: s.value, frame: frame.v, frameT: frame.t, tournament: tour.key }); - } else fills.push({ tour, field: s.field, t: s.t, v: s.value }); + const all = full.get(tour.key)?.[s.field] ?? []; + const near = all.filter((p) => Math.abs(p.t - s.t) <= SPOKEN_WINDOW_S); + if (!near.length) { + // A gap is filled only by a number that fits the readings either side + // of it (within 2×): one that fits neither is about something else (the + // other tournament, a hand) — flagged against the nearer, not drawn. + const before = [...all].reverse().find((p) => p.t < s.t); + const after = all.find((p) => p.t > s.t); + const sides = [before, after].filter((p): p is Pt => !!p); + if (sides.length && sides.every((p) => ratioOf(s.value, p.v) > 2)) { + const n = [...sides].sort((a, b) => Math.abs(a.t - s.t) - Math.abs(b.t - s.t))[0]; + flags.push({ t: s.t, field: s.field, spoken: s.value, frame: n.v, frameT: n.t, tournament: tour.key }); + } else fills.push({ tour, field: s.field, t: s.t, v: s.value }); + continue; + } + // One frame in the window that agrees settles it (the number moved + // before or after); none agreeing flags every one of them. + if (near.some((p) => agree(s.value, p.v, SPOKEN_AGREE[s.field]))) continue; + const bad = near; + for (const p of bad) flagged.add(`${s.field}@${p.t}`); + const nearest = [...bad].sort((a, b) => Math.abs(a.t - s.t) - Math.abs(b.t - s.t))[0]; + if (nearest) flags.push({ t: s.t, field: s.field, spoken: s.value, frame: nearest.v, frameT: nearest.t, tournament: tour.key }); } for (const f of fills) { const list = (f.tour.series[f.field] ??= []); list.push([f.t, f.v, "spoken"]); list.sort((a, b) => a[0] - b[0]); } - return flags; + return { flags, flagged }; } export const POKER_PROFILE: FrameProfile<PokerReading> = { diff --git a/common/lib/frames/pokerDerive.test.ts b/common/lib/frames/pokerDerive.test.ts @@ -0,0 +1,141 @@ +// The derivation against the shapes the first live scan showed (release 30, +// lane P follow-up): pokerReadings.mjs, synthetic values, one part per +// failure. Each test names the failure it pins. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { syntheticPokerReadings, SYNTH_HERO, SYNTH_TITLE } from "../../testing/frames/pokerReadings.mjs"; +import { canonicalTitle, derivePoker, looksLikeTitle, nameSimilarity, type PokerReading } from "./poker"; +import { rederiveRecord } from "./scan"; +import type { FrameScanRecord } from "../frameScan-server"; + +type R = PokerReading & { t: number }; +const fx = syntheticPokerReadings(); +const d = derivePoker(fx.readings as R[], fx.spoken, { everySeconds: 10, hero: fx.hero }); +const kinds = (k: string) => d.events.filter((e) => e.kind === k).map((e) => e.t); +const tour = d.tournaments[0]; + +test("one tournament: hand descriptions, a seat's name and misreads of the title do not switch it", () => { + assert.equal(d.tournaments.length, 1); + assert.equal(tour.name, SYNTH_TITLE); + assert.equal(tour.from, 0); +}); + +test("a title: not a hand, not a seat the log names, not the hero; misreads cluster to one", () => { + assert.equal(looksLikeTitle("Three of a Kind Eights"), false); + assert.equal(looksLikeTitle("with Three of a Kind Jacks."), false); + assert.equal(looksLikeTitle("SeatAlpha", { speakers: ["SeatAlpha"] }), false); + assert.equal(looksLikeTitle("SeatAIpha", { speakers: ["SeatAlpha"] }), false); + assert.equal(looksLikeTitle("SynthHer0", { hero: SYNTH_HERO }), false); + assert.equal(looksLikeTitle("SYNTH NLH PKO"), true); + assert.ok(nameSimilarity("SYNTHNLHKAO", "SYNTH NLH PKO") >= 0.75); + assert.equal(canonicalTitle(["SYNTH", "SYNTH NLH PKO", "Synth NLH PKO", "SYNTH NLH PKO", "SYNTH NLH10", "Other Cup"]), "SYNTH NLH PKO"); + assert.equal(canonicalTitle(["Alpha Cup", "Zed Open"]), null); + assert.equal(canonicalTitle(["Lone Cup"]), "Lone Cup"); +}); + +test("a second tournament only after a confirmed bust and a screen away from the table", () => { + const rs: R[] = [ + { t: 0, phase: "table", tournament: { name: "Cup One" }, hero: { stack: 5000 } }, + { t: 10, phase: "table", tournament: { name: "Cup Two" }, hero: { stack: 5100 } }, + // A single 0 between two stacks, then a break: not a bust (not held, no banner). + { t: 20, phase: "table", hero: { stack: 0 } }, + { t: 30, phase: "break" }, + { t: 40, phase: "table", hero: { stack: 5200 } }, + // A held 0, the banner, a lobby, then chips: the next tournament. + { t: 50, phase: "table", hero: { stack: 0 }, event: "eliminated" }, + { t: 60, phase: "table", hero: { stack: 0 } }, + { t: 70, phase: "lobby" }, + { t: 80, phase: "table", tournament: { name: "Cup Three" }, hero: { stack: 1500 } }, + ]; + const x = derivePoker(rs, [], { everySeconds: 10 }); + assert.equal(x.tournaments.length, 2); + assert.equal(x.tournaments[1].from, 80); + assert.equal(x.tournaments[1].name, "Cup Three"); +}); + +test("a mid-hand dip that returns, and a single wild misread, make no double-up or big loss", () => { + assert.deepEqual(kinds("double-up"), []); + assert.deepEqual(kinds("big-loss"), []); + const set = d.misreads.filter((m) => m.field === "stack").map((m) => m.t); + for (const t of [320, 330, 340, 350, 370]) assert.ok(set.includes(t), `${t} set aside`); + assert.ok(!tour.series.stack.some(([, v]) => v === 153000 || v === 140000)); +}); + +test("a double-up needs its new level held by the next reading", () => { + const base = (t: number, stack: number): R => ({ t, phase: "table", tournament: { name: "Cup" }, hero: { stack } }); + const once = derivePoker([base(0, 10000), base(10, 10000), base(20, 25000), base(200, 9000), base(210, 9000)], [], { everySeconds: 10 }); + assert.deepEqual(once.events.filter((e) => e.kind === "double-up"), []); + const held = derivePoker([base(0, 10000), base(10, 10000), base(20, 25000), base(30, 25500), base(40, 25500)], [], { everySeconds: 10 }); + assert.deepEqual(held.events.filter((e) => e.kind === "double-up").map((e) => e.t), [20]); +}); + +test("players left only from the stats header: a table's seats and a bare count are not the field; no final table from them", () => { + assert.deepEqual(kinds("final-table"), []); + const left = tour.series.playersLeft; + assert.ok(!left.some(([, v]) => v <= 9), JSON.stringify(left)); + assert.deepEqual(left.find(([t]) => t === 90), [90, 85, "spoken"]); + assert.ok(left.some(([t, v]) => t === 200 && v === 85)); +}); + +test("a flagged reading makes no event; the final table needs a larger field read EARLIER", () => { + const h = (t: number, left: number, position = 1): R => ({ t, phase: "table", tournament: { name: "Cup", playersLeft: left, position }, hero: { stack: 1000 } }); + // 7 left read first and held, the field (85) said beside it: flagged, and nothing larger before it. + const early = derivePoker([h(0, 7, 3), h(10, 7, 3), h(20, 7, 3)], [{ t: 20, field: "playersLeft", value: 85, text: "85 left" }], { everySeconds: 10 }); + assert.deepEqual(early.events.filter((e) => e.kind === "final-table"), []); + assert.equal(early.flags.length, 1); + // Players left never rise: a 7 followed within ten minutes by 80 is a misread. + const rises = derivePoker([h(0, 7, 3), h(10, 7, 3), h(400, 80)], [], { everySeconds: 10 }); + assert.deepEqual(rises.tournaments[0].series.playersLeft, [[400, 80]]); + // A real one: 12, 10, then 9. + const real = derivePoker([h(0, 12), h(10, 10), h(20, 9), h(30, 9)], [], { everySeconds: 10 }); + assert.deepEqual(real.events.filter((e) => e.kind === "final-table").map((e) => e.t), [20]); +}); + +test("the log's blinds are the truth: a big blind misread is set aside, stack in big blinds stays sane", () => { + assert.ok(d.misreads.some((m) => m.field === "bigBlind" && m.t === 480 && m.value === 100)); + assert.ok(tour.series.bigBlind.every(([, v]) => v === 2000), JSON.stringify(tour.series.bigBlind)); + assert.ok(tour.series.stackBB.every(([, v]) => v <= 200), JSON.stringify(tour.series.stackBB)); +}); + +test("before the log says any, blinds only go up and never above the first the log says", () => { + const b = (t: number, bb: number | undefined, log?: string[]): R => ({ t, phase: "table", tournament: { name: "Cup", ...(bb ? { blinds: { bb } } : {}) }, hero: { stack: 100000 }, ...(log ? { log } : {}) }); + const x = derivePoker([b(0, 600), b(10, 1200), b(20, 300), b(30, 2400), b(40, undefined, ["Blinds are now 900/1,800"])], [], { everySeconds: 10 }); + assert.deepEqual(x.tournaments[0].series.bigBlind, [[0, 600], [10, 1200], [40, 1800]]); +}); + +test("the model's 'won' is not an event; an 'eliminated' with chips after it is not either; the real end is", () => { + assert.deepEqual(kinds("won"), []); + assert.deepEqual(kinds("eliminated"), [650]); + assert.deepEqual(kinds("bust"), [650]); + // The hero's pot from the log (60,000 at 2,000: 30 BB). + assert.deepEqual(d.events.filter((e) => e.source === "log").map((e) => [e.t, e.kind]), [[540, "big-pot"]]); +}); + +test("rederiveRecord: derived worked out again from the stored readings, no model, the rest kept", () => { + const rec = { + format: "archilyzer-frame-scan", + version: 1, + profile: "poker", + source: { savedVideo: "source-media.mp4", durationSeconds: 700 }, + sampling: { everySeconds: 10, from: 0, to: 700, width: 1280, keyframesOnly: true, frames: 70, kept: 69, skippedDuplicates: 1 }, + model: { route: "api", model: "claude-haiku-4-5", promptVersion: 2 }, + hints: { hero: SYNTH_HERO }, + costUsd: 1.23, + runs: [{ at: "2026-10-15T00:00:00Z", model: "claude-haiku-4-5", route: "api", frames: 70, read: 69, failed: 0, costUsd: 1.23 }], + readings: fx.readings.filter((r) => r.t !== 680), + duplicates: [[680, 670]], + spoken: fx.spoken, + derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] }, + updatedAt: "2026-10-15T00:00:00Z", + } as unknown as FrameScanRecord; + const out = rederiveRecord(rec, { now: () => new Date("2026-10-16T00:00:00Z") }); + assert.equal(out.derived.tournaments.length, 1); + assert.deepEqual(out.derived, derivePoker(fx.readings as R[], fx.spoken, { everySeconds: 10, durationSeconds: 700, hero: SYNTH_HERO })); + assert.equal(out.costUsd, 1.23); + assert.deepEqual(out.runs, rec.runs); + assert.equal(out.rederivedAt, "2026-10-16T00:00:00.000Z"); + // With cues, the spoken numbers are read again. + const withCues = rederiveRecord(rec, { cues: [{ start: 5, end: 8, text: "ninety players left" }] }); + assert.deepEqual(withCues.spoken.map((s) => [s.t, s.field, s.value]), [[5, "playersLeft", 90]]); +}); diff --git a/common/lib/frames/scan.test.ts b/common/lib/frames/scan.test.ts @@ -134,7 +134,8 @@ test("a scan on the API: images as JPEG blocks, readings, the derived timeline, assert.deepEqual(events.filter(([, k]) => k !== "buy-in"), [ [90, "double-up"], [120, "big-loss"], - [120, "final-table"], + // No final table at 120: the frames' 9 left is flagged against the spoken + // "four players left", and a flagged reading makes no event. [180, "bust"], [180, "eliminated"], ]); diff --git a/common/lib/frames/scan.ts b/common/lib/frames/scan.ts @@ -20,7 +20,7 @@ import { PromptTooLargeError } from "../llm/ollama"; import { duplicatesOf } from "./dhash"; import { frameProfile } from "./profiles"; import { probeDuration, sampleFrames, type Crop, type FrameIndex } from "./sample-server"; -import { FRAME_SCAN_FORMAT, type Cue, type FrameRef } from "./types"; +import { FRAME_SCAN_FORMAT, type Cue, type Derived, type FrameRef, type SpokenReading } from "./types"; import type { FrameScanRecord, FrameScanRun } from "../frameScan-server"; export const DEFAULT_EVERY_SECONDS = 10; @@ -109,6 +109,58 @@ function askEstimateUsd(model: string, images: Buffer[], promptChars: number): n return (input * p.input + output * p.output) / 1e6; } +/** + * The derived timeline of a scan's readings — the readings, the duplicates as + * copies of what they show (a held stack is held on every frame, read or not), + * and the spoken numbers, through the profile's pure derivation. No model, no + * frame: what a scan writes and what a re-derive rewrites. + */ +export function deriveOf( + profileId: string, + readings: FrameScanRecord["readings"], + duplicates: readonly [number, number][], + spoken: SpokenReading[], + o: { everySeconds: number; durationSeconds?: number | null; hero?: string }, +): Derived { + const profile = frameProfile(profileId); + const byT = new Map(readings.map((r) => [r.t, r])); + const copies = duplicates.flatMap(([t, src]) => { + const r = byT.get(src); + return r && !byT.has(t) ? [{ ...r, t }] : []; + }); + const expanded = [...readings, ...copies].sort((a, b) => a.t - b.t); + return profile.derive(expanded as never, spoken, { + everySeconds: o.everySeconds, + ...(o.durationSeconds !== null && o.durationSeconds !== undefined ? { durationSeconds: o.durationSeconds } : {}), + ...(o.hero ? { hero: o.hero } : {}), + }); +} + +/** + * A scan's record with its `derived` (and, given cues, its `spoken`) worked + * out again from what it holds — ZERO model calls, no frames. Its readings, + * runs and spend are kept as they were; `rederivedAt` says when. After the + * derivation's rules change, this is what brings an old sidecar up to date. + */ +export function rederiveRecord(rec: FrameScanRecord, o: { cues?: Cue[]; hero?: string; now?: () => Date } = {}): FrameScanRecord { + const profile = frameProfile(rec.profile); + const spoken = o.cues ? profile.spoken(o.cues) : rec.spoken; + const hints = o.hero ? { ...(rec.hints ?? {}), hero: o.hero } : rec.hints; + const at = (o.now ?? (() => new Date()))().toISOString(); + return { + ...rec, + ...(hints ? { hints } : {}), + spoken, + derived: deriveOf(rec.profile, rec.readings, rec.duplicates ?? [], spoken, { + everySeconds: rec.sampling.everySeconds, + durationSeconds: rec.source.durationSeconds, + hero: hints?.hero, + }), + rederivedAt: at, + updatedAt: at, + }; +} + export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Promise<FrameScanOutcome> { const log = o.onLog ?? (() => {}); const profile = frameProfile(o.profile); @@ -176,13 +228,7 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr }); const record = (): FrameScanRecord => { const all = [...readings.values()].sort((a, b) => a.t - b.t); - // The derivation reads the duplicates too, as copies of what they show: - // a held stack is held on every frame, read or not. - const copies = [...dupPairs].flatMap(([t, src]) => { - const r = readings.get(src); - return r && !readings.has(t) ? [{ ...r, t }] : []; - }); - const expanded = [...all, ...copies].sort((a, b) => a.t - b.t); + const duplicates = [...dupPairs].sort((a, b) => a[0] - b[0]); const spoken = o.cues ? profile.spoken(o.cues) : (prev?.spoken ?? []); return { format: FRAME_SCAN_FORMAT, @@ -205,9 +251,9 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr costUsd: Math.round(((prev?.costUsd ?? 0) + meter.usd) * 10_000) / 10_000, runs: [...(prev?.runs ?? []), runOf()], readings: all, - duplicates: [...dupPairs].sort((a, b) => a[0] - b[0]), + duplicates, spoken, - derived: profile.derive(expanded as never, spoken, { everySeconds: every, ...(duration !== null ? { durationSeconds: duration } : {}), ...(hints.hero ? { hero: hints.hero } : {}) }), + derived: deriveOf(profile.id, all, duplicates, spoken, { everySeconds: every, durationSeconds: duration, hero: hints.hero }), updatedAt: now().toISOString(), }; }; diff --git a/common/lib/frames/series.test.ts b/common/lib/frames/series.test.ts @@ -36,3 +36,15 @@ test("changesOnly and nearest", () => { assert.deepEqual(nearest(P([[0, 1], [50, 2], [90, 3]]), 60, 20), { t: 50, v: 2 }); assert.equal(nearest(P([[0, 1]]), 60, 20), null); }); + +test("dropExcursions: a mid-hand dip that returns within the window is set aside; a level left for good stays", async () => { + const { dropExcursions } = await import("./series"); + const dip = P([[0, 345000], [10, 345000], [20, 296000], [30, 296000], [40, 153000], [50, 153000], [60, 344900], [70, 140000], [80, 344900], [90, 345000]]); + const r = dropExcursions(dip, { returnRatio: 1.1, windowS: 90 }); + assert.deepEqual(r.dropped.map((p) => p.t), [20, 30, 40, 50, 70]); + assert.deepEqual(r.kept.map((p) => p.v), [345000, 345000, 344900, 344900, 345000]); + // A real double-up holds: nothing to return to. + assert.deepEqual(dropExcursions(P([[0, 20000], [10, 41000], [20, 41000]]), { returnRatio: 1.1, windowS: 90 }).dropped, []); + // A return after the window is a change and a change back. + assert.deepEqual(dropExcursions(P([[0, 100], [10, 300], [200, 100]]), { returnRatio: 1.1, windowS: 90 }).dropped, []); +}); diff --git a/common/lib/frames/series.ts b/common/lib/frames/series.ts @@ -81,3 +81,36 @@ export function nearest(points: readonly Pt[], t: number, window: number): Pt | } return best; } + +/** + * Excursions set aside: a run of points that leaves a level and comes back to + * it (within `returnRatio`) inside `windowS` seconds of the last point before + * it. A stack read mid-hand (chips in the pot are not in front of the player) + * dips and returns when the pot is won; a misread does the same. Neither is a + * change of the stack. A level that is left and not returned to stays. + */ +export function dropExcursions(points: readonly Pt[], o: { returnRatio: number; windowS: number }): { kept: Pt[]; dropped: Pt[] } { + const kept: Pt[] = []; + const dropped: Pt[] = []; + const back: AgreeRule = { ratio: o.returnRatio }; + let i = 0; + while (i < points.length) { + const anchor = kept[kept.length - 1]; + const p = points[i]; + if (!anchor || agree(p.v, anchor.v, back)) { + kept.push(p); + i++; + continue; + } + let j = i + 1; + while (j < points.length && points[j].t - anchor.t <= o.windowS && !agree(points[j].v, anchor.v, back)) j++; + if (j < points.length && points[j].t - anchor.t <= o.windowS) { + for (let k = i; k < j; k++) dropped.push(points[k]); + i = j; + } else { + kept.push(p); + i++; + } + } + return { kept, dropped }; +} diff --git a/common/testing/frames/pokerReadings.d.mts b/common/testing/frames/pokerReadings.d.mts @@ -0,0 +1,8 @@ +export const SYNTH_HERO: string; +export const SYNTH_TITLE: string; +export function syntheticPokerReadings(): { + readings: ({ t: number; phase: string } & Record<string, unknown>)[]; + spoken: { t: number; field: string; value: number; text: string }[]; + hero: string; + title: string; +}; diff --git a/common/testing/frames/pokerReadings.mjs b/common/testing/frames/pokerReadings.mjs @@ -0,0 +1,70 @@ +// Poker readings with the SHAPES the first live scan showed (release 30, the +// frame derivation's follow-up) — synthetic values and names, none of the +// stream's. Each part is one failure the first derivation fell into: +// +// - the title field holding a hand description from the log, a seat's +// name (one the log shows taking a pot) and misreads of the real title +// ("SYNTH NLH PKO", "SYNTH", "SYNTH NLH10", "SYNTHNLHKAO"); +// - the hero's stack dipping mid-hand and coming back (chips in the pot are +// not in front of the player), and one wild misread between two that agree; +// - players left read off a table's seats ("7 of 7", a 6 with no position) +// and a spoken "85 players left" beside them; +// - a big blind misread (100 and 1,250 where the log says 2,000); +// - the model's "won" banner on other players' hands, and an "eliminated" +// with the hero's chips still there after it; +// - and the real end: the hero's stack at 0, the banner, a break screen. +// +// `syntheticPokerReadings()` → { readings, spoken, hero, title, expect }. + +export const SYNTH_HERO = "SynthHero"; +export const SYNTH_TITLE = "SYNTH NLH PKO"; + +const table = (t, stack, more = {}) => ({ t, phase: "table", ...(stack !== undefined ? { hero: { stack } } : {}), ...more }); + +export function syntheticPokerReadings() { + const rs = []; + // 0–290: the opening table; noisy players-left (a table's 7 of 7, then 6 + // with no position), the header later reads 85 of the field. + for (let t = 0; t < 300; t += 10) { + const more = {}; + if (t >= 40 && t < 80) more.tournament = { playersLeft: 7, totalPlayers: 7, position: 3 }; + if (t >= 80 && t < 120) more.tournament = { playersLeft: 6 }; + if (t >= 200 && t < 260) more.tournament = { playersLeft: 85, position: 40 }; + if (t === 20) more.tournament = { name: "Three of a Kind Eights" }; + if (t === 30) more.tournament = { name: "SeatAlpha" }; + rs.push(table(t, 345000 - t, more)); + } + // 300–590: a mid-hand dip that returns (345k → 296k → 153k → 345k) and a + // single wild misread; the title read in its variants; the log's blinds. + const dip = { 300: 345000, 310: 345000, 320: 296000, 330: 296000, 340: 153000, 350: 153000, 360: 344900, 370: 140000, 380: 344900 }; + for (let t = 300; t < 600; t += 10) { + const names = { 400: SYNTH_TITLE, 410: SYNTH_TITLE, 420: "Synth NLH PKO", 430: SYNTH_TITLE, 440: "SYNTH", 445: "SYNTH", 450: "SYNTH NLH10", 460: "SYNTHNLHKAO", 470: "Two pair Jacks and Fours with the kicker Ace" }; + const tour = {}; + if (names[t]) tour.name = names[t]; + if (t === 480) tour.blinds = { sb: 50, bb: 100 }; + if (t === 490) tour.blinds = { sb: 625, bb: 1250 }; + const log = []; + if (t >= 300 && t < 330) log.push("Blinds are now 1,000/2,000", "Antes are now 300"); + if (t === 330) log.push("Dealer: SeatAlpha takes the pot 30,000."); + if (t === 520) log.push("Dealer: SeatBravo takes the main pot 200,000 with Two pair Kings and Fives."); + if (t === 540) log.push("Dealer: SynthHero takes the pot 60,000."); + const r = table(t, dip[t] ?? 345000, { ...(Object.keys(tour).length ? { tournament: tour } : {}), ...(log.length ? { log } : {}) }); + // The model's "won" on other players' pots, and once on the hero's. + if (t === 520 || t === 540) r.event = "won"; + // An "eliminated" with the hero's chips still there after it. + if (t === 560) r.event = "eliminated"; + rs.push(r); + } + // 600–690: the end — the stack goes to 0 with the banner, then a break screen. + for (let t = 600; t < 650; t += 10) rs.push(table(t, 330000)); + rs.push(table(650, 0, { event: "eliminated" })); + rs.push(table(660, 0)); + rs.push({ t: 670, phase: "break" }); + rs.push({ t: 680, phase: "break" }); + return { + readings: rs, + spoken: [{ t: 90, field: "playersLeft", value: 85, text: "eighty five players left" }], + hero: SYNTH_HERO, + title: SYNTH_TITLE, + }; +} diff --git a/common/testing/frames/syntheticPoker.mjs b/common/testing/frames/syntheticPoker.mjs @@ -18,15 +18,16 @@ const run = promisify(execFile); export const SYNTH_TOURNAMENT = "Synthetic Cup"; export const SYNTH_DURATION = 210; -// What the fake client shows, by time. Each span is one still picture. +// What the fake client shows, by time. Each span is one still picture. Players +// left is a stats header's "position N of M" (both numbers). export const SYNTH_SPANS = [ - { from: 0, to: 30, phase: "lobby", tournament: { name: SYNTH_TOURNAMENT, totalPlayers: 120, playersLeft: 120 } }, - { from: 30, to: 90, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 3, smallBlind: 100, bigBlind: 200, playersLeft: 85, totalPlayers: 120 }, hero: { stack: 20000 } }, - { from: 90, to: 120, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 4, smallBlind: 150, bigBlind: 300, playersLeft: 60, totalPlayers: 120 }, hero: { stack: 41000 } }, - { from: 120, to: 150, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 5, smallBlind: 200, bigBlind: 400, playersLeft: 9, totalPlayers: 120 }, hero: { stack: 9000 } }, + { from: 0, to: 30, phase: "lobby", tournament: { name: SYNTH_TOURNAMENT, totalPlayers: 120, playersLeft: 120, position: 60 } }, + { from: 30, to: 90, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 3, smallBlind: 100, bigBlind: 200, playersLeft: 85, position: 40, totalPlayers: 120 }, hero: { stack: 20000 } }, + { from: 90, to: 120, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 4, smallBlind: 150, bigBlind: 300, playersLeft: 60, position: 22, totalPlayers: 120 }, hero: { stack: 41000 } }, + { from: 120, to: 150, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 5, smallBlind: 200, bigBlind: 400, playersLeft: 9, position: 8, totalPlayers: 120 }, hero: { stack: 9000 } }, { from: 150, to: 180, phase: "break" }, - { from: 180, to: 200, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 6, smallBlind: 300, bigBlind: 600, playersLeft: 7, totalPlayers: 120 }, hero: { stack: 0 }, event: "eliminated" }, - { from: 200, to: 210, phase: "lobby", tournament: { name: SYNTH_TOURNAMENT, totalPlayers: 120, playersLeft: 6 } }, + { from: 180, to: 200, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 6, smallBlind: 300, bigBlind: 600, playersLeft: 7, position: 7, totalPlayers: 120 }, hero: { stack: 0 }, event: "eliminated" }, + { from: 200, to: 210, phase: "lobby", tournament: { name: SYNTH_TOURNAMENT, totalPlayers: 120, playersLeft: 6, position: 7 } }, ]; /** The reading a perfect model gives at `t` (the answer schema's shape, `frame` left to the caller). */ diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A frame scan's timeline reads like the stream.** One tournament stays one tournament until the streamer busts: a hand description, a player's name or a misread of the title no longer starts a new one, and the tournament is named by the title most frames agree on. A stack read mid-hand (chips in the pot) or misread no longer makes a double-up or a big loss; players left come only from the client's own "position N of M" or the log's finishing places, so a table's seats are not the field and no final table appears from them; the big blind is the log's "Blinds are now", so a stack is never 700 big blinds by a misread; "won" banners on other players' hands are gone. A frame and a spoken number that disagree are flagged, and a flagged reading makes no event. **Re-derive** an existing scan with no model call: `pnpm ops frame-scan --json '{"slug":"<channel>","id":"<video>","rederive":true}'`, or `archilyzer frames rederive <channel>/<video> --dry` to see what would change. Needs a restart of the editor. - **Retrying a corrupt full source downloads it again.** A video whose download completed with malformed audio (Odysee's intermittent AAC, on a channel with the audio check) kept its file, and that file made every retry say "Nothing to fetch". A retry of the **corrupt full sources** bucket — the new card on the channel's Download stage, or `pnpm ops retry-bucket --json '{"slug": "<channel>", "bucket": "corruptFullSource"}'` — now sets the kept file aside and downloads again: a clean result replaces it; a malformed one keeps whichever copy decodes longer; a download that fails (a 429, the network) puts the kept file back and the video stays in the bucket, with the attempt recorded. Each retry is recorded in the video's `download-outcome.json`. Needs a restart of the editor. - **A damaged recording is transcribed for what decodes, instead of not at all.** Transcribing a corrupt full source used to fail at the first bad stretch. It is now decoded with error tolerance, with the stretches that will not decode kept as silence of their own length, so every line of the transcript is at its true time in the recording; with parakeet, a window that still fails is skipped and noted. The transcript is marked **salvaged**: the video page says how much decoded and which stretches have no transcript, and the channel's report lists it under **salvaged transcript**. It happens on its own for a corrupt full source; `pnpm ops transcribe-one --json '{"slug": "<channel>", "id": "<video>", "salvage": true}'` asks for it on any video (`false` turns it off). When a later retry downloads the recording clean, the salvaged transcript is removed so the recording is transcribed again in full. On the sites, a salvaged transcript's video page says "Partial transcript: N of M min decoded", and the MCP's `get_transcript` and `get_video_metadata` say it is partial. Needs a restart of the editor; the sites show it after their next build. - **A saved stream can be scanned frame by frame for a poker tournament's progress.** On a video whose source is in the saved-video store, the video page's new **Frame scan** panel has **Scan frames** (or `pnpm ops frame-scan --json '{"slug":"<channel>","id":"<video>"}'`). The scan takes a frame every 10 seconds (keyframes only, so a 4-hour stream decodes in a minute or two), skips frames that show the same picture as the last one read, and has a vision model read the poker client in the rest: the phase (table, lobby, break), the tournament's name, level, blinds and players left, the hero's chips, the board, an all-in or a bust shown on screen. It also reads the numbers the streamer says in the transcript ("eighty five players left", "the average stack is…"). From both, code works out each tournament's chip and players-left series (one wild reading between two that agree is set aside as a misread), the events (a double-up, a big loss, a bust, the final table, a win), the phases, and a flag wherever a spoken number and a frame disagree. The panel shows the phases as a strip, a small chart per tournament, the events (each time a link to that moment on the video's platform) and the flags. Everything is written to `frame-scan.poker.json` beside the video; the frames themselves are a cache on the channel's media drive, removed with `{"evict": true}`. Scanning again only reads frames not read yet. `"crop": [x, y, w, h]` (fractions of the picture) reads only the poker client when a webcam sits beside it, and `"hero": "<screen name>"` tells the model whose seat is the streamer's; both are remembered for the next scan, and `"fresh": true` reads every frame again (another model). It runs on the Claude API by default (`settings.generation.frames`: Claude Haiku 4.5, a $5 cap a scan, the day's cap as for every generation) or on a local vision model (route `frames` to `local`). Needs a restart of the editor. diff --git a/editor/app/api/ops/_frameScan.test.ts b/editor/app/api/ops/_frameScan.test.ts @@ -6,7 +6,7 @@ import path from "node:path"; import { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; import { makeSyntheticPokerStream, pokerTruthAt, SPOKEN_CUES } from "yt-dlp-transcript-common/testing/frames/syntheticPoker.mjs"; import { enqueueFrameScan, frameScanCap, frameScanModel, parseFrameScanBody } from "yt-dlp-transcript-common/controller/frameScan"; -import { loadFrameScan } from "yt-dlp-transcript-common/lib/frameScan-server"; +import { frameScanSidecar, loadFrameScan } from "yt-dlp-transcript-common/lib/frameScan-server"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; @@ -156,3 +156,25 @@ test("past the day's cap an API scan is refused; a local route goes on draft:loc void local.result.stream.cancel(); await local.result.done; }); + +test("rederive: the derived timeline worked out again from the stored readings, no job and no model; refused with no sidecar", async () => { + const sidecar = frameScanSidecar("poker"); + const rec = (await loadFrameScan(videoDir, "poker"))!; + // An old derivation (any shape the rules once made), and the API asked nothing new. + await sidecar.write(videoDir, { ...rec, derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] } }); + const asked = api.requests.length; + const out = await enqueueFrameScan({ slug: SLUG, id: ID, rederive: true }, deps()); + assert.ok("rederived" in out, JSON.stringify(out)); + assert.equal(out.rederived.before.tournaments, 0); + assert.equal(out.rederived.after.tournaments, 1); + assert.ok((out.rederived.eventsByKind.bust ?? 0) >= 1, JSON.stringify(out.rederived.eventsByKind)); + assert.equal(api.requests.length, asked); + const again = (await loadFrameScan(videoDir, "poker"))!; + assert.equal(again.readings.length, rec.readings.length); + assert.equal(again.costUsd, rec.costUsd); + assert.ok(again.rederivedAt); + const none = await enqueueFrameScan({ slug: SLUG, id: "notsaved1", rederive: true }, deps()); + assert.ok("result" in none && !none.result.ok); + assert.match((none.result as { error: string }).error, /no frame-scan\.poker\.json to re-derive/); + assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", rederive: true, evict: true }), /one at a time/); +}); diff --git a/editor/app/api/ops/frame-scan/route.ts b/editor/app/api/ops/frame-scan/route.ts @@ -6,7 +6,7 @@ import { jobResponse, ops } from "../_lib"; export const dynamic = "force-dynamic"; // POST { slug, id, profile?, everySeconds?, from?, to?, maxFrames?, model?, -// maxUsd?, hero?, framesPerAsk?, crop?, fresh?, evict? } +// maxUsd?, hero?, framesPerAsk?, crop?, fresh?, evict?, rederive? } // -> { ok: true, jobId, model, queueKey } (evict: { ok: true, evicted }) // // The frame scan (release 30, lane P), as a `frame-scan` job: the video's @@ -19,13 +19,17 @@ export const dynamic = "force-dynamic"; // model). The same body again resumes: read frames are not asked again. // Refused when the video is not saved (the sentence names the persist-videos // body), past the day's API cap, or with a maxUsd over caps.max. `evict: true` -// removes the frame cache and answers at once. The log ends `@@frame-scan {json}`. +// removes the frame cache and answers at once; `rederive: true` works the +// sidecar's `derived` out again from its stored readings (no model, no frame) +// and answers `{ rederived: {before, after, tournaments, eventsByKind} }`. The +// log ends `@@frame-scan {json}`. // // AN ADAPTER: the refusals are the controller's (controller/frameScan.ts). export async function POST(request: Request) { return ops(request, FRAME_SCAN_BODY_KEYS, async (body) => { const out = await enqueueFrameScan(body, { paths: getPaths() }); if ("evicted" in out) return NextResponse.json({ ok: true, evicted: out.evicted }); + if ("rederived" in out) return NextResponse.json({ ok: true, rederived: out.rederived }); if (!out.result.ok || !("model" in out)) return jobResponse(out.result); void out.result.stream.cancel(); return NextResponse.json({ ok: true, jobId: out.result.jobId, model: out.model, queueKey: out.queueKey }); diff --git a/editor/app/channels/[slug]/videos/[id]/frameScanActions.ts b/editor/app/channels/[slug]/videos/[id]/frameScanActions.ts @@ -14,6 +14,6 @@ import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCom export async function frameScanAction(slug: string, videoId: string, profile: string): Promise<StreamActionResult> { const out = await enqueueFrameScan({ slug, id: videoId, profile }, { paths: getPaths() }); - if ("evicted" in out) return { ok: false, error: "nothing to scan" }; + if ("evicted" in out || "rederived" in out) return { ok: false, error: "nothing to scan" }; return out.result; } diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9690,6 +9690,13 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **Resume** is by grid time: a reading in the sidecar is never asked again; a frame whose dHash (17×16 grey thumbnail, `lib/frames/dhash.ts`) is within the profile's `dupMaxBits` of the last READ frame is not asked (re-read every `rereadEvery`); the derivation reads duplicates as copies of the frame they show. +- **The derivation's rules since `r30/frame-derive`** (they supersede the bullet below where they differ): a tournament + changes only after a confirmed bust + a screen away + chips again (never on a name); its name is `canonicalTitle` of + `looksLikeTitle` names; stack excursions (left and returned to within 90 s) are set aside before events; players left + only from a header (position beside it) or finishing lines, never rising; the log's "Blinds are now" is the big blind; + the model's `won` is no event. `rederiveRecord` / `deriveOf` (`lib/frames/scan.ts`) recompute `derived` from a + record with no model — `frame-scan {rederive: true}`, `archilyzer frames rederive <slug>/<id>`; `rederivedAt` on the + record. - **The reading** is the model's; everything else is code: `coercePokerReading` (ranges, enums, card format, misread pairs dropped), `derivePoker` (series per tournament keyed by the name on screen — unnamed readings take the name before them; a field size change over 1.5× is `<name>#2`; a misread is a point both neighbours agree against; events diff --git a/plans/release-30/frame-derive.md b/plans/release-30/frame-derive.md @@ -0,0 +1,64 @@ +# Release 30, lane P follow-up: the frame derivation (`r30/frame-derive`) + +The first live scan (`v7gkv5w`, 1,139 readings, $4.06 on Haiku 4.5) read well and derived badly: 26 tournaments +where there is one, false double-ups from mid-hand dips, a final table from a table's seat count, stacks of 730 BB +from a misread big blind, six "won" banners on other players' hands. The readings were kept; only the derivation +changed, and a re-derive brings the sidecar up to date with no model call. + +### D1–D6, as shipped (2026-10-15, lane P, `r30/frame-derive` from `main` `14d09aa2`) + +- **D1 One tournament unless the hero is out.** A name read is no longer evidence of a tournament: the model put hand + descriptions, seat names and title misreads in the field. A tournament changes only after a CONFIRMED bust (a stack + of 0 held on the reading beside it, a bust/eliminated banner on it or beside it, or the hero's "has finished the + tournament" line within a minute), a screen away from the table, and chips in front of the hero again. Its name is + `canonicalTitle` of its title-like names (`looksLikeTitle`: not a hand description, not a name the log shows as a + player — `speakersOf` — not the hero, at 75% letter similarity), clustered (case and punctuation, one name's words the + start of the other's, or 75% alike) and named by the biggest cluster's most frequent spelling when it is read at + least 3 times (or is the only one). The old field-size split (totalPlayers changing by 1.5×) is gone (misreads). + A Day/structure change in the header is not a trigger: Day 1B → Day 2 is one tournament, and the header's "Day" was + misread ("Day 18's"). +- **D2 Dips are not events.** `dropExcursions` (`series.ts`): a run of stack readings that leaves a level and comes back + to it (within 1.1×) inside 90 s of the last reading before it is set aside (a stack read mid-hand: chips in the pot + are not in front of the player; a misread), before `dropMisreads`. A double-up or big loss needs its new level held + by the next reading (within 1.25×). +- **D3 Players left from the header only.** A reading's players left counts only with a position beside it, the + position within it, and not a table's seats (≤ 10 of ≤ 10); else the log's finishing places. Players left never rise: + a reading followed within ten minutes by one 1.5× and 3 larger is a misread. A spoken number with no agreeing frame + point in its 90-s window flags every one of them, and a flagged point makes no event; a gap is filled by a spoken + number only when it fits a reading either side (within 2×), else it is flagged. The final table needs a field of more + than 9 read EARLIER in the tournament. +- **D4 The log's blinds.** "Blinds are now a/b" is the big blind from the line on, carried until the next; a read + that disagrees with it by more than 2× is a misread (recorded). Before the log says any, reads only go up and never + above the first the log will say. Stack in big blinds is the kept stack over the big blind of its moment (or the + client's own figure). +- **D5 The model's banners.** `won` is not an event (the model said it for other players' pots; a hand the hero takes + is the log's `pot`/`big-pot`; the tournament won is the players-left series reaching one); `bust`/`eliminated` stand + only with no table frame showing the hero's chips in the next two minutes; `final-table` only beside a header of 9 or + fewer. +- **D6 Re-derive.** `rederiveRecord(record, {cues?, hero?})` and `deriveOf` (`lib/frames/scan.ts`): `derived` (and, + with cues, `spoken`) from the stored readings and duplicates, no model, no frame; readings, runs and spend kept, + `rederivedAt` set. `pnpm ops frame-scan --json '{"slug","id","rederive":true}'` (no job; refused while a scan of the + video is queued or running; answers `{rederived: {before, after, tournaments, eventsByKind}}`) and + `archilyzer frames rederive <slug>/<id> [--profile] [--hero] [--dry] [--json]` (offline: cannot see the editor's + jobs). +- **Measured on the live sidecar, in memory (nothing of it committed; a scratch copy for the CLI):** tournaments 26 → + 1 ("VENOM", 130–13,500 s); events 35 → 18 (big-pot 2, pot 11, buy-in 3, bust 1 at 13,480 "out from 66,429", + eliminated 1 at 13,500; no double-up, big loss, final table or won); flags 1 → 6 (85 said vs 65 read at 5:40; 15 + said at 53:38 against a field of 67, the other tournament; a stack, two places and a stack in BB said that disagree); + big blind 625 → 1,250 → 1,600 read, then the log's 1,800 … 5,500; players left 65, 67, then 115 … 86 from the header. + Left: the header's 65/67 at the start are probably misreads of 85 (flagged); the tournament's `buyIn` fact takes the + first said ($5, the viewer tournament's). + +| Commit | What | +| --- | --- | +| `2c98d31e` | common, editor, scripts: the derivation rebuilt (D1–D5), re-derive (D6) on ops and the CLI, the fixtures and tests, COMMANDS.md | +| (this commit) | plans, CHANGELOG, FACTS: this record | + +Gates (from the worktree root; every tsc and suite under the shared heavy2 lock; no build or e2e — the user bus was down): +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean. +- common 4362/4362 (lib/frames 72/72: `pokerDerive.test.ts` 12 on `testing/frames/pokerReadings.mjs`, the derivation's + old tests moved to the new rules, `dropExcursions`); editor unit 319/319 (`_frameScan.test.ts` 7/7 with re-derive); + test:scripts 1033 (1030 + 3 skipped); umtool 33/33; mcp 373/373. +- `docs cli` regenerated; `docs cli --check`, `docs files --check`, `docs env --check`, `settings example --check` clean. +- Not run: the editor e2e and builds (bus down). The panel and supercut code are unchanged; the one `frameScanActions` + line is a type narrowing. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -121,6 +121,7 @@ // pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait // pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait // pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}' +// pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}' // pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait // pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}' // pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}' @@ -453,8 +454,9 @@ const ACTIONS = [ // THE FRAME SCAN (release 30): a saved stream's frames read by a vision // model through a profile (poker) into frame-scan.<profile>.json beside the // video ({slug, id, profile?, everySeconds?, from?, to?, maxFrames?, model?, - // maxUsd?, hero?, framesPerAsk?, evict?}), as a frame-scan job on `frames` - // (API) or draft:local. evict removes the frame cache (no job). + // maxUsd?, hero?, framesPerAsk?, crop?, fresh?, evict?, rederive?}), as a + // frame-scan job on `frames` (API) or draft:local. evict removes the frame + // cache, rederive works the derived timeline out again (no job, no model). "frame-scan", // RECURRING REPORTS (umtool R5): a living report or a dated series on a // cadence the editor keeps ({action: list | create | update | pause | @@ -1433,7 +1435,7 @@ export function usage() { ' screen name, a hint), "framesPerAsk"? (1-8), "crop"? ([x, y, w, h] as', " fractions of the picture: the part read and hashed, e.g. the poker client", ' beside a webcam), "fresh"? (read every frame again: another model or', - ' prompt), "evict"?} -> {jobId, model,', + ' prompt), "evict"?, "rederive"?} -> {jobId, model,', " queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a", " half hour) into a frame cache on the channel's media side; near-duplicate", " frames are skipped; the rest are read by the vision model and the numbers", @@ -1444,7 +1446,10 @@ export function usage() { " again resumes: read frames are never asked again. Refused when the video is", " not saved (persist-videos first) or past caps.daily; the run stops before", ' an ask that would pass maxUsd. {"evict": true} removes the frame cache', - " and answers at once. The log ends with @@frame-scan {slug, id, profile,", + " and answers at once; {\"rederive\": true} works the derived timeline out", + " again from the readings the sidecar holds (no model, no frame; refused", + " while a scan of the video runs) and answers {rederived: {before, after,", + " tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile,", " file, frames, kept, read, failed, readings, spentUsd, totalUsd, events,", " tournaments, flags, stopped?}.", "",