commit 65ce25705b2b22b735f51c735cebd530e409514c
parent f0041d2922cd2f895ba8f2c18bdb82ea250727a3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 18:59:42 -0400
Merge r30/frame-scan: a stream's frames sampled, deduplicated and read (poker first: stack, pot, dealer log, header, breaks), spoken numbers from the transcript, a derived timeline sidecar, a video-page panel and a umtool supercut draft
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
62 files changed, 4655 insertions(+), 31 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -151,6 +151,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"?} -> {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"?} -> {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"?: \["<article>"\], "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)} -> {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/<run>/ (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"?} -> {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.<profile>.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}'` |
| `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"?} -> {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 <series>-<date> over the window since the last edition ("<topic> · week of <date>"); 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"} -> {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/SETTINGS.md b/SETTINGS.md
@@ -988,6 +988,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `cut` | object — see below | The cut task's limits (below). |
| `verdicts` | object — see below | The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`. |
| `triage` | object — see below | Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below). |
+| `frames` | object — see below | The frame scan (`pnpm ops frame-scan`): the vision model each route reads a saved stream's frames on, a scan's spend cap and its sampling step (below). |
#### `generation.routes`
@@ -1005,6 +1006,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `threads` | `"local"` | A media draft: the cut's threads and each clip's thread. |
| `youtube` | `"local"` | A media draft: the YouTube title and description. |
| `social` | `"local"` | A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code. |
+| `frames` | `"api"` | A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model. |
| `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. |
#### `generation.models`
@@ -1082,6 +1084,15 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `maxEscalationsPerDay` | `3` | The most escalations (tier 2 sweeps) a day (UTC) across every schedule. Past it a tick is held by the cap — a Your call card — with its flags kept. 0 = no cap. |
| `maxCandidates` | `40` | The most candidates one triage judges; the rest stay new for the next tick. |
+#### `generation.frames`
+
+| Key | Default | Description |
+|---|---|---|
+| `apiModel` | `"claude-haiku-4-5"` | The Claude model a scan on the `api` route reads frames with (it must take images). Haiku: about a cent a hundred frames. |
+| `localModel` | `"qwen2.5vl:7b"` | The ollama vision model a scan on the `local` route reads frames with (one frame an ask, under the 8k prompt cap; through the GPU arbiter on `draft:local`). |
+| `maxUsd` | `5` | A scan's API cap when the job names none (at most `caps.max`): the scan stops before an ask that would pass it, and keeps what it read. |
+| `everySeconds` | `10` | Seconds between two sampled frames when the job names none (1 to 600). |
+
Default:
```json
@@ -1100,7 +1111,8 @@ Default:
"threads": "local",
"youtube": "local",
"social": "local",
- "verdicts": "local"
+ "verdicts": "local",
+ "frames": "api"
},
"models": {
"api": "claude-sonnet-5-5",
@@ -1153,6 +1165,12 @@ Default:
"weak": 3,
"maxEscalationsPerDay": 3,
"maxCandidates": 40
+ },
+ "frames": {
+ "apiModel": "claude-haiku-4-5",
+ "localModel": "qwen2.5vl:7b",
+ "maxUsd": 5,
+ "everySeconds": 10
}
}
```
diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts
@@ -0,0 +1,303 @@
+// `frame-scan` — a saved stream's frames read for a profile's progress
+// (release 30, lane P): `pnpm ops frame-scan` → POST /api/ops/frame-scan →
+// here, and the video page's Scan button.
+//
+// slug, id the video (its source container must be in the saved-video store)
+// profile what the frames are read for (default "poker")
+// everySeconds the sampling step (default settings.generation.frames.everySeconds)
+// from, to the range in source seconds (default the whole video)
+// maxFrames at most this many frames (default 5000)
+// model the vision model (default the `frames` route's)
+// maxUsd the run's API cap (default frames.maxUsd, at most caps.max)
+// hero the hero's screen name, a hint to the model
+// framesPerAsk frames per ask (default the profile's: 4 on the API, 1 local)
+// crop [x, y, w, h], fractions: the part of the picture read (the
+// poker client, not the webcam beside it); also what is hashed
+// 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)
+//
+// 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
+// call through the GPU arbiter and the model unloaded at the end, however it
+// ends (as the verdict bench). `needsMedia`: it opens the saved container and
+// writes the cache on the media side, so a channel whose media is unreachable
+// is refused.
+//
+// An API scan is refused past the day's cap, and its spend is appended to the
+// usage ledger (task `frame-scan`, no article). The log ends
+// `@@frame-scan {json}` with the run's counts, spend, and events.
+
+import path from "node:path";
+import { readFile } from "node:fs/promises";
+import { getSettings } from "../lib/settings";
+import type { Paths } from "../lib/paths";
+import type { GenerationSettings } from "../lib/generationSettings";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { DRAFT_LOCAL_QUEUE, FRAME_SCAN_QUEUE } from "../lib/queueKeys";
+import { providerOf, unloadOllama } from "../lib/llm";
+import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments";
+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 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 class FrameScanInputError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "FrameScanInputError";
+ }
+}
+
+export type FrameScanBody = {
+ slug: string;
+ id: string;
+ profile: string;
+ everySeconds?: number;
+ from?: number;
+ to?: number;
+ maxFrames?: number;
+ model?: string;
+ maxUsd?: number;
+ hero?: string;
+ framesPerAsk?: number;
+ crop?: Crop;
+ fresh?: boolean;
+ evict?: boolean;
+};
+
+const fail = (msg: string): never => {
+ throw new FrameScanInputError(msg);
+};
+const numIn = (v: unknown, lo: number, hi: number) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
+
+// The body, judged without touching the disk.
+export function parseFrameScanBody(b: Record<string, unknown>): FrameScanBody {
+ if (!isSafeChannelSegment(b.slug)) fail(`"slug" is a channel's slug`);
+ if (!isSafeIdSegment(b.id)) fail(`"id" is a video's id`);
+ const profile = b.profile ?? "poker";
+ if (!isFrameProfile(profile)) fail(`"profile" is one of ${FRAME_PROFILE_IDS.join(", ")}`);
+ const out: FrameScanBody = { slug: b.slug as string, id: b.id as string, profile: profile as string };
+ if (b.everySeconds !== undefined) {
+ if (!numIn(b.everySeconds, 1, 600)) fail(`"everySeconds" is a number of seconds, 1 to 600`);
+ out.everySeconds = b.everySeconds as number;
+ }
+ for (const k of ["from", "to"] as const) {
+ if (b[k] === undefined) continue;
+ if (!numIn(b[k], 0, 1e7)) fail(`"${k}" is a number of seconds into the video`);
+ out[k] = b[k] as number;
+ }
+ if (out.from !== undefined && out.to !== undefined && !(out.to > out.from)) fail(`"to" must be after "from"`);
+ if (b.maxFrames !== undefined) {
+ if (!(Number.isInteger(b.maxFrames) && numIn(b.maxFrames, 1, 100_000))) fail(`"maxFrames" is a whole number, 1 to 100000`);
+ out.maxFrames = b.maxFrames as number;
+ }
+ if (b.model !== undefined) {
+ if (typeof b.model !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(b.model.trim())) fail(`"model" is a model's name`);
+ out.model = (b.model as string).trim();
+ }
+ if (b.maxUsd !== undefined) {
+ if (!numIn(b.maxUsd, 0.01, 1000)) fail(`"maxUsd" is a number of dollars`);
+ out.maxUsd = b.maxUsd as number;
+ }
+ if (b.hero !== undefined) {
+ if (typeof b.hero !== "string" || !b.hero.trim() || b.hero.length > 60) fail(`"hero" is the hero's screen name (at most 60 characters)`);
+ out.hero = (b.hero as string).trim();
+ }
+ if (b.framesPerAsk !== undefined) {
+ if (!(Number.isInteger(b.framesPerAsk) && numIn(b.framesPerAsk, 1, 8))) fail(`"framesPerAsk" is a whole number, 1 to 8`);
+ out.framesPerAsk = b.framesPerAsk as number;
+ }
+ if (b.crop !== undefined) {
+ if (!isCrop(b.crop)) fail(`"crop" is [x, y, w, h] as fractions of the picture (each 0 to 1, inside it, at least 0.05 wide and high)`);
+ out.crop = b.crop as Crop;
+ }
+ if (b.fresh !== undefined) {
+ if (typeof b.fresh !== "boolean") fail(`"fresh" is true or false`);
+ out.fresh = b.fresh as boolean;
+ }
+ if (b.evict !== undefined) {
+ if (typeof b.evict !== "boolean") fail(`"evict" is true or false`);
+ out.evict = b.evict as boolean;
+ }
+ return out;
+}
+
+/** The model a scan runs on: the asked one, else the `frames` route's. */
+export function frameScanModel(gen: GenerationSettings, asked?: string): string {
+ if (asked) return asked;
+ const route = gen.routes.frames;
+ if (route === "code") fail(`frames is routed to Claude Code (settings.generation.routes.frames) — name a "model", or route frames to api or local`);
+ return route === "api" ? gen.frames.apiModel : gen.frames.localModel;
+}
+
+/** The run's API cap: the asked one within caps.max, else frames.maxUsd (at most caps.max). */
+export function frameScanCap(gen: GenerationSettings, asked?: number): number {
+ if (asked !== undefined) {
+ if (asked > gen.caps.max) fail(`maxUsd $${asked} is over the settings' max of $${gen.caps.max} (settings.generation.caps.max)`);
+ return asked;
+ }
+ return Math.min(gen.frames.maxUsd, gen.caps.max);
+}
+
+export type FrameScanDepsIn = {
+ paths: Paths;
+ settings?: () => { generation: GenerationSettings };
+ now?: () => Date;
+};
+
+export type FrameScanEnqueued =
+ | { result: StreamActionResult; model: string; queueKey: string }
+ | { result: StreamActionResult & { ok: false } }
+ | { evicted: { dir: string; removed: boolean; bytes: number } };
+
+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;
+ return doc.cues
+ .filter((c): c is Cue => !!c && typeof c === "object" && typeof (c as Cue).start === "number" && typeof (c as Cue).end === "number" && typeof (c as Cue).text === "string")
+ .sort((a, b) => a.start - b.start);
+ } catch {
+ return undefined;
+ }
+}
+
+export async function enqueueFrameScan(raw: Record<string, unknown>, deps: FrameScanDepsIn): Promise<FrameScanEnqueued> {
+ const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ let body: FrameScanBody;
+ try {
+ body = parseFrameScanBody(raw);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const paths = deps.paths;
+ const videoDir = path.join(paths.channelsDir, body.slug, "data", body.id);
+ const cacheDir = await frameCacheDirOf(paths.channelsDir, body.slug, body.id, body.profile);
+ if (body.evict) {
+ const bytes = await frameCacheBytes(cacheDir);
+ return { evicted: { dir: cacheDir, removed: await removeFrameCache(cacheDir), bytes } };
+ }
+ const source = await resolveSavedVideo(videoDir);
+ if (!source) {
+ return refuse(
+ `${body.slug}/${body.id} has no saved video to read frames from — save it first: ` +
+ `pnpm ops persist-videos --json '{"items":[{"slug":"${body.slug}","id":"${body.id}"}],"format":"original"}'`,
+ );
+ }
+ const gen = (deps.settings ?? getSettings)().generation;
+ let model: string;
+ let maxUsd: number;
+ try {
+ model = frameScanModel(gen, body.model);
+ maxUsd = frameScanCap(gen, body.maxUsd);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const route = providerOf(model);
+ const capRefusal = async () => (route === "api" ? dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily) : null);
+ const early = await capRefusal();
+ if (early) return refuse(early);
+ const queueKey = route === "local" ? DRAFT_LOCAL_QUEUE : FRAME_SCAN_QUEUE;
+ const result = await runManagedFunction({
+ kind: FRAME_SCAN_JOB_KIND,
+ queueKey,
+ paths,
+ channelSlug: body.slug,
+ videoId: body.id,
+ fn: async (onLog, signal, setProgress, ctx) => {
+ const g = (deps.settings ?? getSettings)().generation;
+ // Again at the job's turn: jobs ahead in the queue may have spent the day.
+ const late = await capRefusal();
+ if (late) throw new Error(late);
+ onLog(`frame scan ${body.slug}/${body.id} (${body.profile}) on ${model}${route === "api" ? ` (API cap $${maxUsd})` : ""}`);
+ const sidecar = frameScanSidecar(body.profile);
+ let out: FrameScanOutcome | null = null;
+ try {
+ out = await runFrameScan(
+ {
+ profile: body.profile,
+ source,
+ cacheDir,
+ everySeconds: body.everySeconds ?? g.frames.everySeconds,
+ ...(body.from !== undefined ? { from: body.from } : {}),
+ ...(body.to !== undefined ? { to: body.to } : {}),
+ maxFrames: body.maxFrames ?? DEFAULT_MAX_FRAMES,
+ model,
+ llm: llmConfigOf(g, paths, route === "local" ? { onLog, signal } : undefined),
+ maxUsd: route === "api" ? maxUsd : Number.POSITIVE_INFINITY,
+ ...(body.hero ? { hints: { hero: body.hero } } : {}),
+ ...(body.framesPerAsk ? { framesPerAsk: body.framesPerAsk } : {}),
+ ...(body.crop ? { crop: body.crop } : {}),
+ ...(body.fresh ? { fresh: true } : {}),
+ cues: await loadCues(videoDir),
+ jobId: ctx.jobId,
+ signal,
+ onLog,
+ onProgress: (p) => setProgress({ metric: "frames", initial: 0, target: p.total, current: p.current }),
+ ...(deps.now ? { now: deps.now } : {}),
+ },
+ { load: () => sidecar.load(videoDir), write: (r) => sidecar.write(videoDir, r) },
+ );
+ const r = out.record;
+ onLog(
+ `${FRAME_SCAN_RESULT_MARKER}${JSON.stringify({
+ slug: body.slug,
+ id: body.id,
+ profile: body.profile,
+ file: sidecar.filename,
+ frames: out.run.frames,
+ kept: r.sampling.kept,
+ read: out.run.read,
+ failed: out.run.failed,
+ readings: r.readings.length,
+ spentUsd: out.run.costUsd,
+ totalUsd: r.costUsd,
+ events: r.derived.events.length,
+ tournaments: r.derived.tournaments.length,
+ flags: r.derived.flags.length,
+ ...(out.run.stopped ? { stopped: out.run.stopped } : {}),
+ })}`,
+ );
+ if (out.run.stopped === "cancelled" || signal.aborted) throw new Error("cancelled");
+ } finally {
+ if (route === "local") {
+ await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ if (out && route === "api") {
+ const at = deps.now?.() ?? new Date();
+ const rows: GenerationUsageRow[] = Object.entries(out.spent.byModel)
+ .filter(([, t]) => t.calls > 0)
+ .map(([m, t]) => ({
+ at: at.toISOString(),
+ day: utcDay(at),
+ jobId: ctx.jobId,
+ article: "",
+ iteration: 0,
+ task: FRAME_SCAN_JOB_KIND,
+ model: m,
+ inputTokens: t.input,
+ outputTokens: t.output,
+ cacheReadTokens: t.cacheRead,
+ cacheWriteTokens: t.cacheWrite,
+ usd: Math.round(t.usd * 10_000) / 10_000,
+ }));
+ await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ }
+ },
+ });
+ if (!result.ok) return { result };
+ return { result, model, queueKey };
+}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -190,7 +190,9 @@ export function isKnownApiModel(model: string): boolean {
return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`));
}
-const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS, REFRESH_TASK, TRIAGE_DRAFT_TASK];
+// `frames` is routed by settings.generation like every task, but it is the
+// frame scan's (`pnpm ops frame-scan`), never a report-draft.
+const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS.filter((t) => t !== "frames"), REFRESH_TASK, TRIAGE_DRAFT_TASK];
const ymd = /^\d{4}-\d{2}-\d{2}$/;
function fail(msg: string): never {
@@ -700,7 +702,8 @@ async function runReportDraft(
case "refresh":
case "triage":
case "verdicts":
- // A refresh, a triage and verdict proposals are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts), never this one.
+ case "frames":
+ // A refresh, a triage, verdict proposals and a frame scan are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts), never this one.
throw new Error(`a ${body.task} runs as its own job`);
case "sweep":
input =
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -979,6 +979,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
replayable: false,
queueKeyStrategy: "custom",
},
+ // The frame scan (release 30, lane P): a saved stream sampled into frames
+ // and the kept ones read by a vision model through a profile (poker), into
+ // `frame-scan.<profile>.json` beside the video — `pnpm ops frame-scan`, the
+ // video page's Scan button. On `frames` (API) or `draft:local` (a local
+ // vision model, through the GPU arbiter). OPENS THE SAVED CONTAINER and
+ // writes the frame cache on the channel's media side: needsMedia. Not
+ // replayable: the same body again resumes it (read frames are skipped).
+ "frame-scan": {
+ kind: "frame-scan",
+ label: "Frame scan",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ },
"tts-file": {
kind: "tts-file",
label: "Text to speech",
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -33,7 +33,10 @@ export type JobProgressMetric =
// re-count; the runner always sets `current`.
| "turns"
| "cards"
- | "entries";
+ | "entries"
+ // A frame scan (controller/frameScan.ts, release 30): frames sampled, then
+ // frames read. The runner always sets `current`.
+ | "frames";
export type JobProgress = {
metric: JobProgressMetric;
diff --git a/common/lib/frameScan-server.ts b/common/lib/frameScan-server.ts
@@ -0,0 +1,103 @@
+// The frame scan's per-video files (release 30, lane P).
+//
+// channels/<slug>/data/<id>/frame-scan.<profile>.json the timeline sidecar
+// (readings, spoken numbers, the derived series/events/segments) — TEXT,
+// on the corpus disk with every other sidecar. Never published: nothing
+// in the export build reads it.
+// channels/<slug>/media/<id>/frames/<profile>/ the frame CACHE —
+// JPEGs and their index, on the channel's MEDIA side (the media tier's
+// directory, which may be a link to another drive), so a 4-hour stream's
+// frames never land on /home when the channel's media lives elsewhere.
+// A classic channel (no `media/`) keeps them in `data/<id>/frames/`.
+// Evictable at any time (`frame-scan {evict: true}`): a re-run decodes
+// them again, and readings already in the sidecar are not asked again.
+// Deleting the video removes `media/<id>/` and so the cache with it.
+
+import path from "node:path";
+import { lstat } from "node:fs/promises";
+import { sidecar, sidecarField, type Sidecar } from "./sidecar-server";
+import { FRAME_PROFILE_IDS } from "./frames/profiles";
+import { FRAME_SCAN_FORMAT, type Derived, type SpokenReading } from "./frames/types";
+
+export const frameScanFilename = (profile: string) => `frame-scan.${profile}.json`;
+
+export type FrameScanRun = {
+ at: string;
+ jobId?: string;
+ model: string;
+ route: "api" | "local";
+ frames: number;
+ read: number;
+ failed: number;
+ costUsd: number;
+ stopped?: "cap" | "cancelled" | "errors" | "maxFrames";
+};
+
+export type FrameScanRecord = {
+ format: typeof FRAME_SCAN_FORMAT;
+ version: 1;
+ profile: string;
+ source: { savedVideo: string; durationSeconds: number | null };
+ sampling: { everySeconds: number; from: number; to: number; width: number; keyframesOnly: boolean; crop?: [number, number, number, number]; frames: number; kept: number; skippedDuplicates: number };
+ model: { route: "api" | "local"; model: string; promptVersion: number };
+ // What the model was told (the hero's screen name), kept for the next run and the derivation.
+ hints?: { hero?: string };
+ costUsd: number;
+ runs: FrameScanRun[];
+ readings: ({ t: number; phase: string } & Record<string, unknown>)[];
+ // Frames not read because they duplicate a read one: [t, the read frame's t].
+ duplicates: [number, number][];
+ spoken: SpokenReading[];
+ derived: Derived;
+ updatedAt: string;
+};
+
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
+
+export function coerceFrameScan(v: unknown): FrameScanRecord | null {
+ if (!isObj(v) || v.format !== FRAME_SCAN_FORMAT || typeof v.profile !== "string") return null;
+ if (!Array.isArray(v.readings) || !isObj(v.derived) || !isObj(v.sampling) || !isObj(v.source)) return null;
+ const d = v.derived as Record<string, unknown>;
+ if (!Array.isArray(d.tournaments) || !Array.isArray(d.events) || !Array.isArray(d.segments)) return null;
+ return {
+ ...(v as unknown as FrameScanRecord),
+ runs: Array.isArray(v.runs) ? (v.runs as FrameScanRun[]) : [],
+ spoken: Array.isArray(v.spoken) ? (v.spoken as SpokenReading[]) : [],
+ duplicates: Array.isArray(v.duplicates) ? (v.duplicates as [number, number][]).filter((p) => Array.isArray(p) && p.length === 2) : [],
+ derived: { ...(d as unknown as Derived), flags: Array.isArray(d.flags) ? (d.flags as Derived["flags"]) : [], misreads: Array.isArray(d.misreads) ? (d.misreads as Derived["misreads"]) : [] },
+ costUsd: typeof v.costUsd === "number" ? v.costUsd : 0,
+ };
+}
+
+// One declaration per profile, at load (sidecar()'s naming guard runs then).
+const SIDECARS: Record<string, Sidecar<FrameScanRecord>> = Object.fromEntries(
+ FRAME_PROFILE_IDS.map((p) => [p, sidecar(frameScanFilename(p), sidecarField(coerceFrameScan), { indent: 0 })]),
+);
+
+export function frameScanSidecar(profile: string): Sidecar<FrameScanRecord> {
+ const s = SIDECARS[profile];
+ if (!s) throw new Error(`"${profile}" is not a frame-scan profile`);
+ return s;
+}
+
+export const loadFrameScan = (videoDir: string, profile: string) => frameScanSidecar(profile).load(videoDir);
+
+/** Every profile's sidecar this video has. */
+export async function loadFrameScans(videoDir: string): Promise<FrameScanRecord[]> {
+ const out: FrameScanRecord[] = [];
+ for (const p of FRAME_PROFILE_IDS) {
+ const r = await loadFrameScan(videoDir, p);
+ if (r) out.push(r);
+ }
+ return out;
+}
+
+/** Where a video's frame cache for a profile lives (see the header). */
+export async function frameCacheDirOf(channelsDir: string, slug: string, id: string, profile: string): Promise<string> {
+ const media = path.join(channelsDir, slug, "media");
+ const tiered = await lstat(media).then(
+ (l) => l.isDirectory() || l.isSymbolicLink(),
+ () => false,
+ );
+ return tiered ? path.join(media, id, "frames", profile) : path.join(channelsDir, slug, "data", id, "frames", profile);
+}
diff --git a/common/lib/frames/dhash.test.ts b/common/lib/frames/dhash.test.ts
@@ -0,0 +1,40 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { dHash, duplicatesOf, hamming, hashesOf, THUMB_BYTES, THUMB_H, THUMB_W } from "./dhash";
+
+const flat = (v: number) => new Uint8Array(THUMB_BYTES).fill(v);
+const ramp = (dir: 1 | -1) => {
+ const a = new Uint8Array(THUMB_BYTES);
+ for (let r = 0; r < THUMB_H; r++) for (let c = 0; c < THUMB_W; c++) a[r * THUMB_W + c] = dir === 1 ? c * 10 : 250 - c * 10;
+ return a;
+};
+
+test("dHash: brightness-proof, and a picture that moves changes it", () => {
+ assert.equal(dHash(flat(10)), dHash(flat(200)));
+ assert.equal(dHash(ramp(-1)).length, ((THUMB_W - 1) * THUMB_H) / 4);
+ assert.equal(hamming(dHash(ramp(-1)), dHash(ramp(1))), (THUMB_W - 1) * THUMB_H);
+ assert.equal(hamming(dHash(flat(1)), dHash(flat(1))), 0);
+ assert.throws(() => dHash(new Uint8Array(3)));
+});
+
+test("hamming: Infinity when two hashes cannot be compared", () => {
+ assert.equal(hamming("ab", "abc"), Infinity);
+ assert.equal(hamming("", ""), Infinity);
+ assert.equal(hamming("f0", "0f"), 8);
+});
+
+test("hashesOf: one hash per thumbnail in a rawvideo stream", () => {
+ const raw = Buffer.concat([Buffer.from(flat(5)), Buffer.from(ramp(-1)), Buffer.alloc(7)]);
+ const hs = hashesOf(raw);
+ assert.equal(hs.length, 2);
+ assert.equal(hs[1], dHash(ramp(-1)));
+});
+
+test("duplicatesOf: a duplicate of the last READ frame is skipped; a run is read again every N", () => {
+ const A = "0000";
+ const B = "ffff";
+ const out = duplicatesOf([A, A, A, B, B, A, A, A, A, A], { maxBits: 0, rereadEvery: 3 });
+ assert.deepEqual(out, [null, 0, 0, null, 3, null, 5, 5, null, 8]);
+ // Near enough under maxBits.
+ assert.deepEqual(duplicatesOf(["0000", "0001", "0003"], { maxBits: 1, rereadEvery: 0 }), [null, 0, null]);
+});
diff --git a/common/lib/frames/dhash.ts b/common/lib/frames/dhash.ts
@@ -0,0 +1,70 @@
+// A difference hash of a frame's tiny grey thumbnail (release 30, lane P):
+// the cheap test of "the same picture as the last one" that lets a static
+// lobby or break screen cost one read. Pure.
+//
+// The thumbnail is (w+1)×h grey bytes, row-major, as ffmpeg writes
+// `scale=<w+1>:<h>,format=gray` rawvideo: each bit says whether a pixel is
+// brighter than its right-hand neighbour, so the hash survives a change of
+// overall brightness and of compression noise, and a picture that moves does
+// not.
+
+export const THUMB_W = 17;
+export const THUMB_H = 16;
+export const THUMB_BYTES = THUMB_W * THUMB_H;
+
+/** The dHash (hex, `(w-1)·h` bits) of one `w`×`h` grey thumbnail. */
+export function dHash(px: Uint8Array | Buffer, w = THUMB_W, h = THUMB_H): string {
+ if (px.length < w * h) throw new Error(`a ${w}×${h} thumbnail is ${w * h} bytes, not ${px.length}`);
+ const bits: number[] = [];
+ for (let r = 0; r < h; r++) for (let c = 0; c < w - 1; c++) bits.push(px[r * w + c] > px[r * w + c + 1] ? 1 : 0);
+ while (bits.length % 4) bits.push(0);
+ let hex = "";
+ for (let i = 0; i < bits.length; i += 4) hex += ((bits[i] << 3) | (bits[i + 1] << 2) | (bits[i + 2] << 1) | bits[i + 3]).toString(16);
+ return hex;
+}
+
+const POP = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
+
+/** Bits two hashes of one length differ by; Infinity when they cannot be compared. */
+export function hamming(a: string, b: string): number {
+ if (!a || a.length !== b.length) return Infinity;
+ let d = 0;
+ for (let i = 0; i < a.length; i++) {
+ const x = parseInt(a[i], 16) ^ parseInt(b[i], 16);
+ if (Number.isNaN(x)) return Infinity;
+ d += POP[x];
+ }
+ return d;
+}
+
+/** Split ffmpeg's rawvideo stream of thumbnails into one hash per frame. */
+export function hashesOf(raw: Buffer | Uint8Array, w = THUMB_W, h = THUMB_H): string[] {
+ const n = Math.floor(raw.length / (w * h));
+ const out: string[] = [];
+ for (let i = 0; i < n; i++) out.push(dHash(raw.subarray(i * w * h, (i + 1) * w * h), w, h));
+ return out;
+}
+
+/**
+ * Which frames a model must read: a frame is a duplicate of the last frame
+ * READ when their hashes differ by at most `maxBits`, and a duplicate run is
+ * read again every `rereadEvery` frames. Answers, per frame in order, null (read
+ * it) or the index of the frame it duplicates.
+ */
+export function duplicatesOf(hashes: readonly string[], o: { maxBits: number; rereadEvery: number }): (number | null)[] {
+ const out: (number | null)[] = [];
+ let lastRead = -1;
+ let run = 0;
+ for (let i = 0; i < hashes.length; i++) {
+ const dup = lastRead >= 0 && hamming(hashes[i], hashes[lastRead]) <= o.maxBits;
+ if (dup && (o.rereadEvery <= 0 || run + 1 < o.rereadEvery)) {
+ out.push(lastRead);
+ run++;
+ } else {
+ out.push(null);
+ lastRead = i;
+ run = 0;
+ }
+ }
+ return out;
+}
diff --git a/common/lib/frames/numberWords.test.ts b/common/lib/frames/numberWords.test.ts
@@ -0,0 +1,39 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { normalizeNumbers, numbersIn } from "./numberWords";
+
+const cases: [string, string][] = [
+ ["eighty five players left", "85 players left"],
+ ["fifteen players left", "15 players left"],
+ ["$2,750 buy in", "$2750 buy in"],
+ ["an opponent at five hundred sixty seven thousand chips", "an opponent at 567000 chips"],
+ ["the average stack is three hundred seventy three thousand, I have two hundred thirty three", "the average stack is 373000, I have 233"],
+ ["a double up would put me in the top twenty", "a double up would put me in the top 20"],
+ ["first place five hundred bucks", "first place 500 bucks"],
+ ["blinds are five ten", "blinds are 5 10"],
+ ["one point five million", "1500000"],
+ ["233k and 10M", "233000 and 10000000"],
+ ["two million three hundred thousand", "2300000"],
+ ["a hundred and five", "105"],
+ ["eighty-five", "85"],
+ ["twenty five hundred", "2500"],
+ ["I have no one to call", "I have no one to call"],
+ ["level 14, blinds 1,500/3,000 ante 3,000", "level 14, blinds 1500/3000 ante 3000"],
+ ["thousand thousand", "1000 1000"],
+ ["a cat", "a cat"],
+ ["the average is four hundred twelve K and I have", "the average is 412000 and I have"],
+ ["sixty k", "60000"],
+ ["a k of spades", "a k of spades"],
+ ["I climbed to seventy second", "I climbed to 72"],
+ ["first place gets the most, third place less", "first place gets the most, third place less"],
+ ["the fifteenth hand", "the 15 hand"],
+];
+
+test("normalizeNumbers: spoken and written numbers become plain digits, the rest is kept", () => {
+ for (const [input, want] of cases) assert.equal(normalizeNumbers(input), want, input);
+});
+
+test("numbersIn: every number, in order", () => {
+ assert.deepEqual(numbersIn("blinds two hundred four hundred, eighty five left"), [200, 400, 85]);
+ assert.deepEqual(numbersIn("nothing here"), []);
+});
diff --git a/common/lib/frames/numberWords.ts b/common/lib/frames/numberWords.ts
@@ -0,0 +1,272 @@
+// Spoken numbers as digits (release 30, lane P). An ASR transcript writes a
+// number the way it was said — "eighty five players left", "three hundred
+// seventy three thousand", "$2,750 buy in", "233k" — and the frame scan's
+// spoken signal (`spoken.ts`) reads stats out of that text with plain
+// patterns. So the text is normalized first: every run of number words (and
+// every digit group with commas, a decimal point or a `k`/`m` suffix) becomes
+// one plain number, and the patterns only ever see digits.
+//
+// Rule-based and pure. What it does NOT do: ordinals ("third"), fractions
+// ("a half"), years read as pairs ("twenty twenty five" is 20 then 25), and
+// "grand". A run that is not a well-formed number splits where the next word
+// cannot continue it ("five ten" is 5 then 10, as blinds are said).
+
+const UNITS: Record<string, number> = {
+ zero: 0, oh: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9,
+ ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17,
+ eighteen: 18, nineteen: 19,
+};
+const TENS: Record<string, number> = {
+ twenty: 20, thirty: 30, forty: 40, fourty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90,
+};
+const SCALES: Record<string, number> = { thousand: 1_000, million: 1_000_000, billion: 1_000_000_000 };
+// Ordinals, read as their number: a unit ordinal only after a tens word
+// ("eighty first" → 81; "first place" stays words), a teen or tens ordinal
+// on its own ("thirteenth", "twentieth").
+const UNIT_ORDINALS: Record<string, number> = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5, sixth: 6, seventh: 7, eighth: 8, ninth: 9 };
+const OWN_ORDINALS: Record<string, number> = {
+ tenth: 10, eleventh: 11, twelfth: 12, thirteenth: 13, fourteenth: 14, fifteenth: 15, sixteenth: 16, seventeenth: 17,
+ eighteenth: 18, nineteenth: 19, twentieth: 20, thirtieth: 30, fortieth: 40, fiftieth: 50, sixtieth: 60, seventieth: 70,
+ eightieth: 80, ninetieth: 90,
+};
+
+// A digit token: "2,750", "1.5", "233k", "$5", "10m". The `$` stays outside.
+const DIGITS = /^(\d{1,3}(?:,\d{3})+|\d+)(?:\.(\d+))?(k|m|mil|bn)?$/i;
+
+type Tok = { word: string; raw: string };
+
+function digitValue(w: string): number | null {
+ const m = DIGITS.exec(w);
+ if (!m) return null;
+ let v = Number(m[1].replace(/,/g, "") + (m[2] ? `.${m[2]}` : ""));
+ const suf = (m[3] ?? "").toLowerCase();
+ if (suf === "k") v *= 1_000;
+ else if (suf === "m" || suf === "mil") v *= 1_000_000;
+ else if (suf === "bn") v *= 1_000_000_000;
+ return Number.isFinite(v) ? v : null;
+}
+
+// What kind of number word a token is, or null.
+function kindOf(w: string): "unit" | "tens" | "hundred" | "scale" | "digits" | "ordinal" | null {
+ if (w in UNITS) return "unit";
+ if (w in OWN_ORDINALS) return "ordinal";
+ if (w in TENS) return "tens";
+ if (w === "hundred") return "hundred";
+ if (w in SCALES) return "scale";
+ if (digitValue(w) !== null) return "digits";
+ return null;
+}
+
+// One number from a run of tokens that form it (the caller decides the run).
+class Acc {
+ total = 0;
+ current = 0;
+ decimal: string | null = null;
+ last: "unit" | "tens" | "hundred" | "scale" | "digits" | "a" | "ordinal" | null = null;
+ any = false;
+ // The count before the last "hundred" ("fifteen hundred" → 15).
+ hundredsCount = 0;
+
+ value(): number {
+ return this.total + this.current;
+ }
+
+ // Whether `w` (of kind `k`) continues the number so far.
+ accepts(k: ReturnType<typeof kindOf> | "a" | "point" | "unitOrdinal", w: string): boolean {
+ if (!this.any) return k !== "point" && k !== "unitOrdinal";
+ // An ordinal ends a number.
+ if (this.last === "ordinal") return false;
+ if (k === "unitOrdinal") return this.last === "tens";
+ if (k === "ordinal") return false;
+ if (this.decimal !== null) return k === "unit" && UNITS[w] <= 9 ? true : k === "scale";
+ switch (k) {
+ case "unit":
+ // "twenty five" and "a hundred five" continue; "five ten" does not.
+ if (this.last === "tens") return UNITS[w] <= 9;
+ return this.last === "hundred" || this.last === "scale";
+ case "tens":
+ return this.last === "hundred" || this.last === "scale";
+ case "hundred":
+ return (this.last === "unit" || this.last === "a") && this.current < 100 && this.current > 0;
+ case "scale":
+ return this.last !== "scale" && this.value() > 0 && (this.lastScale() === 0 || SCALES[w] < this.lastScale());
+ case "digits":
+ return false;
+ case "point":
+ return this.last === "unit" || this.last === "tens" || this.last === "digits";
+ case "a":
+ return false;
+ default:
+ return false;
+ }
+ }
+
+ private scales: number[] = [];
+ private lastScale(): number {
+ // A scale may follow only a smaller one ("two million three hundred
+ // thousand"); "thousand thousand" is two numbers.
+ return this.scales.length ? Math.min(...this.scales) : 0;
+ }
+
+ add(k: NonNullable<ReturnType<typeof kindOf>> | "a" | "point" | "unitOrdinal", w: string): void {
+ this.any = true;
+ if (k === "unitOrdinal") {
+ this.current += UNIT_ORDINALS[w];
+ this.last = "ordinal";
+ return;
+ }
+ if (k === "ordinal") {
+ this.current += OWN_ORDINALS[w];
+ this.last = "ordinal";
+ return;
+ }
+ if (k === "point") {
+ this.decimal = "";
+ this.last = "unit";
+ return;
+ }
+ if (this.decimal !== null && k === "unit") {
+ this.decimal += String(UNITS[w]);
+ this.current = Math.trunc(this.current) + Number(`0.${this.decimal}`);
+ return;
+ }
+ switch (k) {
+ case "a":
+ this.current = 1;
+ break;
+ case "unit":
+ this.current += UNITS[w];
+ break;
+ case "tens":
+ this.current += TENS[w];
+ break;
+ case "hundred":
+ this.hundredsCount = this.current || 1;
+ this.current = (this.current || 1) * 100;
+ break;
+ case "scale":
+ this.total += (this.current || 1) * SCALES[w];
+ this.current = 0;
+ this.scales.push(SCALES[w]);
+ this.decimal = null;
+ break;
+ case "digits":
+ this.current = digitValue(w) ?? 0;
+ break;
+ }
+ this.last = k;
+ }
+}
+
+// "no one", "the one", "this one": a pronoun, not a count.
+const NOT_A_NUMBER_BEFORE_ONE = new Set(["no", "any", "some", "every", "the", "this", "that", "which", "each", "another", "last", "next", "only"]);
+
+function tokenize(text: string): Tok[] {
+ // Words, digit groups and the punctuation between them, every piece kept so
+ // the text can be put back together around the numbers.
+ return (text.match(/\$|\d[\d,]*(?:\.\d+)?(?:k|m|mil|bn)?\b|[A-Za-z]+(?:'[A-Za-z]+)?|[^A-Za-z\d$]+/gi) ?? []).map((raw) => ({
+ raw,
+ word: raw.toLowerCase(),
+ }));
+}
+
+const fmt = (v: number) => (Number.isInteger(v) ? String(v) : String(Math.round(v * 1000) / 1000));
+
+// The words of the number run that would follow token `n` (its own word first).
+function runAhead(toks: readonly Tok[], n: number): string[] {
+ const out: string[] = [toks[n].word];
+ for (let k = n + 1; k + 1 < toks.length && /^[\s-]+$/.test(toks[k].raw); k += 2) {
+ const w = toks[k + 1].word;
+ if (!kindOf(w) && w !== "and") break;
+ out.push(w);
+ }
+ return out;
+}
+
+// Where two numbers said back to back would otherwise run together: "two
+// hundred four hundred" is 200 then 400 (not 204, 100), and "fifteen hundred
+// three thousand" is 1500 then 3000 (blinds, said the colloquial way: a
+// hundreds count of ten or more is a whole number, never the start of a
+// larger one).
+function splitsBefore(acc: Acc, k: string, toks: readonly Tok[], n: number): boolean {
+ if (acc.last !== "hundred" || (k !== "unit" && k !== "tens")) return false;
+ const ahead = runAhead(toks, n);
+ const next = ahead.findIndex((w, i) => i > 0 && (w === "hundred" || w in SCALES));
+ if (next < 0) return false;
+ if (ahead[next] === "hundred") return true;
+ return acc.hundredsCount >= 10;
+}
+
+/**
+ * The text with every spoken or written number as plain digits: "eighty five
+ * players left" → "85 players left", "$2,750" → "$2750", "two hundred thirty
+ * three thousand" → "233000", "1.5 million" → "1500000". Hyphens inside a
+ * number ("eighty-five") join it. Everything else is kept as it was.
+ */
+export function normalizeNumbers(text: string): string {
+ const toks = tokenize(text);
+ const out: string[] = [];
+ let i = 0;
+ while (i < toks.length) {
+ const t = toks[i];
+ const k = kindOf(t.word);
+ // "a hundred", "a thousand": "a" starts a number only before a scale.
+ const aStart = t.word === "a" && i + 2 < toks.length && /^\s+$/.test(toks[i + 1].raw) && (toks[i + 2].word === "hundred" || toks[i + 2].word in SCALES);
+ if (!k && !aStart) {
+ out.push(t.raw);
+ i++;
+ continue;
+ }
+ const acc = new Acc();
+ acc.add(aStart ? "a" : (k as NonNullable<typeof k>), t.word);
+ let j = i + 1;
+ let end = i; // last token index in the number
+ while (j < toks.length) {
+ const sep = toks[j];
+ // A separator between two number words: spaces, a hyphen, " and ".
+ if (/^[\s-]+$/.test(sep.raw) && j + 1 < toks.length) {
+ let n = j + 1;
+ // "three hundred and five": "and" continues a number after hundred/scale.
+ if (toks[n].word === "and" && (acc.last === "hundred" || acc.last === "scale") && n + 2 < toks.length && /^\s+$/.test(toks[n + 1].raw)) n += 2;
+ const w = toks[n].word;
+ const nk = w === "point" ? "point" : w in UNIT_ORDINALS ? "unitOrdinal" : kindOf(w);
+ if (nk && acc.accepts(nk, w) && !splitsBefore(acc, nk, toks, n)) {
+ if (nk === "point") {
+ // "one point five": the point needs a unit after it.
+ const after = toks[n + 2]?.word;
+ if (!(n + 2 < toks.length && /^\s+$/.test(toks[n + 1].raw) && after && after in UNITS && UNITS[after] <= 9)) break;
+ }
+ acc.add(nk, w);
+ end = n;
+ j = n + 1;
+ continue;
+ }
+ break;
+ }
+ // A digit group followed directly by a scale word with no space is not a thing; stop.
+ break;
+ }
+ // "three hundred eleven K", "50 k": a lone k after a number is thousands.
+ if (end + 2 < toks.length && /^ +$/.test(toks[end + 1].raw) && toks[end + 2].word === "k" && !/^[A-Za-z']/.test(toks[end + 3]?.raw ?? "")) {
+ out.push(fmt(acc.value() * 1000));
+ i = end + 3;
+ continue;
+ }
+ // A lone "oh" or "one" stays a word only when it is plainly not a number:
+ // "oh" alone, never; "one" alone becomes 1 (the patterns need it).
+ const prev = out.length ? (out[out.length - 1].trim() === "" ? out[out.length - 2] ?? "" : out[out.length - 1]).trim().toLowerCase() : "";
+ if (end === i && (t.word === "oh" || (t.word === "one" && NOT_A_NUMBER_BEFORE_ONE.has(prev)))) {
+ out.push(t.raw);
+ i++;
+ continue;
+ }
+ out.push(fmt(acc.value()));
+ i = end + 1;
+ }
+ return out.join("");
+}
+
+/** Every number in a text, in order (after `normalizeNumbers`). */
+export function numbersIn(text: string): number[] {
+ return (normalizeNumbers(text).match(/\d+(?:\.\d+)?/g) ?? []).map(Number);
+}
diff --git a/common/lib/frames/poker.test.ts b/common/lib/frames/poker.test.ts
@@ -0,0 +1,241 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { closeSchema } from "../llm/structured";
+import { coercePokerReading, derivePoker, pokerSchema, pokerSystem, pokerUser, POKER_PROFILE, type PokerReading } from "./poker";
+import type { SpokenReading } from "./types";
+
+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 },
+ ...(stack !== undefined ? { hero: { stack } } : {}),
+ ...extra,
+});
+const derive = (rs: R[], spoken: SpokenReading[] = []) => derivePoker(rs, spoken, { everySeconds: 10 });
+const series = (d: ReturnType<typeof derive>, field: string, key?: string) =>
+ (key ? d.tournaments.find((t) => t.key === key)! : d.tournaments[0]).series[field];
+
+// ─── coerce ───
+
+test("coerce: a reading's fields are checked; unreadable is absent, never zero", () => {
+ const r = coercePokerReading({
+ frame: 1,
+ phase: "table",
+ tournament: { name: " Main Event ", level: 7, smallBlind: 500, bigBlind: 1000, ante: null, playersLeft: 85, totalPlayers: 1200, prizePool: null },
+ hero: { stack: 23456.4, stackInBigBlinds: null, seat: null, cards: ["Ah", "10d"] },
+ hand: { pot: 4500, board: ["7c", "7c"], action: null },
+ event: null,
+ });
+ assert.deepEqual(r, {
+ phase: "table",
+ tournament: { name: "Main Event", level: 7, blinds: { sb: 500, bb: 1000 }, playersLeft: 85, totalPlayers: 1200 },
+ hero: { stack: 23456, cards: ["Ah", "Td"] },
+ hand: { pot: 4500 },
+ });
+});
+
+test("coerce: refuses what is not a reading, and drops misread pairs", () => {
+ assert.equal(coercePokerReading(null), null);
+ assert.equal(coercePokerReading({ phase: "dancing" }), null);
+ const r = coercePokerReading({ phase: "table", tournament: { smallBlind: 400, bigBlind: 200, playersLeft: 90, totalPlayers: 40 }, hero: { stack: -5 }, event: "fireworks" });
+ assert.deepEqual(r, { phase: "table", tournament: { playersLeft: 90 } });
+});
+
+// ─── the ask ───
+
+test("the prompt carries rules, a hero hint when given, and no sample reading", () => {
+ const s = pokerSystem({ hero: "SynthHero" });
+ assert.match(s, /null/);
+ assert.match(s, /"SynthHero"/);
+ assert.doesNotMatch(s, /\{"phase"/);
+ assert.doesNotMatch(pokerSystem(), /screen name is/);
+ assert.equal(pokerUser([{ t: 65 }, { t: 3725 }]), "2 frames, in order: frame 1 at 1:05; frame 2 at 1:02:05. Read each.");
+});
+
+test("the schema asks for exactly n readings and closes for a strict model", () => {
+ const s = pokerSchema(3) as { properties: { frames: { minItems: number; maxItems: number } } };
+ assert.equal(s.properties.frames.minItems, 3);
+ assert.equal(s.properties.frames.maxItems, 3);
+ const closed = JSON.stringify(closeSchema(pokerSchema(1)));
+ assert.match(closed, /"additionalProperties":false/);
+ assert.ok(POKER_PROFILE.framesPerAsk.local === 1);
+});
+
+// ─── derive ───
+
+test("a stack that jumps 100× for one frame is a misread, not a double-up", () => {
+ const d = derive([table(0, 20000), table(10, 2000000), table(20, 20500), table(30, 21000)]);
+ assert.deepEqual(d.misreads.filter((m) => m.field === "stack"), [{ t: 10, field: "stack", value: 2000000 }]);
+ assert.deepEqual(d.events.filter((e) => e.kind === "double-up"), []);
+ assert.deepEqual(series(d, "stack"), [[0, 20000], [20, 20500], [30, 21000]]);
+});
+
+test("a double-up held by the next frame is an event; a big loss too", () => {
+ const d = derive([table(0, 20000), table(10, 20000), table(20, 41000), table(30, 41500), table(40, 15000), table(50, 15000), table(60, 15500)]);
+ const kinds = d.events.map((e) => [e.t, e.kind]);
+ assert.deepEqual(kinds, [[20, "double-up"], [40, "big-loss"]]);
+ assert.match(d.events[0].detail, /20,000 → 41,000 chips \(2\.0×\)/);
+});
+
+test("stack in big blinds is the client's when shown, else the stack over the big blind", () => {
+ const d = derive([table(0, 20000), table(10, 30000, {}, { hero: { stack: 30000, bb: 150 } })]);
+ assert.deepEqual(series(d, "stackBB"), [[0, 100], [10, 150]]);
+});
+
+test("a bust: the stack at 0 and no chips after it in that tournament", () => {
+ const d = derive([table(0, 9000), table(10, 9000), table(20, 0, {}, { event: "eliminated" }), { t: 30, phase: "lobby", tournament: { name: "Main Event" } }]);
+ const bust = d.events.find((e) => e.kind === "bust")!;
+ assert.equal(bust.t, 20);
+ assert.match(bust.detail, /out from 9,000 chips/);
+ assert.ok(d.events.some((e) => e.kind === "eliminated" && e.source === "frame"));
+});
+
+test("a 0 for one frame between two stacks is a misread, not a bust", () => {
+ const d = derive([table(0, 9000), table(10, 0), table(20, 9100)]);
+ assert.equal(d.events.filter((e) => e.kind === "bust").length, 0);
+});
+
+test("the final table: players left first at 9 or fewer in a larger field", () => {
+ const d = derive([table(0, 1, { playersLeft: 12 }), table(10, 1, { playersLeft: 10 }), table(20, 1, { playersLeft: 9 }), table(30, 1, { playersLeft: 8 })]);
+ assert.deepEqual(d.events.filter((e) => e.kind === "final-table").map((e) => e.t), [20]);
+});
+
+test("a win: one player left and the hero with chips", () => {
+ const d = derive([table(0, 50000, { playersLeft: 2 }), table(10, 240000, { playersLeft: 1 })]);
+ assert.ok(d.events.some((e) => e.kind === "won" && e.t === 10));
+});
+
+test("frame events are one per run: the same banner for a minute is one moment", () => {
+ const d = derive([table(0, 1000, {}, { event: "all-in" }), table(10, 1000, {}, { event: "all-in" }), table(100, 1000, {}, { event: "all-in" })]);
+ assert.deepEqual(d.events.filter((e) => e.kind === "all-in").map((e) => e.t), [0, 100]);
+});
+
+test("phase segments: a one-frame blip between two of another phase is absorbed", () => {
+ const d = derive([
+ { t: 0, phase: "lobby" },
+ { t: 10, phase: "lobby" },
+ table(20, 100),
+ { t: 30, phase: "other" },
+ table(40, 100),
+ { t: 50, phase: "break" },
+ { t: 60, phase: "break" },
+ ]);
+ assert.deepEqual(d.segments.map((s) => [s.from, s.to, s.phase]), [[0, 20, "lobby"], [20, 50, "table"], [50, 70, "break"]]);
+ 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)]);
+ 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", "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", () => {
+ 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 } },
+ ]);
+ assert.deepEqual(d.tournaments.map((t) => t.key), ["main event", "main event#2"]);
+});
+
+test("a spoken number that disagrees with a nearby frame is flagged, never trusted; one that agrees is quiet", () => {
+ const spoken: SpokenReading[] = [
+ { t: 12, field: "playersLeft", value: 85, text: "eighty five players left" },
+ { 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" }]);
+});
+
+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 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.equal(d.events.filter((e) => e.kind === "double-up").length, 0);
+});
+
+test("spoken facts land in the tournament's facts when no frame read them; a buy-in is an event", () => {
+ const spoken: SpokenReading[] = [{ t: 5, field: "buyIn", value: 2750, text: "$2,750 buy in" }];
+ const d = derive([table(0, 1000), table(10, 1000)], spoken);
+ assert.equal(d.tournaments[0].facts.buyIn, 2750);
+ assert.equal(d.tournaments[0].facts.totalPlayers, 120);
+ assert.ok(d.events.some((e) => e.kind === "buy-in" && e.source === "spoken"));
+});
+
+test("derive is pure over its input order", () => {
+ const rs = [table(20, 41000), table(0, 20000), table(10, 20000), table(30, 41000)];
+ assert.deepEqual(derive(rs), derive([...rs].sort((a, b) => a.t - b.t)));
+});
+
+// ─── The client's log (prompt version 2) ───
+
+test("coerce: the log's lines kept as written (trimmed, the last eight), the hero's bounty, the average stack", () => {
+ const r = coercePokerReading({
+ phase: "table",
+ tournament: { averageStack: 300000, position: 32, playersLeft: 85 },
+ hero: { stack: 355050, bounty: 625 },
+ log: [" Dealer: SynthA takes the pot 1,000. ", 7, "", "Blinds are now 1,800/3,600"],
+ })!;
+ assert.deepEqual(r.log, ["Dealer: SynthA takes the pot 1,000.", "Blinds are now 1,800/3,600"]);
+ assert.equal(r.hero?.bounty, 625);
+ assert.equal(r.tournament?.averageStack, 300000);
+});
+
+const logged = (t: number, stack: number, log: string[], more: Partial<NonNullable<PokerReading["tournament"]>> = {}): R => ({ ...table(t, stack, more), log });
+
+test("the hero's pots from the log, each line once while it scrolls; 25 big blinds or more is a big pot", () => {
+ const rs = [
+ logged(0, 20000, ["Dealer: SynthHero takes the pot 1,600."]),
+ logged(10, 21600, ["Dealer: SynthHero takes the pot 1,600.", "Dealer: Villain takes the pot 3,000."]),
+ logged(20, 26600, ["Dealer: SynthHero takes the pot 1,600.", "Dealer: Villain takes the pot 3,000.", "Dealer: SynthHero takes the main pot 6,000 with One pair Tens."]),
+ ];
+ const d = derivePoker(rs, [], { everySeconds: 10, hero: "SynthHero" });
+ const pots = d.events.filter((e) => e.source === "log").map((e) => [e.t, e.kind, e.detail]);
+ assert.deepEqual(pots, [
+ [0, "pot", "takes the pot 1,600 (8 BB)"],
+ [20, "big-pot", "takes the main pot 6,000 (30 BB) with One pair Tens"],
+ ]);
+ // Without the hero's name, the log says nothing about the hero.
+ assert.equal(derivePoker(rs, [], { everySeconds: 10 }).events.filter((e) => e.source === "log").length, 0);
+});
+
+test("a knockout and a bust from the log; the blinds from 'Blinds are now' when the frame did not read them", () => {
+ const noBlinds = (t: number, stack: number, log: string[]): R => ({ t, phase: "table", tournament: { name: "Main Event" }, hero: { stack }, log });
+ const rs = [
+ noBlinds(0, 50000, ["Blinds are now 1,800/3,600"]),
+ noBlinds(10, 90000, ["Blinds are now 1,800/3,600", "SynthHero knocked out Villain and wins a $625 bounty"]),
+ noBlinds(20, 0, ["Villain2 knocked out SynthHero"]),
+ ];
+ const d = derivePoker(rs, [], { everySeconds: 10, hero: "SynthHero" });
+ assert.deepEqual(d.tournaments[0].series.bigBlind, [[0, 3600]]);
+ assert.deepEqual(d.tournaments[0].series.stackBB, [[0, 13.9], [10, 25], [20, 0]]);
+ assert.deepEqual(d.events.filter((e) => e.source === "log").map((e) => [e.t, e.kind]), [[10, "knockout"], [20, "bust"]]);
+});
+
+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 })]);
+ 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]]);
+});
+
+test("the stats header: the hero's place and the average stack are series", () => {
+ const d = derive([table(0, 300000, { position: 40, playersLeft: 90, averageStack: 280000 }), table(10, 310000, { position: 32, playersLeft: 85, averageStack: 300000 })]);
+ assert.deepEqual(series(d, "position"), [[0, 40], [10, 32]]);
+ assert.deepEqual(series(d, "averageStack"), [[0, 280000], [10, 300000]]);
+});
+
+test("players left from the log's finishing places when the frame did not show them", () => {
+ const rs: R[] = [
+ { t: 0, phase: "table", tournament: { name: "Main Event" }, hero: { stack: 1000 }, log: ["SynthA has finished the tournament in 88th", "SynthB has finished the tournament in 87th"] },
+ { 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]]);
+});
diff --git a/common/lib/frames/poker.ts b/common/lib/frames/poker.ts
@@ -0,0 +1,581 @@
+// The frame scan's first profile: an online poker client on a stream
+// (release 30, lane P). A vision model reads each kept frame into a POKER
+// READING — what the client shows, every field optional and never invented —
+// and pure code derives the rest: the series per tournament (chips, big
+// blinds, players left, level), the events (a double-up, a bust, the final
+// table…), the phase segments, and the flags where a spoken number disagrees
+// with what a frame read.
+//
+// The model reads a frame; code derives everything else (the brief's rule).
+// Counts, ranges and enums are enforced here, in `coercePokerReading`, never
+// trusted from the prompt.
+
+import { pokerSpoken } from "./pokerSpoken";
+import { agree, changesOnly, dropMisreads, nearest, type AgreeRule, type Pt } from "./series";
+import {
+ clock,
+ fmtNum,
+ type Derived,
+ type DerivedEvent,
+ type DerivedFlag,
+ type DerivedSegment,
+ type DerivedTournament,
+ type FrameProfile,
+ type SeriesPoint,
+ type SpokenReading,
+} from "./types";
+
+export const POKER_PHASES = ["lobby", "table", "break", "other"] as const;
+export type PokerPhase = (typeof POKER_PHASES)[number];
+export const POKER_FRAME_EVENTS = ["all-in", "bust", "double-up", "final-table", "eliminated", "won"] as const;
+export type PokerFrameEvent = (typeof POKER_FRAME_EVENTS)[number];
+
+export type PokerReading = {
+ phase: PokerPhase;
+ tournament?: {
+ name?: string;
+ level?: number;
+ blinds?: { sb?: number; bb?: number; ante?: number };
+ playersLeft?: number;
+ totalPlayers?: number;
+ prizePool?: number;
+ position?: number;
+ payout?: number;
+ averageStack?: number;
+ };
+ hero?: { stack?: number; bb?: number; seat?: number; cards?: string[]; bounty?: number };
+ hand?: { number?: number; pot?: number; board?: string[]; action?: string };
+ // The client's dealer/chat log lines as shown, oldest first (code reads
+ // the hero's pots, knockouts, a bust and the blinds out of them).
+ log?: string[];
+ event?: PokerFrameEvent;
+};
+
+// ─── The ask ───
+
+const num = { type: ["number", "null"] } as const;
+const int = { type: ["integer", "null"] } as const;
+const str = { type: ["string", "null"] } as const;
+const cards = { type: ["array", "null"], items: { type: "string" } } as const;
+
+const READING_SCHEMA = {
+ type: "object",
+ properties: {
+ frame: { type: "integer" },
+ phase: { type: "string", enum: [...POKER_PHASES] },
+ tournament: {
+ type: "object",
+ properties: {
+ name: str,
+ level: int,
+ smallBlind: num,
+ bigBlind: num,
+ ante: num,
+ playersLeft: int,
+ totalPlayers: int,
+ prizePool: num,
+ position: int,
+ payout: num,
+ averageStack: num,
+ },
+ },
+ hero: {
+ type: "object",
+ properties: { stack: num, stackInBigBlinds: num, seat: int, cards, bounty: num },
+ },
+ hand: {
+ type: "object",
+ properties: { number: int, pot: num, board: cards, action: str },
+ },
+ log: { type: ["array", "null"], items: { type: "string" } },
+ event: { type: ["string", "null"], enum: [...POKER_FRAME_EVENTS, null] },
+ },
+ required: ["frame", "phase"],
+} as const;
+
+export function pokerSchema(n: number): object {
+ return {
+ type: "object",
+ properties: { frames: { type: "array", items: READING_SCHEMA, minItems: n, maxItems: n } },
+ required: ["frames"],
+ };
+}
+
+// Rules only (Q0): no worked examples, no sample readings.
+export function pokerSystem(hints: { hero?: string } = {}): string {
+ return [
+ "You read screenshots from a livestream of online poker and report what the poker client shows, as data.",
+ "Rules:",
+ "- Report only what is legible in that frame. A field that is not shown, cut off or unreadable is null. Never guess, never carry a value over from another frame, never compute a value the screen does not show.",
+ "- Numbers are plain numbers: chips as whole chips (expand K and M suffixes), money in dollars, no separators.",
+ "- phase: table when a poker table in play is the main picture; lobby for a tournament lobby, a tournament list, a registration or a results screen; break when the table shows a break or a resume countdown, or a paused or starting-soon screen; other for anything else (a camera, a desktop, a browser, a chat).",
+ `- The hero is the streamer's own player: the seat whose hole cards are shown face up, usually at the bottom of the table.${hints.hero ? ` The hero's screen name is "${hints.hero}".` : ""}`,
+ "- A seat's name box may show the player's last action (FOLD, CHECK, CALL) in place of the name for a moment; the seat is still that player's.",
+ "- hero.stack is the hero's chip count; hero.stackInBigBlinds only when the client itself shows the stack in big blinds; hero.cards the hero's hole cards.",
+ "- Cards are rank then suit, one character each: ranks 2-9, T, J, Q, K, A; suits s, h, d, c.",
+ "- tournament.name is the tournament's title as the client shows it (a lobby title, a stats header, or the name printed on the table felt); level the blind level's number; smallBlind, bigBlind and ante the current blinds; position the hero's rank and playersLeft the players remaining, as in a \"position N of M\" display; totalPlayers the field at the start, when shown apart; averageStack the average stack when shown; payout the money the hero has won or is guaranteed, when shown; prizePool when shown.",
+ "- hero.bounty is the bounty shown on the hero's own seat (a knockout tournament), in dollars.",
+ "- log is the client's dealer or chat log as shown on screen, one string per line, oldest first, copied as written (names, numbers and punctuation); null when no log is shown.",
+ "- hand.pot is the pot in chips; hand.board the community cards; hand.action a few words for the action shown (a bet, a raise, an all-in), or null.",
+ "- event is set only when the screen shows it in words or a banner: all-in, bust or eliminated (the hero is out), double-up, final-table, won (the hero won the tournament). Otherwise null.",
+ "- Frames come in time order, numbered from 1. Answer one reading per frame, in order, each read on its own.",
+ ].join("\n");
+}
+
+export function pokerUser(frames: { t: number }[]): string {
+ return `${frames.length} frame${frames.length === 1 ? "" : "s"}, in order: ${frames.map((f, i) => `frame ${i + 1} at ${clock(f.t)}`).join("; ")}. Read each.`;
+}
+
+// ─── The reading, cleaned ───
+
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
+const nonNeg = (v: unknown, max = 1e12): number | undefined =>
+ typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= max ? v : undefined;
+const whole = (v: unknown, max = 1e12): number | undefined => {
+ const n = nonNeg(v, max);
+ return n === undefined ? undefined : Math.round(n);
+};
+const CARD = /^(?:[2-9TJQKA])[shdc]$/;
+function cardList(v: unknown, max: number): string[] | undefined {
+ if (!Array.isArray(v)) return undefined;
+ const out = v
+ .filter((c): c is string => typeof c === "string")
+ .map((c) => c.trim().replace(/^10/, "T"))
+ .map((c) => (c.length === 2 ? c[0].toUpperCase() + c[1].toLowerCase() : c))
+ .filter((c) => CARD.test(c));
+ return out.length && out.length <= max && new Set(out).size === out.length ? out : undefined;
+}
+const prune = <T extends Record<string, unknown>>(o: T): T | undefined => {
+ for (const k of Object.keys(o)) if (o[k] === undefined) delete o[k];
+ return Object.keys(o).length ? o : undefined;
+};
+
+/** A model's reading as a PokerReading, every field checked; null when it is not a reading. */
+const logLines = (v: unknown): string[] | undefined => {
+ if (!Array.isArray(v)) return undefined;
+ const out = v
+ .filter((l): l is string => typeof l === "string")
+ .map((l) => l.replace(/\s+/g, " ").trim().slice(0, 200))
+ .filter(Boolean)
+ .slice(-8);
+ return out.length ? out : undefined;
+};
+
+export function coercePokerReading(raw: unknown): PokerReading | null {
+ if (!isObj(raw)) return null;
+ const phase = typeof raw.phase === "string" && (POKER_PHASES as readonly string[]).includes(raw.phase) ? (raw.phase as PokerPhase) : null;
+ if (!phase) return null;
+ const out: PokerReading = { phase };
+ const t = isObj(raw.tournament) ? raw.tournament : null;
+ if (t) {
+ const blinds = prune({ sb: nonNeg(t.smallBlind), bb: nonNeg(t.bigBlind), ante: nonNeg(t.ante) });
+ // A big blind under the small one is a misread pair: neither is kept.
+ const okBlinds = blinds && !(blinds.sb !== undefined && blinds.bb !== undefined && blinds.bb < blinds.sb) ? blinds : undefined;
+ const name = typeof t.name === "string" ? t.name.replace(/\s+/g, " ").trim().slice(0, 120) : "";
+ const tour = prune({
+ name: name || undefined,
+ level: whole(t.level, 500),
+ blinds: okBlinds,
+ playersLeft: whole(t.playersLeft, 10_000_000),
+ totalPlayers: whole(t.totalPlayers, 10_000_000),
+ prizePool: nonNeg(t.prizePool),
+ position: whole(t.position, 10_000_000),
+ payout: nonNeg(t.payout),
+ averageStack: whole(t.averageStack),
+ });
+ // Players left over the field is a misread pair: the field is dropped.
+ if (tour && tour.playersLeft !== undefined && tour.totalPlayers !== undefined && tour.playersLeft > tour.totalPlayers) delete tour.totalPlayers;
+ if (tour) out.tournament = tour;
+ }
+ const h = isObj(raw.hero) ? raw.hero : null;
+ if (h) {
+ const hero = prune({ stack: whole(h.stack), bb: nonNeg(h.stackInBigBlinds ?? h.bb, 1_000_000), seat: whole(h.seat, 12), cards: cardList(h.cards, 6), bounty: nonNeg(h.bounty, 1e9) });
+ if (hero) out.hero = hero;
+ }
+ const hd = isObj(raw.hand) ? raw.hand : null;
+ if (hd) {
+ const action = typeof hd.action === "string" ? hd.action.replace(/\s+/g, " ").trim().slice(0, 80) : "";
+ const hand = prune({ number: whole(hd.number), pot: whole(hd.pot), board: cardList(hd.board, 5), action: action || undefined });
+ if (hand) out.hand = hand;
+ }
+ const log = logLines(raw.log);
+ if (log) out.log = log;
+ if (typeof raw.event === "string" && (POKER_FRAME_EVENTS as readonly string[]).includes(raw.event)) out.event = raw.event as PokerFrameEvent;
+ return out;
+}
+
+// ─── Derivation (pure) ───
+
+type R = PokerReading & { t: number };
+
+// How two readings of a field must agree to call a third a misread, and a
+// spoken number a frame's.
+const MISREAD: Record<string, AgreeRule> = {
+ stack: { ratio: 3 },
+ stackBB: { ratio: 3 },
+ playersLeft: { ratio: 1.5, absolute: 3 },
+ level: { ratio: 1.5, absolute: 1 },
+ position: { ratio: 2, absolute: 5 },
+ averageStack: { ratio: 2 },
+ bigBlind: { ratio: 2.5 },
+};
+const SPOKEN_AGREE: Record<string, AgreeRule> = {
+ stack: { ratio: 1.3 },
+ stackBB: { ratio: 1.3, absolute: 2 },
+ playersLeft: { ratio: 1.15, absolute: 2 },
+ level: { ratio: 1, absolute: 1 },
+ position: { ratio: 1.2, absolute: 3 },
+ averageStack: { ratio: 1.3 },
+ bigBlind: { ratio: 1.01 },
+};
+// Spoken fields that are series; the rest are facts.
+const SPOKEN_SERIES = new Set(["stack", "stackBB", "playersLeft", "level", "position", "averageStack", "bigBlind"]);
+const SPOKEN_WINDOW_S = 90;
+const FINAL_TABLE = 9;
+
+const normName = (s: string) => s.toLowerCase().replace(/[^a-z0-9$]+/g, " ").trim();
+
+// 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;
+ }
+ if (r.phase !== "table") awayAfterOut = true;
+ if (r.phase !== "table" && r.phase !== "lobby") {
+ keys.push(null);
+ continue;
+ }
+ 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);
+ }
+ out = false;
+ }
+ if (r.hero?.stack === 0 || r.event === "bust" || r.event === "eliminated") {
+ out = true;
+ awayAfterOut = 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);
+ }
+ 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);
+ }
+ return { keys, names };
+}
+
+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 }));
+
+/**
+ * Readings (and spoken numbers) to tournaments with series, events, phase
+ * segments and flags. Pure; heavily tested (poker.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 segments = phaseSegments(rs, o);
+ const { keys, names } = keyReadings(rs);
+ 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 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);
+ });
+
+ 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 });
+ }
+ 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);
+ }
+ 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;
+ if (t?.prizePool !== undefined) facts.prizePool = t.prizePool;
+ if (t?.payout !== undefined) facts.payout = t.payout;
+ if (t?.position !== 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);
+ if (name) tour.name = name;
+ tournaments.push(tour);
+ }
+ tournaments.sort((a, b) => a.from - b.from);
+
+ const flags = crossCheck(tournaments, 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) };
+}
+
+// Phase segments: a phase seen on ONE frame between two frames of another
+// (the same both sides) is that other phase — a transition frame, a misread.
+function phaseSegments(rs: readonly R[], o: { everySeconds: number; durationSeconds?: number }): DerivedSegment[] {
+ const phases = rs.map((r) => r.phase as string);
+ for (let i = 1; i < phases.length - 1; i++) if (phases[i - 1] === phases[i + 1] && phases[i] !== phases[i - 1]) phases[i] = phases[i - 1];
+ const out: DerivedSegment[] = [];
+ rs.forEach((r, i) => {
+ const last = out[out.length - 1];
+ if (last && last.phase === phases[i]) return;
+ if (last) last.to = r.t;
+ out.push({ from: r.t, to: r.t, phase: phases[i] });
+ });
+ if (out.length) {
+ const end = rs[rs.length - 1].t + o.everySeconds;
+ out[out.length - 1].to = o.durationSeconds !== undefined ? Math.min(o.durationSeconds, end) : end;
+ }
+ 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[] {
+ const out: DerivedEvent[] = [];
+ rs.forEach((r, i) => {
+ if (!r.event) return;
+ const prev = out.filter((e) => e.kind === r.event).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" };
+ 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[] {
+ const out: DerivedEvent[] = [];
+ 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 ?? [];
+ 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) {
+ 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) {
+ out.push({ t: b.t, kind: "big-loss", detail: `${fmtNum(a.v)} → ${fmtNum(b.v)} chips`, source: "series", tournament: tour.key });
+ }
+ }
+ const zero = stack.findIndex((p) => p.v === 0);
+ if (zero >= 0 && !stack.slice(zero + 1).some((p) => p.v > 0)) {
+ 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 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 });
+ }
+ return out;
+}
+
+// ─── The client's log ───
+
+const digits = (s: string) => Number(s.replace(/,/g, ""));
+const BLINDS_LINE = /^blinds are now ([\d,]+)\s*\/\s*([\d,]+)/i;
+const POT_LINE = /^dealer:\s*(.+?) takes the (?:(main|side) )?pot ([\d,]+)(?: with (.+?))?\.?$/i;
+
+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
+// three minutes is the same line scrolling, not a second pot. A pot the hero
+// takes is `pot`, or `big-pot` at 25 big blinds or more; a line naming the
+// hero beside a knockout word is a `knockout` (the hero knocked someone out)
+// or a `bust` (someone knocked the hero out, or the hero finished).
+function logEvents(rs: readonly R[], keys: readonly (string | null)[], full: ReadonlyMap<string, Record<string, Pt[]>>, hero?: string): DerivedEvent[] {
+ if (!hero) return [];
+ const out: DerivedEvent[] = [];
+ const seen = new Map<string, number>();
+ rs.forEach((r, i) => {
+ for (const line of r.log ?? []) {
+ const at = seen.get(line);
+ seen.set(line, r.t);
+ if (at !== undefined && r.t - at <= 180) continue;
+ const key = keys[i] ?? undefined;
+ const pot = POT_LINE.exec(line);
+ if (pot) {
+ if (!sameName(pot[1], hero)) continue;
+ const v = digits(pot[3]);
+ const bb = key ? nearestBefore(full.get(key)?.bigBlind ?? [], r.t) : null;
+ const big = bb ? v >= 25 * bb : false;
+ out.push({ t: r.t, kind: big ? "big-pot" : "pot", detail: `takes the ${pot[2] ? `${pot[2]} ` : ""}pot ${fmtNum(v)}${bb ? ` (${Math.round(v / bb)} BB)` : ""}${pot[4] ? ` with ${pot[4]}` : ""}`, source: "log", ...(key ? { tournament: key } : {}) });
+ continue;
+ }
+ if (!/\b(knocked out|knocks out|eliminated|eliminates|busted|finished|bounty)\b/i.test(line) || !line.toLowerCase().includes(hero.toLowerCase())) continue;
+ const heroFirst = line.toLowerCase().replace(/^dealer:\s*/, "").startsWith(hero.toLowerCase());
+ const kind = heroFirst && !/\bfinished\b|\bbusted\b|\bis eliminated\b|\bwas eliminated\b|\bhas been eliminated\b/i.test(line) ? "knockout" : "bust";
+ out.push({ t: r.t, kind, detail: line, source: "log", ...(key ? { tournament: key } : {}) });
+ }
+ });
+ return out;
+}
+
+function nearestBefore(points: readonly Pt[], t: number): number | null {
+ let v: number | null = null;
+ for (const p of points) {
+ if (p.t > t) break;
+ v = p.v;
+ }
+ return v ?? points[0]?.v ?? null;
+}
+
+// What the streamer said that is an event in itself: none of the numbers is,
+// but a buy-in or a prize said marks the start of talk about a tournament.
+function spokenEvents(spoken: readonly SpokenReading[]): DerivedEvent[] {
+ return spoken
+ .filter((s) => s.field === "buyIn")
+ .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[] {
+ const flags: DerivedFlag[] = [];
+ 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) {
+ const tour = at(s.t);
+ if (!SPOKEN_SERIES.has(s.field)) {
+ if (tour && tour.facts[s.field] === undefined) tour.facts[s.field] = s.value;
+ 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 });
+ }
+ 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;
+}
+
+export const POKER_PROFILE: FrameProfile<PokerReading> = {
+ id: "poker",
+ // 2: the stats header, the dealer log, the hero's bounty, the break countdown.
+ promptVersion: 2,
+ // Wide enough for a client's small numbers on a 1080p stream.
+ width: 1280,
+ dupMaxBits: 2,
+ rereadEvery: 6,
+ framesPerAsk: { api: 4, local: 1 },
+ system: pokerSystem,
+ user: pokerUser,
+ schema: pokerSchema,
+ coerce: coercePokerReading,
+ spoken: pokerSpoken,
+ derive: derivePoker,
+};
diff --git a/common/lib/frames/pokerSpoken.test.ts b/common/lib/frames/pokerSpoken.test.ts
@@ -0,0 +1,103 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { pokerSpoken } from "./pokerSpoken";
+
+const cue = (start: number, text: string) => ({ start, end: start + 3, text });
+const pick = (rs: ReturnType<typeof pokerSpoken>, field: string) => rs.filter((r) => r.field === field).map((r) => [r.t, r.value]);
+
+test("players left, said in words, dated by its cue", () => {
+ const rs = pokerSpoken([cue(339, "okay eighty five players left"), cue(3218, "we are down to fifteen players left now")]);
+ assert.deepEqual(pick(rs, "playersLeft"), [[339, 85], [3218, 15]]);
+});
+
+test("a phrase split across two cues still reads, dated by its first cue", () => {
+ const rs = pokerSpoken([cue(10, "we have eighty five"), cue(13, "players left in this one")]);
+ assert.deepEqual(pick(rs, "playersLeft"), [[10, 85]]);
+});
+
+test("a buy-in, in dollars or words", () => {
+ const rs = pokerSpoken([cue(3326, "this is the $2,750 buy in"), cue(5000, "the buy in is six bucks for the viewers")]);
+ assert.deepEqual(pick(rs, "buyIn"), [[3326, 2750], [5000, 6]]);
+});
+
+test("a stack said without 'thousand' beside an average said with it is scaled, and marked approx", () => {
+ const rs = pokerSpoken([cue(6557, "the average stack is three hundred seventy three thousand"), cue(6560, "I have two hundred thirty three")]);
+ assert.deepEqual(pick(rs, "averageStack"), [[6557, 373000]]);
+ const stack = rs.filter((r) => r.field === "stack");
+ assert.deepEqual(stack.map((r) => [r.t, r.value, r.approx]), [[6560, 233000, true]]);
+});
+
+test("a small stack with no average near it is left out, as is a count of something else", () => {
+ const rs = pokerSpoken([cue(10, "I have two hundred thirty three"), cue(20, "I have 2 kings"), cue(30, "I have 500 bucks on this")]);
+ assert.deepEqual(pick(rs, "stack"), []);
+});
+
+test("an opponent's chips are not the hero's", () => {
+ const rs = pokerSpoken([cue(5350, "he's at five hundred sixty seven thousand chips")]);
+ assert.deepEqual(pick(rs, "stack"), []);
+});
+
+test("stack in big blinds, blinds, level, first prize", () => {
+ const rs = pokerSpoken([
+ cue(100, "I'm down to six big blinds"),
+ cue(200, "blinds are fifteen hundred three thousand"),
+ cue(300, "we're on level fourteen"),
+ cue(400, "first place five hundred bucks"),
+ ]);
+ assert.deepEqual(pick(rs, "stackBB"), [[100, 6]]);
+ assert.deepEqual(pick(rs, "bigBlind"), [[200, 3000]]);
+ assert.deepEqual(pick(rs, "smallBlind"), [[200, 1500]]);
+ assert.deepEqual(pick(rs, "level"), [[300, 14]]);
+ assert.deepEqual(pick(rs, "firstPrize"), [[400, 500]]);
+});
+
+test("two numbers beside 'blinds' that are not a blind pair are not read as one", () => {
+ const rs = pokerSpoken([cue(10, "blinds are 5 50")]);
+ assert.deepEqual(pick(rs, "bigBlind"), []);
+});
+
+test("the same number said again within 30 s is one reading", () => {
+ const rs = pokerSpoken([cue(10, "eighty five players left"), cue(20, "yeah eighty five players left"), cue(100, "eighty five players left")]);
+ assert.deepEqual(pick(rs, "playersLeft"), [[10, 85], [100, 85]]);
+});
+
+test("no cues, no readings; the text is kept for a reader", () => {
+ assert.deepEqual(pokerSpoken([]), []);
+ const [r] = pokerSpoken([cue(1, "eighty five players left")]);
+ assert.equal(r.text, "eighty five players left");
+});
+
+test("calibrated phrasings: a k after a number, a buy-in said in dollars, the ASR's 'buying', a prize pool before its number", () => {
+ const rs = pokerSpoken([
+ cue(10, "the average is four hundred twelve K I have three hundred eight K"),
+ cue(20, "no it's one thousand one hundred dollars buy in"),
+ cue(30, "tonight's buying is like four bucks"),
+ cue(40, "two million dollars in the prize pool"),
+ ]);
+ assert.deepEqual(pick(rs, "averageStack"), [[10, 412000]]);
+ assert.deepEqual(pick(rs, "stack"), [[10, 308000]]);
+ assert.deepEqual(pick(rs, "buyIn"), [[20, 1100], [30, 4]]);
+ assert.deepEqual(pick(rs, "prizePool"), [[40, 2000000]]);
+});
+
+test("the hero's place in the field, and the field it is out of", () => {
+ const rs = pokerSpoken([cue(10, "I'm in sixty fourth place out of seventy two people"), cue(100, "and I moved up to forty first")]);
+ assert.deepEqual(pick(rs, "position"), [[10, 64], [100, 41]]);
+ assert.deepEqual(pick(rs, "playersLeft"), [[10, 72]]);
+});
+
+test("a stack said as a supposition is not a reading; a bare 'level' of a game is not the blind level", () => {
+ const rs = pokerSpoken([
+ cue(10, "once I'm down to sixty thousand chips I shove"),
+ cue(20, "it's not like I'm sitting on forty k"),
+ cue(30, "I'd buy a level sixty character"),
+ cue(40, "we're at level nine now"),
+ ]);
+ assert.deepEqual(pick(rs, "stack"), []);
+ assert.deepEqual(pick(rs, "level"), [[40, 9]]);
+});
+
+test("a stack said without 'thousand' is scaled by an average said up to half an hour away", () => {
+ const rs = pokerSpoken([cue(100, "the average stack is two hundred thousand"), cue(1500, "well I've got one hundred eighty")]);
+ assert.deepEqual(rs.filter((r) => r.field === "stack").map((r) => [r.value, r.approx]), [[180000, true]]);
+});
diff --git a/common/lib/frames/pokerSpoken.ts b/common/lib/frames/pokerSpoken.ts
@@ -0,0 +1,156 @@
+// The poker stats a streamer SAYS, read out of the cues by pure code
+// (release 30, lane P): the frame scan's second, cheap signal. A frame reading
+// that disagrees with a nearby spoken number is flagged, and a gap the frames
+// leave is filled from it (poker.ts `derive`).
+//
+// The cues are joined into one text so a phrase split across two cues ("eighty
+// five" | "players left") still reads, every number is normalized to digits
+// (numberWords.ts), and plain patterns read the fields. A match is dated by the
+// cue its first character came from. Rule-based: what the patterns do not
+// cover is not read, never guessed.
+
+import { normalizeNumbers } from "./numberWords";
+import type { Cue, SpokenReading } from "./types";
+
+type Piece = { at: number; t: number; cue: number };
+
+// The joined, normalized text and where each cue's part of it starts.
+function joined(cues: readonly Cue[]): { text: string; pieces: Piece[] } {
+ const pieces: Piece[] = [];
+ let text = "";
+ cues.forEach((c, i) => {
+ pieces.push({ at: text.length, t: c.start, cue: i });
+ text += `${normalizeNumbers(String(c.text ?? "")).replace(/\s+/g, " ").trim()} `;
+ });
+ return { text: text.toLowerCase(), pieces };
+}
+
+function pieceAt(pieces: readonly Piece[], at: number): Piece {
+ let lo = 0;
+ let hi = pieces.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (pieces[mid].at <= at) lo = mid;
+ else hi = mid - 1;
+ }
+ return pieces[lo];
+}
+
+const N = String.raw`(\d+(?:\.\d+)?)`;
+const SOFT = String.raw`(?:about |around |like |only |just |roughly |almost |nearly |over |under )?`;
+
+// One field's patterns: the first capture group is the value.
+type Rule = { field: string; re: RegExp; min?: number; max?: number };
+
+const RULES: Rule[] = [
+ { field: "playersLeft", re: new RegExp(String.raw`\b${N} (?:players|people|runners|entrants|left in the field|of us)(?: are)? (?:left|remaining)\b`, "g"), min: 1, max: 1_000_000 },
+ { field: "playersLeft", re: new RegExp(String.raw`\b(?:down to|we're at|we are at|there are|there's) ${SOFT}${N} (?:players )?(?:left|remaining)\b`, "g"), min: 1, max: 1_000_000 },
+ { field: "playersLeft", re: new RegExp(String.raw`\bplace out of ${N} (?:people|players|left)\b`, "g"), min: 1, max: 1_000_000 },
+ { field: "totalPlayers", re: new RegExp(String.raw`\b${N} (?:entrants|entries|runners|players registered|players total|total players)\b`, "g"), min: 2, max: 1_000_000 },
+ { field: "averageStack", re: new RegExp(String.raw`\baverage(?: stack| chip stack)?(?: is| was| of|'s)? ${SOFT}${N}\b`, "g"), min: 100 },
+ // The hero's stack in big blinds: "I'm down to 6 big blinds", "I have 22 bigs".
+ { field: "stackBB", re: new RegExp(String.raw`\b(?:i have|i've got|i got|i'm at|i am at|i'm down to|i am down to|i'm sitting on|i'm sitting at|i'm on|my stack is) ${SOFT}${N} (?:big blinds|bigs|bbs|bb)\b`, "g"), min: 0, max: 100_000 },
+ // The hero's chips: "I have 233" (said without "thousand" beside an average
+ // said with it: scaled below), "I've got 1500000 chips".
+ { field: "stack", re: new RegExp(String.raw`\b(?:i have|i've got|i got|i'm at|i am at|i'm sitting on|i'm sitting at|my stack is|i'm up to|i'm down to) ${SOFT}${N}(?! (?:big blinds|bigs|bbs|bb|players|people|minutes|seconds|hours|dollars|bucks|percent|hands|cards|outs|times|kings|queens|jacks|aces|tens|nines|eights|sevens|sixes|fives|fours|threes|twos|of)\b)`, "g"), min: 100 },
+ { field: "buyIn", re: new RegExp(String.raw`\$?${N} (?:dollars? |bucks? )?buy[- ]?in\b`, "g"), min: 0.01 },
+ // "the buy in is six bucks" — and the ASR's "buying is like five bucks".
+ { field: "buyIn", re: new RegExp(String.raw`\bbuy(?:[- ]?in|ing) (?:is|was|of|for) ${SOFT}\$?${N}\b`, "g"), min: 0.01 },
+ { field: "firstPrize", re: new RegExp(String.raw`\bfirst place (?:is |gets |pays |is worth |wins )?\$?${N}\b`, "g"), min: 1 },
+ { field: "prizePool", re: new RegExp(String.raw`\b(?:prize pool|guarantee)(?: is| of) \$?${N}\b`, "g"), min: 1 },
+ { field: "prizePool", re: new RegExp(String.raw`\$?${N} (?:dollars? |bucks? )?(?:in the |for the )?(?:prize pool|guaranteed?)\b`, "g"), min: 1 },
+ // The blind level, said as poker says it — never a bare "level N" (a
+ // streamer who games says "a level eighty character" too).
+ { field: "level", re: new RegExp(String.raw`\b(?:blind level|(?:we're|we are|it's|now|we're now) (?:at |on |in )?level) ${N}\b`, "g"), min: 1, max: 200 },
+ { field: "level", re: new RegExp(String.raw`\blevel ${N} (?:blinds|of the tournament)\b`, "g"), min: 1, max: 200 },
+ // The hero's place in the field: "I'm in 93rd place", "I moved up to 81st".
+ { field: "position", re: new RegExp(String.raw`\b(?:i'm|i am) (?:in )?${N}(?:st|nd|rd|th)? place\b`, "g"), min: 1, max: 1_000_000 },
+ { field: "position", re: new RegExp(String.raw`\bmoved (?:up|down) to ${N}(?:st|nd|rd|th)?\b(?! (?:chips|big|bb|bbs|thousand|k)\b)`, "g"), min: 1, max: 1_000_000 },
+];
+
+// The hero's own numbers said as a supposition ("once I'm down to seventy
+// thousand", "it's not like I'm sitting on fifty k") are not a reading: a
+// stack, big-blind or place match with one of these words just before it in
+// the same sentence is left out.
+const HERO_FIELDS = new Set(["stack", "stackBB", "position"]);
+const SUPPOSING = /\b(?:if|once|when|till|until|unless|by the time|not like|would|could|should|wanna|want to|gonna)\b[^.!?]*$/;
+
+// "blinds are 1500 3000", "blinds 5 10", "1500 3000 blinds": both blinds.
+const BLINDS = [
+ new RegExp(String.raw`\bblinds (?:are |at |now |of |going up to |are going up to |up to )?${N}(?: ?/ ?| and | to | )${N}\b`, "g"),
+ new RegExp(String.raw`\b${N}(?: ?/ ?| )${N} blinds\b`, "g"),
+];
+
+/** Every spoken poker stat in the cues, in time order. */
+export function pokerSpoken(cues: readonly Cue[]): SpokenReading[] {
+ if (!cues.length) return [];
+ const { text, pieces } = joined(cues);
+ const out: SpokenReading[] = [];
+ const at = (index: number) => pieceAt(pieces, index);
+ const words = (p: Piece) => String(cues[p.cue].text ?? "").replace(/\s+/g, " ").trim().slice(0, 160);
+ for (const rule of RULES) {
+ rule.re.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = rule.re.exec(text))) {
+ const v = Number(m[1]);
+ if (!Number.isFinite(v)) continue;
+ if (rule.min !== undefined && v < rule.min) continue;
+ if (rule.max !== undefined && v > rule.max) continue;
+ if (HERO_FIELDS.has(rule.field) && SUPPOSING.test(text.slice(Math.max(0, m.index - 40), m.index))) continue;
+ const p = at(m.index);
+ out.push({ t: p.t, field: rule.field, value: v, text: words(p) });
+ }
+ }
+ for (const re of BLINDS) {
+ re.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(text))) {
+ const sb = Number(m[1]);
+ const bb = Number(m[2]);
+ // A big blind is the small one's double (or so): anything else is two
+ // numbers that happen to sit beside "blinds".
+ if (!(sb > 0 && bb > sb && bb <= sb * 3)) continue;
+ const p = at(m.index);
+ out.push({ t: p.t, field: "bigBlind", value: bb, text: words(p) });
+ out.push({ t: p.t, field: "smallBlind", value: sb, text: words(p) });
+ }
+ }
+ out.sort((a, b) => a.t - b.t || a.field.localeCompare(b.field));
+ return scaleStacks(dedupe(out));
+}
+
+// The same field and value said again within 30 s is one reading.
+function dedupe(rs: SpokenReading[]): SpokenReading[] {
+ const out: SpokenReading[] = [];
+ for (const r of rs) {
+ if (out.some((o) => o.field === r.field && o.value === r.value && Math.abs(o.t - r.t) <= 30)) continue;
+ out.push(r);
+ }
+ return out;
+}
+
+// The magnitude of the average decides only whether a small stack is
+// thousands; a half hour away it still has the right number of digits.
+const AVERAGE_WINDOW_S = 1800;
+
+// "the average stack is three hundred seventy three thousand… I have two
+// hundred thirty three": a stack said under 1000 within half an hour of an
+// average said in the thousands, and within 50× of it once scaled, is
+// thousands too (marked `approx`). One still under 1000 with no such average
+// is left out: a tournament stack is rarely that small, and the number is
+// more likely something else.
+function scaleStacks(rs: SpokenReading[]): SpokenReading[] {
+ const out: SpokenReading[] = [];
+ for (const r of rs) {
+ if (r.field !== "stack" || r.value >= 1000) {
+ out.push(r);
+ continue;
+ }
+ const avg = rs
+ .filter((o) => o.field === "averageStack" && o.value >= 10_000 && Math.abs(o.t - r.t) <= AVERAGE_WINDOW_S)
+ .sort((a, b) => Math.abs(a.t - r.t) - Math.abs(b.t - r.t))[0];
+ const scaled = r.value * 1000;
+ if (avg && scaled >= avg.value / 50 && scaled <= avg.value * 50) out.push({ ...r, value: scaled, approx: true });
+ }
+ return out;
+}
diff --git a/common/lib/frames/profiles.ts b/common/lib/frames/profiles.ts
@@ -0,0 +1,21 @@
+// The frame scan's profiles (release 30, lane P): what a frame is read for.
+// Poker is the first; a profile is one entry here.
+
+import { POKER_PROFILE } from "./poker";
+import type { FrameProfile } from "./types";
+
+export const FRAME_PROFILES: Readonly<Record<string, FrameProfile<{ phase: string }>>> = {
+ poker: POKER_PROFILE as unknown as FrameProfile<{ phase: string }>,
+};
+
+export const FRAME_PROFILE_IDS = Object.keys(FRAME_PROFILES);
+
+export function isFrameProfile(v: unknown): v is string {
+ return typeof v === "string" && Object.prototype.hasOwnProperty.call(FRAME_PROFILES, v);
+}
+
+export function frameProfile(id: string): FrameProfile<{ phase: string }> {
+ const p = FRAME_PROFILES[id];
+ if (!p) throw new Error(`"${id}" is not a frame-scan profile (${FRAME_PROFILE_IDS.join(", ")})`);
+ return p;
+}
diff --git a/common/lib/frames/sample-server.ts b/common/lib/frames/sample-server.ts
@@ -0,0 +1,236 @@
+// Sampling a saved video into frames (release 30, lane P): ONE ffmpeg per
+// batch of the stream (half an hour by default), never one process per frame.
+// Each batch writes its frames as JPEGs scaled to the profile's width and, on
+// the same decode, a tiny grey thumbnail per frame on stdout for the dHash.
+//
+// By default only the KEYFRAMES are decoded (`-skip_frame nokey`): a 4-hour
+// 1080p stream decodes in a minute or two instead of half an hour, and a
+// frame's picture is then the keyframe nearest its grid time — at most a
+// keyframe interval away (two seconds or so on a stream). `t` is always the
+// grid time in SOURCE seconds, so clips cut from it line up within that.
+//
+// The cache is a directory of JPEGs plus `index.json` (the grid, the width and
+// each frame's hash). A re-run reuses every frame the index already has on the
+// same grid and width. Server-only (node:child_process, node:fs).
+
+import { spawn } from "node:child_process";
+import { mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
+import path from "node:path";
+import { writeJsonAtomic } from "../jsonFile-server";
+import { hashesOf, THUMB_H, THUMB_W } from "./dhash";
+import type { FrameRef } from "./types";
+
+export const FRAME_INDEX_FILE = "index.json";
+export const DEFAULT_BATCH_SECONDS = 1800;
+
+export type FrameIndex = {
+ everySeconds: number;
+ width: number;
+ keyframesOnly: boolean;
+ // The part of the picture kept, as fractions of it: [x, y, w, h]; absent = all of it.
+ crop?: Crop;
+ frames: FrameRef[];
+};
+
+/** A region of the picture as fractions of its width and height: [x, y, w, h]. */
+export type Crop = [number, number, number, number];
+
+/** Whether a crop is four fractions that stay inside the picture. */
+export function isCrop(v: unknown): v is Crop {
+ return (
+ Array.isArray(v) &&
+ v.length === 4 &&
+ v.every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1) &&
+ v[2] > 0.05 &&
+ v[3] > 0.05 &&
+ v[0] + v[2] <= 1.0001 &&
+ v[1] + v[3] <= 1.0001
+ );
+}
+
+const sameCrop = (a?: Crop, b?: Crop) => (!a && !b) || (!!a && !!b && a.every((v, i) => Math.abs(v - b[i]) < 1e-6));
+
+/** A grid time as the frame's file name: `t000012340.jpg` (centiseconds). */
+export const frameFileOf = (t: number) => `t${String(Math.round(t * 100)).padStart(9, "0")}.jpg`;
+
+/** The grid: from, from+N, … below `to`, rounded to the centisecond. */
+export function gridOf(from: number, to: number, every: number): number[] {
+ const out: number[] = [];
+ if (!(every > 0) || !(to > from)) return out;
+ for (let k = 0; ; k++) {
+ const t = Math.round((from + k * every) * 100) / 100;
+ if (t >= to) break;
+ out.push(t);
+ }
+ return out;
+}
+
+/** The batches a grid is sampled in: [from, to) windows of at most `seconds`, on grid points. */
+export function batchesOf(grid: readonly number[], every: number, seconds = DEFAULT_BATCH_SECONDS): number[][] {
+ const per = Math.max(1, Math.floor(seconds / every));
+ const out: number[][] = [];
+ for (let i = 0; i < grid.length; i += per) out.push(grid.slice(i, i + per));
+ return out;
+}
+
+export async function readFrameIndex(dir: string): Promise<FrameIndex | null> {
+ try {
+ const v = JSON.parse(await readFile(path.join(dir, FRAME_INDEX_FILE), "utf8")) as FrameIndex;
+ return v && Array.isArray(v.frames) && typeof v.everySeconds === "number" && typeof v.width === "number" ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function probeDuration(file: string, ffprobe = "ffprobe"): Promise<number | null> {
+ const out = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", file]).catch(() => null);
+ const d = out ? Number(out.stdout.toString("utf8").trim()) : NaN;
+ return Number.isFinite(d) && d > 0 ? d : null;
+}
+
+function runCapture(cmd: string, args: string[], signal?: AbortSignal): Promise<{ stdout: Buffer; stderr: string }> {
+ return new Promise((resolve, reject) => {
+ const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], signal });
+ const out: Buffer[] = [];
+ let err = "";
+ p.stdout.on("data", (c: Buffer) => out.push(c));
+ p.stderr.on("data", (c: Buffer) => {
+ err += c.toString("utf8");
+ if (err.length > 20_000) err = err.slice(-10_000);
+ });
+ p.on("error", reject);
+ p.on("close", (code) => {
+ if (code === 0) resolve({ stdout: Buffer.concat(out), stderr: err });
+ else reject(new Error(`${cmd} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`));
+ });
+ });
+}
+
+/** The ffmpeg arguments for one batch (exported for the test). */
+export function batchArgs(o: { source: string; start: number; seconds: number; every: number; width: number; outPattern: string; keyframesOnly: boolean; crop?: Crop }): string[] {
+ // The crop comes after the sampling (it then runs on one frame in N) and
+ // before both the JPEG and the thumbnail, so a webcam or an overlay beside
+ // the region does not make two frames of one picture differ.
+ const crop = o.crop ? `,crop=trunc(iw*${o.crop[2]}/2)*2:trunc(ih*${o.crop[3]}/2)*2:trunc(iw*${o.crop[0]}):trunc(ih*${o.crop[1]})` : "";
+ return [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostdin",
+ ...(o.keyframesOnly ? ["-skip_frame", "nokey"] : []),
+ "-ss",
+ String(o.start),
+ "-t",
+ String(o.seconds),
+ "-i",
+ o.source,
+ "-filter_complex",
+ `[0:v]fps=1/${o.every}:round=near${crop},split=2[a][b];[a]scale=${o.width}:-2:flags=area[big];[b]scale=${THUMB_W}:${THUMB_H}:flags=area,format=gray[small]`,
+ "-map",
+ "[big]",
+ "-q:v",
+ "3",
+ "-start_number",
+ "0",
+ o.outPattern,
+ "-map",
+ "[small]",
+ "-f",
+ "rawvideo",
+ "pipe:1",
+ ];
+}
+
+/**
+ * Sample `[from, to)` of `source` every `every` seconds into `dir`. Frames the
+ * index already has (same grid step, width and decode mode) are kept and not
+ * decoded again; a batch with any frame missing is decoded whole. Answers the
+ * index, every frame of the range in order.
+ */
+export async function sampleFrames(o: {
+ source: string;
+ dir: string;
+ from: number;
+ to: number;
+ every: number;
+ width: number;
+ keyframesOnly?: boolean;
+ crop?: Crop;
+ batchSeconds?: number;
+ ffmpeg?: string;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ onBatch?: (done: number, total: number) => void;
+}): Promise<FrameIndex> {
+ const keyframesOnly = o.keyframesOnly ?? true;
+ await mkdir(o.dir, { recursive: true });
+ const prev = await readFrameIndex(o.dir);
+ const same = prev && prev.everySeconds === o.every && prev.width === o.width && prev.keyframesOnly === keyframesOnly && sameCrop(prev.crop, o.crop);
+ const have = new Map<number, FrameRef>();
+ if (same) {
+ const files = new Set(await readdir(o.dir).catch(() => [] as string[]));
+ for (const f of prev!.frames) if (files.has(f.file)) have.set(f.t, f);
+ }
+ const grid = gridOf(o.from, o.to, o.every);
+ const batches = batchesOf(grid, o.every, o.batchSeconds);
+ const index: FrameIndex = { everySeconds: o.every, width: o.width, keyframesOnly, ...(o.crop ? { crop: o.crop } : {}), frames: [] };
+ // Frames outside this run's range stay in the index.
+ const keepOutside = same ? prev!.frames.filter((f) => (f.t < o.from || f.t >= o.to) && have.has(f.t)) : [];
+ let done = 0;
+ for (const batch of batches) {
+ if (o.signal?.aborted) throw new Error("cancelled");
+ if (batch.every((t) => have.has(t))) {
+ for (const t of batch) index.frames.push(have.get(t)!);
+ o.onBatch?.(++done, batches.length);
+ continue;
+ }
+ const start = batch[0];
+ const seconds = Math.round((batch[batch.length - 1] - start + o.every) * 100) / 100;
+ const tmp = path.join(o.dir, `.batch-${process.pid}-${Math.round(start * 100)}`);
+ await rm(tmp, { recursive: true, force: true });
+ await mkdir(tmp, { recursive: true });
+ try {
+ const { stdout } = await runCapture(
+ o.ffmpeg ?? "ffmpeg",
+ batchArgs({ source: o.source, start, seconds, every: o.every, width: o.width, outPattern: path.join(tmp, "%06d.jpg"), keyframesOnly, ...(o.crop ? { crop: o.crop } : {}) }),
+ o.signal,
+ );
+ const hashes = hashesOf(stdout);
+ const written = (await readdir(tmp)).filter((f) => /^\d{6}\.jpg$/.test(f)).sort();
+ const n = Math.min(batch.length, hashes.length, written.length);
+ for (let k = 0; k < n; k++) {
+ const t = batch[k];
+ const file = frameFileOf(t);
+ await rename(path.join(tmp, written[k]), path.join(o.dir, file));
+ index.frames.push({ t, file, hash: hashes[k] });
+ }
+ if (n < batch.length) o.onLog?.(`frames ${batch[0]}–${batch[batch.length - 1]} s: ${n} of ${batch.length} decoded (the stream ends or has no picture there)`);
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+ o.onBatch?.(++done, batches.length);
+ // The index after every batch: a cut run keeps what it decoded.
+ await writeIndex(o.dir, index, keepOutside);
+ }
+ await writeIndex(o.dir, index, keepOutside);
+ return index;
+}
+
+async function writeIndex(dir: string, index: FrameIndex, outside: FrameRef[]): Promise<void> {
+ const frames = [...outside, ...index.frames].sort((a, b) => a.t - b.t);
+ const seen = new Set<number>();
+ await writeJsonAtomic(path.join(dir, FRAME_INDEX_FILE), { ...index, frames: frames.filter((f) => (seen.has(f.t) ? false : (seen.add(f.t), true))) }, { indent: 0 });
+}
+
+/** The cache's size on disk, and remove it. */
+export async function frameCacheBytes(dir: string): Promise<number> {
+ let total = 0;
+ for (const f of await readdir(dir).catch(() => [] as string[])) total += (await stat(path.join(dir, f)).catch(() => null))?.size ?? 0;
+ return total;
+}
+
+export async function removeFrameCache(dir: string): Promise<boolean> {
+ const there = await stat(dir).then(() => true, () => false);
+ if (there) await rm(dir, { recursive: true, force: true });
+ return there;
+}
diff --git a/common/lib/frames/scan.test.ts b/common/lib/frames/scan.test.ts
@@ -0,0 +1,300 @@
+// The frame scan end to end over a synthetic stream (ffmpeg-made, in a temp
+// dir) and the fake model servers: sampling, duplicates, the reads with real
+// JPEGs as image blocks, the cap, resume, the derivation. No real model.
+
+import { test, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { errorTurn, imagesOf, startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../testing/llm/fakeAnthropic.mjs";
+import { imagesOf as ollamaImagesOf, jsonReply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs";
+import { makeSyntheticPokerStream, pokerTruthAt, SPOKEN_CUES } from "../../testing/frames/syntheticPoker.mjs";
+import { duplicatesOf } from "./dhash";
+import { batchArgs, batchesOf, gridOf, readFrameIndex, sampleFrames } from "./sample-server";
+import { claudeImageTokens, jpegSize, runFrameScan } from "./scan";
+import type { FrameScanRecord } from "../frameScan-server";
+
+let dir = "";
+let video = "";
+
+before(async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), "frame-scan-"));
+ video = (await makeSyntheticPokerStream(dir)).file;
+});
+after(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+// The fake model: each ask's frame times from its text, each frame read as the
+// synthetic client shows it at that time.
+const timesOf = (body: { messages: { content: unknown }[] }): number[] => {
+ const c = body.messages[0].content;
+ const text = typeof c === "string" ? c : (c as { type: string; text?: string }[]).filter((b) => b.type === "text").map((b) => b.text).join("");
+ return [...text.matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2]));
+};
+const truthTurn = (body: any) => toolTurn("answer", { frames: timesOf(body).map((t, i) => ({ frame: i + 1, ...pokerTruthAt(t) })) });
+
+function memoryStore() {
+ let rec: FrameScanRecord | null = null;
+ let writes = 0;
+ return {
+ load: async () => rec,
+ write: async (r: FrameScanRecord) => {
+ rec = JSON.parse(JSON.stringify(r));
+ writes++;
+ },
+ get: () => rec,
+ writes: () => writes,
+ };
+}
+
+test("gridOf and batchesOf: grid times in source seconds, batches on the grid", () => {
+ assert.deepEqual(gridOf(5, 40, 10), [5, 15, 25, 35]);
+ assert.deepEqual(gridOf(0, 0, 10), []);
+ assert.deepEqual(batchesOf([0, 10, 20, 30, 40], 10, 20), [[0, 10], [20, 30], [40]]);
+ const args = batchArgs({ source: "in.mp4", start: 30, seconds: 60, every: 10, width: 1280, outPattern: "o/%06d.jpg", keyframesOnly: true });
+ assert.ok(args.includes("nokey"));
+ assert.ok(args.join(" ").includes("fps=1/10"));
+ assert.equal(args.indexOf("-ss") < args.indexOf("-i"), true);
+});
+
+test("claudeImageTokens and jpegSize", () => {
+ assert.equal(claudeImageTokens(1280, 720), 1229);
+ assert.ok(claudeImageTokens(3840, 2160) <= 1534);
+ assert.equal(jpegSize(Buffer.from("not a jpeg")), null);
+});
+
+test("sampleFrames: one ffmpeg a batch, JPEGs at the profile's width, a hash each; a re-run decodes nothing", async () => {
+ const cache = path.join(dir, "cache-sample");
+ const idx = await sampleFrames({ source: video, dir: cache, from: 0, to: 210, every: 10, width: 640, batchSeconds: 100 });
+ assert.equal(idx.frames.length, 21);
+ assert.deepEqual(idx.frames.slice(0, 3).map((f) => f.t), [0, 10, 20]);
+ const files = (await readdir(cache)).filter((f) => f.endsWith(".jpg"));
+ assert.equal(files.length, 21);
+ // Static stretches hash alike; a change of picture does not.
+ const dup = duplicatesOf(idx.frames.map((f) => f.hash), { maxBits: 2, rereadEvery: 6 });
+ assert.equal(dup[1], 0); // lobby 10 s = lobby 0 s
+ assert.equal(dup[3], null); // the table at 30 s
+ assert.equal(dup[4], 3);
+ assert.equal(dup[9], null); // the double-up at 90 s
+ const kept = dup.filter((d) => d === null).length;
+ assert.ok(kept >= 7 && kept <= 10, `kept ${kept}`);
+ // The index is reused: a re-run with an ffmpeg that cannot run still answers.
+ const again = await sampleFrames({ source: video, dir: cache, from: 0, to: 210, every: 10, width: 640, batchSeconds: 100, ffmpeg: "/nonexistent/ffmpeg" });
+ assert.deepEqual(again.frames, idx.frames);
+ assert.equal((await readFrameIndex(cache))?.frames.length, 21);
+});
+
+test("a scan on the API: images as JPEG blocks, readings, the derived timeline, the spend; a re-run asks nothing", async () => {
+ const api: FakeAnthropic = await startFakeAnthropic({ turns: Array.from({ length: 20 }, () => truthTurn) });
+ const store = memoryStore();
+ const cache = path.join(dir, "cache-api");
+ const logs: string[] = [];
+ try {
+ const opts = {
+ profile: "poker",
+ source: video,
+ cacheDir: cache,
+ everySeconds: 10,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ maxUsd: 1,
+ cues: SPOKEN_CUES,
+ hints: { hero: "SynthHero" },
+ onLog: (l: string) => logs.push(l),
+ now: () => new Date("2026-10-15T12:00:00Z"),
+ };
+ const out = await runFrameScan(opts, store);
+ const r = out.record;
+ // Every ask carried real 1280-px JPEGs, at most four, with the frame times in its text.
+ assert.ok(api.requests.length >= 2);
+ for (const body of api.requests) {
+ const imgs = imagesOf(body);
+ assert.ok(imgs.length >= 1 && imgs.length <= 4);
+ for (const im of imgs) {
+ assert.equal(im.mediaType, "image/jpeg");
+ assert.equal(im.width, 1280);
+ }
+ assert.equal(imgs.length, timesOf(body).length);
+ assert.match(JSON.stringify(body.system), /SynthHero/);
+ }
+ assert.equal(r.sampling.frames, 21);
+ assert.equal(r.readings.length, r.sampling.kept);
+ assert.equal(r.sampling.skippedDuplicates, 21 - r.sampling.kept);
+ assert.equal(r.duplicates.length, r.sampling.skippedDuplicates);
+ assert.equal(out.run.read, r.sampling.kept);
+ assert.equal(out.run.failed, 0);
+ assert.ok(out.run.costUsd > 0 && r.costUsd === out.run.costUsd);
+ assert.equal(r.model.model, "claude-haiku-4-5");
+ assert.equal(r.source.savedVideo, path.basename(video));
+
+ const d = r.derived;
+ const events = d.events.map((e) => [e.t, e.kind]);
+ assert.deepEqual(events.filter(([, k]) => k !== "buy-in"), [
+ [90, "double-up"],
+ [120, "big-loss"],
+ [120, "final-table"],
+ [180, "bust"],
+ [180, "eliminated"],
+ ]);
+ assert.ok(events.some(([t, k]) => k === "buy-in" && t === 35));
+ assert.equal(d.tournaments.length, 1);
+ assert.equal(d.tournaments[0].name, "Synthetic Cup");
+ assert.deepEqual(d.tournaments[0].series.stack, [[30, 20000], [90, 41000], [120, 9000], [180, 0]]);
+ assert.deepEqual(d.segments.map((s) => s.phase), ["lobby", "table", "break", "table", "lobby"]);
+ // The spoken "four players left" against the frames' 9: flagged, not trusted.
+ assert.deepEqual(d.flags.map((f) => [f.t, f.field, f.spoken, f.frame]), [[125, "playersLeft", 4, 9]]);
+
+ // Again: every kept frame is read, so nothing is asked.
+ const asked = api.requests.length;
+ const again = await runFrameScan(opts, store);
+ assert.equal(api.requests.length, asked);
+ assert.equal(again.run.read, 0);
+ assert.equal(again.record.runs.length, 2);
+ assert.equal(again.record.costUsd, out.run.costUsd);
+ } finally {
+ await api.close();
+ }
+});
+
+test("the cap stops a scan before an ask that would pass it; the next run reads the rest", async () => {
+ const api = await startFakeAnthropic({ turns: Array.from({ length: 20 }, () => truthTurn) });
+ const store = memoryStore();
+ try {
+ const base = {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-cap"),
+ everySeconds: 10,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ framesPerAsk: 1,
+ };
+ // About one ask's worth (~$0.0035 estimated a frame on Haiku 4.5).
+ const first = await runFrameScan({ ...base, maxUsd: 0.005 }, store);
+ assert.equal(first.run.stopped, "cap");
+ assert.ok(first.run.read >= 1 && first.run.read < first.record.sampling.kept, `read ${first.run.read}`);
+ assert.ok(first.run.costUsd <= 0.005);
+ const second = await runFrameScan({ ...base, maxUsd: 1 }, store);
+ assert.equal(second.run.stopped, undefined);
+ assert.equal(first.run.read + second.run.read, second.record.sampling.kept);
+ } finally {
+ await api.close();
+ }
+});
+
+test("three failed asks in a row stop a scan, and nothing is recorded as read", async () => {
+ const api = await startFakeAnthropic({ turns: [errorTurn(400, "invalid_request_error", "this model does not take images"), errorTurn(400, "invalid_request_error", "no"), errorTurn(400, "invalid_request_error", "no")] });
+ const store = memoryStore();
+ try {
+ const out = await runFrameScan(
+ {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-err"),
+ everySeconds: 30,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, maxRetries: 0 } },
+ maxUsd: 1,
+ framesPerAsk: 1,
+ },
+ store,
+ );
+ assert.equal(out.run.stopped, "errors");
+ assert.equal(out.run.failed, 3);
+ assert.equal(out.record.readings.length, 0);
+ } finally {
+ await api.close();
+ }
+});
+
+test("a scan on a local vision model: one frame an ask, as `images`, under the prompt cap", async () => {
+ const ol = await startFakeOllama({
+ models: ["qwen2.5vl:7b"],
+ turns: Array.from({ length: 30 }, () => (body: any) => {
+ const t = [...String(body.messages[1].content).matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2]));
+ return jsonReply({ frames: t.map((x, i) => ({ frame: i + 1, ...pokerTruthAt(x) })) });
+ }),
+ });
+ const store = memoryStore();
+ try {
+ const out = await runFrameScan(
+ {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-local"),
+ everySeconds: 20,
+ model: "qwen2.5vl:7b",
+ llm: { ollama: { baseUrl: ol.url } },
+ maxUsd: Number.POSITIVE_INFINITY,
+ },
+ store,
+ );
+ assert.equal(out.run.failed, 0);
+ assert.equal(out.run.costUsd, 0);
+ assert.equal(ol.requests.length, out.run.read);
+ for (const body of ol.requests) {
+ const imgs = ollamaImagesOf(body);
+ assert.equal(imgs.length, 1);
+ assert.equal(imgs[0].width, 1280);
+ }
+ assert.ok(out.record.derived.events.some((e) => e.kind === "bust"));
+ } finally {
+ await ol.close();
+ }
+});
+
+test("maxFrames bounds a scan's range and says so", async () => {
+ const api = await startFakeAnthropic({ turns: Array.from({ length: 5 }, () => truthTurn) });
+ try {
+ const out = await runFrameScan(
+ {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-max"),
+ everySeconds: 10,
+ maxFrames: 5,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ maxUsd: 1,
+ },
+ memoryStore(),
+ );
+ assert.equal(out.run.stopped, "maxFrames");
+ assert.equal(out.record.sampling.frames, 5);
+ assert.equal(out.record.sampling.to, 50);
+ } finally {
+ await api.close();
+ }
+});
+
+test("fresh: every frame read again (another model), the runs and the spend kept; a crop is hashed and read", async () => {
+ const api = await startFakeAnthropic({ turns: Array.from({ length: 30 }, () => truthTurn) });
+ const store = memoryStore();
+ try {
+ const base = {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-fresh"),
+ everySeconds: 30,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ maxUsd: 1,
+ crop: [0, 0.25, 1, 0.5] as [number, number, number, number],
+ };
+ const first = await runFrameScan(base, store);
+ const asked = api.requests.length;
+ assert.ok(first.run.read > 0);
+ for (const body of api.requests) for (const im of imagesOf(body)) assert.deepEqual([im.width, im.height], [1280, 360]);
+ assert.deepEqual(first.record.sampling.crop, [0, 0.25, 1, 0.5]);
+ const again = await runFrameScan({ ...base, model: "claude-haiku-5-5", fresh: true }, store);
+ assert.equal(again.run.read, first.run.read);
+ assert.ok(api.requests.length > asked);
+ assert.equal(again.record.runs.length, 2);
+ assert.ok(again.record.costUsd > first.record.costUsd);
+ assert.equal(again.record.model.model, "claude-haiku-5-5");
+ } finally {
+ await api.close();
+ }
+});
diff --git a/common/lib/frames/scan.ts b/common/lib/frames/scan.ts
@@ -0,0 +1,282 @@
+// One frame scan (release 30, lane P): sample, skip duplicates, read the kept
+// frames through a profile, derive, write the sidecar. Every effect is a dep,
+// so the tests run it over synthetic frames and the fake model servers.
+//
+// RESUMABLE: a reading already in the sidecar (by its grid time) is never
+// asked again, and a frame that duplicates a read frame is not asked at all.
+// The sidecar is written every few asks, so a cancelled or cut job keeps what
+// it read; the next run asks only the rest.
+//
+// CAPPED: the run stops before an ask that could take its spend past
+// `maxUsd` (an estimate per ask, from the frames' sizes and the model's
+// price), and again on the meter's own count. Three failed asks in a row stop
+// it too (a key refused, a model that cannot read images).
+
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { Meter, structuredAnswer, priceOf, providerOf, type AnswerImage, type LlmConfig } from "../llm";
+import { CancelledError } from "../llm/anthropic";
+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 type { FrameScanRecord, FrameScanRun } from "../frameScan-server";
+
+export const DEFAULT_EVERY_SECONDS = 10;
+export const DEFAULT_MAX_FRAMES = 5000;
+// Asks between two writes of the sidecar.
+const WRITE_EVERY_ASKS = 5;
+const MAX_FAILED_IN_A_ROW = 3;
+
+export type FrameScanOptions = {
+ profile: string;
+ // The saved container (absolute) and its basename for the record.
+ source: string;
+ cacheDir: string;
+ everySeconds?: number;
+ from?: number;
+ to?: number;
+ maxFrames?: number;
+ model: string;
+ llm: LlmConfig;
+ maxUsd: number;
+ hints?: { hero?: string };
+ framesPerAsk?: number;
+ keyframesOnly?: boolean;
+ // The part of the picture the model reads (the poker client, not the webcam
+ // beside it): fractions [x, y, w, h]. The hash is taken of it too.
+ crop?: Crop;
+ cues?: Cue[];
+ // Read every frame again (another model, another prompt): the readings and
+ // duplicates so far are dropped; the runs and the spend are kept.
+ fresh?: boolean;
+ jobId?: string;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ onProgress?: (p: { phase: "sample" | "read"; current: number; total: number }) => void;
+ now?: () => Date;
+};
+
+export type FrameScanDeps = {
+ load: () => Promise<FrameScanRecord | null>;
+ write: (r: FrameScanRecord) => Promise<void>;
+ sample?: typeof sampleFrames;
+ probe?: (file: string) => Promise<number | null>;
+ readImage?: (file: string) => Promise<Buffer>;
+ // One structured ask (default: structuredAnswer).
+ ask?: typeof structuredAnswer;
+};
+
+export type FrameScanOutcome = { record: FrameScanRecord; run: FrameScanRun; spent: ReturnType<Meter["summary"]> };
+
+// What one image costs on the Claude API, in input tokens: (w·h)/750 after the
+// API's own downscale (long edge ≤ 1568, ≤ ~1.15 MP). A JPEG's size is read
+// from its SOF marker; an unreadable one is priced at the most an image costs.
+export function claudeImageTokens(w: number, h: number): number {
+ let s = 1;
+ if (Math.max(w, h) > 1568) s = 1568 / Math.max(w, h);
+ if (w * h * s * s > 1_150_000) s = Math.sqrt(1_150_000 / (w * h));
+ return Math.ceil((w * s * h * s) / 750);
+}
+
+export function jpegSize(buf: Buffer): { w: number; h: number } | null {
+ if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null;
+ let i = 2;
+ while (i + 9 < buf.length) {
+ if (buf[i] !== 0xff) return null;
+ const marker = buf[i + 1];
+ const len = buf.readUInt16BE(i + 2);
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
+ return { h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) };
+ }
+ i += 2 + len;
+ }
+ return null;
+}
+
+// An ask's cost estimate before it is sent: its images, the prompt text and
+// a reading's worth of output per frame.
+function askEstimateUsd(model: string, images: Buffer[], promptChars: number): number {
+ if (providerOf(model) !== "api") return 0;
+ const p = priceOf(model);
+ const imgTokens = images.reduce((n, b) => {
+ const s = jpegSize(b);
+ return n + (s ? claudeImageTokens(s.w, s.h) : 1600);
+ }, 0);
+ const input = imgTokens + Math.ceil(promptChars / 3.5);
+ const output = 250 * images.length;
+ return (input * p.input + output * p.output) / 1e6;
+}
+
+export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Promise<FrameScanOutcome> {
+ const log = o.onLog ?? (() => {});
+ const profile = frameProfile(o.profile);
+ const every = o.everySeconds ?? DEFAULT_EVERY_SECONDS;
+ const route: "api" | "local" = providerOf(o.model);
+ const now = o.now ?? (() => new Date());
+ const meter = new Meter({ maxUsd: o.maxUsd });
+ const prev = await deps.load();
+
+ const duration = await (deps.probe ?? probeDuration)(o.source);
+ const from = Math.max(0, o.from ?? 0);
+ let to = o.to ?? duration ?? 0;
+ if (duration !== null) to = Math.min(to, duration);
+ if (!(to > from)) throw new Error(`nothing to scan: ${from}–${to} s${duration === null ? " (the video's length could not be read)" : ""}`);
+ const maxFrames = o.maxFrames ?? DEFAULT_MAX_FRAMES;
+ let stopped: FrameScanRun["stopped"];
+ if ((to - from) / every > maxFrames) {
+ to = Math.round((from + maxFrames * every) * 100) / 100;
+ stopped = "maxFrames";
+ log(`the range would be over ${maxFrames} frames: scanning ${from}–${to} s only (raise maxFrames or everySeconds)`);
+ }
+
+ // The crop is the scan's: a re-run that names none keeps the last run's.
+ const crop = o.crop ?? prev?.sampling.crop;
+ log(`sampling ${from}–${Math.round(to)} s every ${every} s at ${profile.width} px wide${crop ? `, cropped to [${crop.join(", ")}]` : ""} into ${o.cacheDir}`);
+ const index: FrameIndex = await (deps.sample ?? sampleFrames)({
+ source: o.source,
+ dir: o.cacheDir,
+ from,
+ to,
+ every,
+ width: profile.width,
+ keyframesOnly: o.keyframesOnly ?? true,
+ ...(crop ? { crop } : {}),
+ signal: o.signal,
+ onLog: log,
+ onBatch: (d, n) => o.onProgress?.({ phase: "sample", current: d, total: n }),
+ });
+ const frames = index.frames.filter((f) => f.t >= from && f.t < to).sort((a, b) => a.t - b.t);
+ const dup = duplicatesOf(frames.map((f) => f.hash), { maxBits: profile.dupMaxBits, rereadEvery: profile.rereadEvery });
+ const kept = frames.filter((_, i) => dup[i] === null);
+ const readings = new Map<number, FrameScanRecord["readings"][number]>();
+ if (!o.fresh) for (const r of prev?.readings ?? []) readings.set(r.t, r);
+ const todo = kept.filter((f) => !readings.has(f.t));
+ log(`${frames.length} frames, ${kept.length} kept (${frames.length - kept.length} duplicates), ${kept.length - todo.length} already read, ${todo.length} to read on ${o.model}`);
+
+ const per = Math.max(1, o.framesPerAsk ?? profile.framesPerAsk[route]);
+ // The hints are the scan's: a re-run without them keeps the last run's.
+ const hints = { ...(prev?.hints ?? {}), ...(o.hints ?? {}) };
+ const system = profile.system(hints);
+ const ask = deps.ask ?? structuredAnswer;
+ const readImage = deps.readImage ?? ((f: string) => readFile(f));
+ let read = 0;
+ let failed = 0;
+ let inARow = 0;
+ let asks = 0;
+
+ // A duplicate frame shows what the frame it duplicates shows: [t, that t].
+ // Kept with the record (the cache is evictable), merged over runs.
+ const dupPairs = new Map<number, number>();
+ if (!o.fresh) for (const [t, src] of prev?.duplicates ?? []) if (t < from || t >= to) dupPairs.set(t, src);
+ frames.forEach((f, i) => {
+ const d = dup[i];
+ if (d !== null) dupPairs.set(f.t, frames[d].t);
+ });
+ 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 spoken = o.cues ? profile.spoken(o.cues) : (prev?.spoken ?? []);
+ return {
+ format: FRAME_SCAN_FORMAT,
+ version: 1,
+ profile: profile.id,
+ source: { savedVideo: path.basename(o.source), durationSeconds: duration },
+ sampling: {
+ everySeconds: every,
+ from,
+ to,
+ width: profile.width,
+ keyframesOnly: index.keyframesOnly,
+ ...(index.crop ? { crop: index.crop } : {}),
+ frames: frames.length,
+ kept: kept.length,
+ skippedDuplicates: frames.length - kept.length,
+ },
+ model: { route, model: o.model, promptVersion: profile.promptVersion },
+ ...(hints.hero ? { hints } : {}),
+ 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]),
+ spoken,
+ derived: profile.derive(expanded as never, spoken, { everySeconds: every, ...(duration !== null ? { durationSeconds: duration } : {}), ...(hints.hero ? { hero: hints.hero } : {}) }),
+ updatedAt: now().toISOString(),
+ };
+ };
+ const runOf = (): FrameScanRun => ({
+ at: now().toISOString(),
+ ...(o.jobId ? { jobId: o.jobId } : {}),
+ model: o.model,
+ route,
+ frames: frames.length,
+ read,
+ failed,
+ costUsd: Math.round(meter.usd * 10_000) / 10_000,
+ ...(stopped ? { stopped } : {}),
+ });
+
+ for (let i = 0; i < todo.length; i += per) {
+ if (o.signal?.aborted) {
+ stopped = "cancelled";
+ break;
+ }
+ const chunk: FrameRef[] = todo.slice(i, i + per);
+ const bufs = await Promise.all(chunk.map((f) => readImage(path.join(o.cacheDir, f.file))));
+ const user = profile.user(chunk);
+ const schema = profile.schema(chunk.length);
+ const estimate = askEstimateUsd(o.model, bufs, system.length + user.length + JSON.stringify(schema).length);
+ if (meter.over() || (route === "api" && meter.usd + estimate > o.maxUsd)) {
+ stopped = "cap";
+ log(`stopping at the cap: $${meter.usd.toFixed(4)} spent of $${o.maxUsd} (the next ask is ~$${estimate.toFixed(4)})`);
+ break;
+ }
+ const images: AnswerImage[] = bufs.map((b) => ({ mediaType: "image/jpeg", data: b.toString("base64") }));
+ let answer: unknown;
+ try {
+ answer = await ask({ llm: o.llm, model: o.model, system, user, schema, images, meter, signal: o.signal, maxTokens: 400 * chunk.length + 400 });
+ } catch (err) {
+ if (o.signal?.aborted || err instanceof CancelledError) {
+ stopped = "cancelled";
+ break;
+ }
+ failed += chunk.length;
+ inARow++;
+ log(`ask failed for ${chunk.map((f) => f.t).join(", ")} s: ${(err as Error).message}`);
+ if (err instanceof PromptTooLargeError || inARow >= MAX_FAILED_IN_A_ROW) {
+ stopped = "errors";
+ log(`stopping: ${inARow} failed asks in a row`);
+ break;
+ }
+ continue;
+ }
+ inARow = 0;
+ const list = answer && typeof answer === "object" && Array.isArray((answer as { frames?: unknown }).frames) ? ((answer as { frames: unknown[] }).frames) : [];
+ chunk.forEach((f, k) => {
+ // The answer's own frame numbers when it gives them, else its order.
+ const raw = list.find((x) => x && typeof x === "object" && (x as { frame?: unknown }).frame === k + 1) ?? (list.length === chunk.length ? list[k] : undefined);
+ const reading = profile.coerce(raw);
+ if (!reading) {
+ failed++;
+ return;
+ }
+ readings.set(f.t, { t: f.t, ...reading });
+ read++;
+ });
+ asks++;
+ o.onProgress?.({ phase: "read", current: Math.min(todo.length, i + per), total: todo.length });
+ if (asks % WRITE_EVERY_ASKS === 0) await deps.write(record());
+ }
+ const out = record();
+ await deps.write(out);
+ const run = out.runs[out.runs.length - 1];
+ log(`read ${read} frames (${failed} failed), $${meter.usd.toFixed(4)} this run${stopped ? `, stopped: ${stopped}` : ""}; ${out.derived.events.length} events, ${out.derived.tournaments.length} tournament(s)`);
+ return { record: out, run, spent: meter.summary() };
+}
diff --git a/common/lib/frames/series.test.ts b/common/lib/frames/series.test.ts
@@ -0,0 +1,38 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { agree, changesOnly, dropMisreads, nearest, ratioOf } from "./series";
+
+const P = (pairs: [number, number][]) => pairs.map(([t, v]) => ({ t, v }));
+
+test("ratioOf and agree", () => {
+ assert.equal(ratioOf(10, 20), 2);
+ assert.equal(ratioOf(0, 0), 1);
+ assert.equal(ratioOf(0, 5), Infinity);
+ assert.ok(agree(9, 7, { ratio: 1.1, absolute: 2 }));
+ assert.ok(!agree(9, 6, { ratio: 1.1, absolute: 2 }));
+});
+
+test("a single frame that jumps 100× is a misread when its neighbours agree", () => {
+ const { kept, dropped } = dropMisreads(P([[0, 20000], [10, 2000000], [20, 21000]]), { ratio: 3 });
+ assert.deepEqual(dropped, P([[10, 2000000]]));
+ assert.equal(kept.length, 2);
+});
+
+test("a real change is followed by points that agree with it, so it stays", () => {
+ const { dropped } = dropMisreads(P([[0, 20000], [10, 41000], [20, 41000], [30, 40500]]), { ratio: 1.5 });
+ assert.deepEqual(dropped, []);
+});
+
+test("an end point that disagrees hard with the two next to it is a misread", () => {
+ assert.deepEqual(dropMisreads(P([[0, 5], [10, 500], [20, 510]]), { ratio: 2 }).dropped, P([[0, 5]]));
+ assert.deepEqual(dropMisreads(P([[0, 500], [10, 510], [20, 50000]]), { ratio: 2 }).dropped, P([[20, 50000]]));
+ // A series that ends at 0 ended there (a bust); a first reading before a change stays.
+ assert.deepEqual(dropMisreads(P([[0, 500], [10, 510], [20, 0]]), { ratio: 2 }).dropped, []);
+ assert.deepEqual(dropMisreads(P([[0, 20000], [10, 41000], [20, 41000]]), { ratio: 1.5 }).dropped, []);
+});
+
+test("changesOnly and nearest", () => {
+ assert.deepEqual(changesOnly(P([[0, 1], [10, 1], [20, 2], [30, 2], [40, 1]])), P([[0, 1], [20, 2], [40, 1]]));
+ 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);
+});
diff --git a/common/lib/frames/series.ts b/common/lib/frames/series.ts
@@ -0,0 +1,83 @@
+// Series helpers every profile's derivation shares (release 30, lane P). Pure.
+//
+// A model reading a frame misreads now and then — a digit dropped, a
+// neighbour's stack taken for the hero's — and a single frame that jumps
+// 100× is a misread, not a double-up. The rule is AGREEMENT OF NEIGHBOURS: a
+// point is set aside when the points either side of it agree with each other
+// and it agrees with neither. A real change is followed by points that agree
+// with it, so it stays.
+
+export type Pt = { t: number; v: number };
+
+/** How far apart two values are, as a ratio ≥ 1 (Infinity when one is 0 and the other is not). */
+export function ratioOf(a: number, b: number): number {
+ if (a === b) return 1;
+ if (a <= 0 || b <= 0) return Infinity;
+ return a > b ? a / b : b / a;
+}
+
+export type AgreeRule = { ratio: number; absolute?: number };
+
+/** Whether two values agree under a rule: within `ratio`, or within `absolute` of each other. */
+export function agree(a: number, b: number, rule: AgreeRule): boolean {
+ if (rule.absolute !== undefined && Math.abs(a - b) <= rule.absolute) return true;
+ return ratioOf(a, b) <= rule.ratio;
+}
+
+/**
+ * The points with misreads set aside: `kept` and `dropped`. A middle point is
+ * dropped when its two neighbours agree and it agrees with neither; an end
+ * point when the next two (or last two) agree and it disagrees with both by
+ * the square of the ratio — but a last point of 0 is kept (a series that ends
+ * at 0 ended there).
+ * One pass over the original points, so two misreads in a row both stay (the
+ * rule cannot tell them from a change) — that is what `flags` and the review
+ * are for.
+ */
+export function dropMisreads(points: readonly Pt[], rule: AgreeRule): { kept: Pt[]; dropped: Pt[] } {
+ const kept: Pt[] = [];
+ const dropped: Pt[] = [];
+ const n = points.length;
+ for (let i = 0; i < n; i++) {
+ const p = points[i];
+ let a: Pt | undefined;
+ let b: Pt | undefined;
+ if (i > 0 && i < n - 1) {
+ a = points[i - 1];
+ b = points[i + 1];
+ } else if (i === 0 && n >= 3) {
+ a = points[1];
+ b = points[2];
+ } else if (i === n - 1 && n >= 3 && p.v !== 0) {
+ // The last point has nothing after it to agree with, so it is judged by
+ // the two before it — except a 0, which ends a series for real (a bust).
+ a = points[n - 2];
+ b = points[n - 3];
+ }
+ // An end point has only one side to be judged by, so it must disagree
+ // twice as hard (the square of the ratio): a first reading followed by a
+ // real change is kept, a 100× outlier is not.
+ const end = i === 0 || i === n - 1;
+ const r: AgreeRule = end ? { ratio: rule.ratio * rule.ratio, ...(rule.absolute !== undefined ? { absolute: rule.absolute * 2 } : {}) } : rule;
+ if (a && b && agree(a.v, b.v, rule) && !agree(p.v, a.v, r) && !agree(p.v, b.v, r)) dropped.push(p);
+ else kept.push(p);
+ }
+ return { kept, dropped };
+}
+
+/** Collapse a series to its changes: a point equal to the one before it is left out. */
+export function changesOnly(points: readonly Pt[]): Pt[] {
+ const out: Pt[] = [];
+ for (const p of points) if (!out.length || out[out.length - 1].v !== p.v) out.push(p);
+ return out;
+}
+
+/** The point nearest `t` within `window` seconds, or null. */
+export function nearest(points: readonly Pt[], t: number, window: number): Pt | null {
+ let best: Pt | null = null;
+ for (const p of points) {
+ const d = Math.abs(p.t - t);
+ if (d <= window && (!best || d < Math.abs(best.t - t))) best = p;
+ }
+ return best;
+}
diff --git a/common/lib/frames/types.ts b/common/lib/frames/types.ts
@@ -0,0 +1,104 @@
+// The frame scan's shapes (release 30, lane P): a stream sampled into frames,
+// each kept frame read by a vision model through a PROFILE (poker first), the
+// readings and the transcript's spoken numbers turned into series, events and
+// segments by pure code. Pure: types and small helpers only.
+
+/** One sampled frame in the cache. `t` is the SOURCE second (the grid time). */
+export type FrameRef = {
+ t: number;
+ // The JPEG's basename in the cache dir.
+ file: string;
+ // dHash of the frame's grey thumbnail (hex).
+ hash: string;
+};
+
+/** A cue, as `transcript.cues.json` holds it. */
+export type Cue = { start: number; end: number; text: string };
+
+/** A number the streamer SAID, read out of the cues by pure code. */
+export type SpokenReading = {
+ t: number;
+ field: string;
+ value: number;
+ // The cue's words (trimmed), so a reader can see why.
+ text: string;
+ // Scaled by a rule (a stack said without "thousand" beside an average said with it).
+ approx?: boolean;
+};
+
+/** A series point: [t, value], or [t, value, "spoken"] when a spoken number filled it. */
+export type SeriesPoint = [number, number] | [number, number, "spoken"];
+
+export type DerivedEvent = {
+ t: number;
+ kind: string;
+ detail: string;
+ // Where it came from: the model's reading of a frame, the series, the
+ // client's log as a frame showed it, or the transcript.
+ source: "frame" | "series" | "log" | "spoken";
+ tournament?: string;
+};
+
+export type DerivedSegment = { from: number; to: number; phase: string; tournament?: string };
+
+/** A frame reading and a spoken number that disagree (never silently trusted). */
+export type DerivedFlag = { t: number; field: string; spoken: number; frame: number; frameT: number; tournament?: string };
+
+export type DerivedTournament = {
+ key: string;
+ name?: string;
+ from: number;
+ to: number;
+ series: Record<string, SeriesPoint[]>;
+ // The last values seen: buy-in, prize, field size.
+ facts: Record<string, number>;
+};
+
+export type Derived = {
+ tournaments: DerivedTournament[];
+ events: DerivedEvent[];
+ segments: DerivedSegment[];
+ flags: DerivedFlag[];
+ // Readings the smoothing set aside as misreads, by field.
+ misreads: { t: number; field: string; value: number }[];
+};
+
+/** A profile: what a frame is read for, and how readings become a timeline. */
+export type FrameProfile<R extends { phase: string }> = {
+ id: string;
+ // Bumped whenever the prompt or the schema changes.
+ promptVersion: number;
+ // The width frames are scaled to before a model reads them.
+ width: number;
+ // dHash bits two frames may differ by and still be one picture.
+ dupMaxBits: number;
+ // A duplicate run is read again every this many frames (a number on a
+ // static screen can change too small for the hash to see).
+ rereadEvery: number;
+ // Frames per ask on the API and on a local model.
+ framesPerAsk: { api: number; local: number };
+ system(hints: { hero?: string }): string;
+ user(frames: { t: number }[]): string;
+ // The answer's schema for an ask of `n` frames: `{ frames: [reading…] }`.
+ schema(n: number): object;
+ // A model's reading cleaned to the profile's shape; null when it is not one.
+ coerce(raw: unknown): R | null;
+ spoken(cues: Cue[]): SpokenReading[];
+ derive(readings: (R & { t: number })[], spoken: SpokenReading[], o: { everySeconds: number; durationSeconds?: number; hero?: string }): Derived;
+};
+
+export const FRAME_SCAN_FORMAT = "archilyzer-frame-scan";
+
+/** "1:02:03" / "4:05". */
+export function clock(t: number): string {
+ const s = Math.max(0, Math.round(t));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+}
+
+/** 12400 → "12,400"; 1.5 → "1.5". */
+export function fmtNum(v: number): string {
+ return Number.isInteger(v) ? v.toLocaleString("en-US") : String(Math.round(v * 10) / 10);
+}
diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -129,3 +129,25 @@ test("generation settings: the verdict bench's bar (fractions, clamped) and the
assert.deepEqual(sanitizeGeneration({ verdicts: { window: { mode: "turn", seconds: 30.4 } } }).verdicts.window, { mode: "turn", seconds: 30 });
assert.deepEqual(sanitizeGeneration({ verdicts: { window: { mode: "sentence", seconds: 900 } } }).verdicts.window, { mode: "seconds", seconds: 60 });
});
+
+test("the frame scan (release 30): its own route and settings; a file from before keeps its preset", () => {
+ assert.ok((GENERATION_TASKS as readonly string[]).includes("frames"));
+ assert.equal(GENERATION_PRESETS.code.frames, "code");
+ assert.equal(GENERATION_PRESETS.balanced.frames, "api");
+ assert.equal(GENERATION_PRESETS.local.frames, "local");
+ assert.deepEqual(DEFAULT_GENERATION_SETTINGS.frames, { apiModel: "claude-haiku-4-5", localModel: "qwen2.5vl:7b", maxUsd: 5, everySeconds: 10 });
+ assert.deepEqual(sanitizeGeneration({}).frames, DEFAULT_GENERATION_SETTINGS.frames);
+ assert.deepEqual(sanitizeGeneration({ frames: { apiModel: "claude-haiku-5-5", localModel: "bad model", maxUsd: -1, everySeconds: 0.5 } }).frames, {
+ apiModel: "claude-haiku-5-5",
+ localModel: "qwen2.5vl:7b",
+ maxUsd: 5,
+ everySeconds: 10,
+ });
+ // A file that routes every task but frames keeps its preset.
+ for (const p of ["code", "balanced", "api", "local"] as const) {
+ const routes = Object.fromEntries(GENERATION_TASKS.filter((t) => t !== "frames").map((t) => [t, GENERATION_PRESETS[p][t]]));
+ const g = sanitizeGeneration({ routes });
+ assert.equal(g.preset, p);
+ assert.equal(g.routes.frames, GENERATION_PRESETS[p].frames);
+ }
+});
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -21,7 +21,10 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri
// `verdicts` (release 29 M8): verdict proposals for a fact-check's unruled
// claims — no iteration, no step: a sidecar beside the article, and only on a
// model in `verdicts.models` (the bench's bar).
-export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts"] as const;
+// `frames` (release 30, lane P): a frame scan's readings of a saved stream's
+// frames by a vision model — no article, no iteration: a sidecar beside the
+// video. `api` or `local`; `code` = none unless the job names a model.
+export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames"] as const;
export type GenerationTask = (typeof GENERATION_TASKS)[number];
// The tasks every settings file since release 27 S6 routes.
const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"];
@@ -33,10 +36,12 @@ export type GenerationRoute = (typeof GENERATION_ROUTES)[number];
const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }) as const;
export const GENERATION_PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code" },
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code" },
+ // A frame scan is on the API in `balanced`: a vision model is not a given
+ // on the local card, and the cheap model's reads cost cents an hour.
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local" },
} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>;
export type GenerationPreset = keyof typeof GENERATION_PRESETS;
export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[];
@@ -82,6 +87,11 @@ export type GenerationTriage = {
};
export const DEFAULT_GENERATION_TRIAGE: GenerationTriage = { model: "local", strong: 1, weak: 3, maxEscalationsPerDay: 3, maxCandidates: 40 };
+// The frame scan (release 30, lane P): the vision models each route reads
+// frames on, a scan's default spend cap and its default sampling step.
+export type GenerationFrames = { apiModel: string; localModel: string; maxUsd: number; everySeconds: number };
+export const DEFAULT_GENERATION_FRAMES: GenerationFrames = { apiModel: "claude-haiku-4-5", localModel: "qwen2.5vl:7b", maxUsd: 5, everySeconds: 10 };
+
export type GenerationSettings = {
preset: GenerationPreset | "custom";
routes: GenerationRoutes;
@@ -98,6 +108,7 @@ export type GenerationSettings = {
cut: GenerationCut;
verdicts: GenerationVerdicts;
triage: GenerationTriage;
+ frames: GenerationFrames;
};
export const DEFAULT_GENERATION_VERDICT_WINDOW: GenerationVerdictWindow = { mode: "seconds", seconds: 60 };
@@ -123,6 +134,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
cut: { maxClips: 20 },
verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [], window: { ...DEFAULT_GENERATION_VERDICT_WINDOW } },
triage: { ...DEFAULT_GENERATION_TRIAGE },
+ frames: { ...DEFAULT_GENERATION_FRAMES },
};
export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
@@ -147,6 +159,14 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
"The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`.",
triage:
"Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below).",
+ frames: "The frame scan (`pnpm ops frame-scan`): the vision model each route reads a saved stream's frames on, a scan's spend cap and its sampling step (below).",
+};
+
+export const GENERATION_FRAMES_FIELD_DOCS: FieldDocs<GenerationFrames> = {
+ apiModel: "The Claude model a scan on the `api` route reads frames with (it must take images). Haiku: about a cent a hundred frames.",
+ localModel: "The ollama vision model a scan on the `local` route reads frames with (one frame an ask, under the 8k prompt cap; through the GPU arbiter on `draft:local`).",
+ maxUsd: "A scan's API cap when the job names none (at most `caps.max`): the scan stops before an ask that would pass it, and keeps what it read.",
+ everySeconds: "Seconds between two sampled frames when the job names none (1 to 600).",
};
export const GENERATION_TRIAGE_FIELD_DOCS: FieldDocs<GenerationTriage> = {
@@ -193,6 +213,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
threads: "A media draft: the cut's threads and each clip's thread.",
youtube: "A media draft: the YouTube title and description.",
social: "A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code.",
+ frames:
+ "A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model.",
verdicts:
"Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.",
};
@@ -314,6 +336,18 @@ export function sanitizeGeneration(value: unknown): GenerationSettings {
},
verdicts: sanitizeVerdicts(r.verdicts),
triage: sanitizeTriage(r.triage),
+ frames: sanitizeFrames(r.frames, model),
+ };
+}
+
+function sanitizeFrames(v: unknown, model: (v: unknown, fallback: string) => string): GenerationFrames {
+ const d = DEFAULT_GENERATION_FRAMES;
+ const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+ return {
+ apiModel: model(o.apiModel, d.apiModel),
+ localModel: model(o.localModel, d.localModel),
+ maxUsd: usd(o.maxUsd, d.maxUsd, 1000),
+ everySeconds: typeof o.everySeconds === "number" && Number.isFinite(o.everySeconds) && o.everySeconds >= 1 && o.everySeconds <= 600 ? Math.round(o.everySeconds * 100) / 100 : d.everySeconds,
};
}
diff --git a/common/lib/llm/ollama.ts b/common/lib/llm/ollama.ts
@@ -46,9 +46,22 @@ export function estimateTokens(v: unknown): number {
return Math.ceil(s.length / CHARS_PER_TOKEN);
}
-// What a chat request is estimated at: its messages, tools and format.
+// An image a vision model reads (release 30, the frame scan) is counted at a
+// fixed cost, not by its base64: a 1280-px frame is about a thousand tokens to
+// a vision model, and its base64 would read as tens of thousands.
+export const IMAGE_TOKEN_ESTIMATE = 1_200;
+
+// What a chat request is estimated at: its messages (each message's `images`
+// at IMAGE_TOKEN_ESTIMATE apiece), tools and format.
export function promptEstimate(req: { messages: unknown[]; tools?: unknown[]; format?: unknown }): number {
- return estimateTokens([req.messages, req.tools ?? null, req.format ?? null]);
+ let images = 0;
+ const messages = req.messages.map((m) => {
+ if (!m || typeof m !== "object" || !Array.isArray((m as { images?: unknown }).images)) return m;
+ const { images: imgs, ...rest } = m as { images: unknown[] };
+ images += imgs.length;
+ return rest;
+ });
+ return estimateTokens([messages, req.tools ?? null, req.format ?? null]) + images * IMAGE_TOKEN_ESTIMATE;
}
export function numCtxOf(cfg: OllamaConfig): number {
diff --git a/common/lib/llm/structured.test.ts b/common/lib/llm/structured.test.ts
@@ -9,8 +9,9 @@ import {
textBlock,
} from "../../testing/llm/fakeAnthropic.mjs";
import { faultReply, jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs";
-import { closeSchema, structuredAnswer, StructuredAnswerError } from "./structured";
-import { PromptTooLargeError } from "./ollama";
+import { closeSchema, structuredAnswer, structuredPromptEstimate, StructuredAnswerError } from "./structured";
+import { IMAGE_TOKEN_ESTIMATE, PromptTooLargeError, promptEstimate } from "./ollama";
+import { execFileSync } from "node:child_process";
import { Meter } from "./meter";
import { providerOf } from "./config";
@@ -170,3 +171,56 @@ test("a provider without its config is a clear error", async () => {
await assert.rejects(structuredAnswer({ llm: {}, model: "qwen3:8b", system: "s", user: "u", schema }), /no ollama URL/);
await assert.rejects(structuredAnswer({ llm: {}, model: "claude-sonnet-5", system: "s", user: "u", schema }), /no API config/);
});
+
+// ─── Images (release 30, the frame scan) ───
+
+const tinyJpeg = () =>
+ execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=blue:s=64x36:d=1", "-frames:v", "1", "-c:v", "mjpeg", "-f", "image2pipe", "pipe:1"]).toString("base64");
+
+test("Claude with images: image blocks before the text, in the one user turn", async () => {
+ const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["chips"] })])] });
+ try {
+ const data = tinyJpeg();
+ const out = await structuredAnswer<{ terms: string[] }>({
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ model: "claude-haiku-4-5",
+ system: "Read the frames.",
+ user: "Two frames.",
+ schema,
+ images: [
+ { mediaType: "image/jpeg", data },
+ { mediaType: "image/jpeg", data },
+ ],
+ });
+ assert.deepEqual(out, { terms: ["chips"] });
+ const content = api.requests[0].messages[0].content;
+ assert.deepEqual(content.map((b: { type: string }) => b.type), ["image", "image", "text"]);
+ assert.equal(content[0].source.media_type, "image/jpeg");
+ assert.equal(content[2].text, "Two frames.");
+ } finally {
+ await api.close();
+ }
+});
+
+test("ollama with images: the user message's images, counted at a fixed cost in the estimate", async () => {
+ const ol = await startFakeOllama({ models: ["qwen2.5vl:7b"], turns: [jsonReply({ terms: ["stack"] })] });
+ try {
+ const data = tinyJpeg();
+ const out = await structuredAnswer<{ terms: string[] }>({
+ llm: { ollama: { baseUrl: ol.url } },
+ model: "qwen2.5vl:7b",
+ system: "Read the frame.",
+ user: "One frame.",
+ schema,
+ images: [{ mediaType: "image/jpeg", data }],
+ });
+ assert.deepEqual(out, { terms: ["stack"] });
+ assert.deepEqual(ol.requests[0].messages[1].images, [data]);
+ const est = structuredPromptEstimate({ system: "s", user: "u", schema, images: [{ mediaType: "image/jpeg", data }] });
+ assert.equal(est, structuredPromptEstimate({ system: "s", user: "u", schema }) + IMAGE_TOKEN_ESTIMATE);
+ // The base64 itself is never counted as text.
+ assert.ok(promptEstimate({ messages: [{ role: "user", content: "u", images: ["A".repeat(100_000)] }] }) < 2000);
+ } finally {
+ await ol.close();
+ }
+});
diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts
@@ -47,12 +47,18 @@ export function closeSchema<T>(schema: T): T {
return out as T;
}
+// An image the model reads with the question (release 30, the frame scan):
+// base64 bytes and their media type. Claude gets image blocks before the
+// text; ollama gets the user message's `images`.
+export type AnswerImage = { mediaType: "image/jpeg" | "image/png"; data: string };
+
type Opts = {
llm: LlmConfig;
model: string;
system: string;
user: string;
schema: object;
+ images?: AnswerImage[];
meter?: Meter;
signal?: AbortSignal;
maxTokens?: number;
@@ -81,8 +87,17 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean):
input_schema: strict ? closeSchema(o.schema) : o.schema,
...(strict ? { strict: true } : {}),
};
+ const text = strict ? `${o.user}\n\n${ASK}` : o.user;
let messages: { role: string; content: string | ContentBlock[] }[] = [
- { role: "user", content: strict ? `${o.user}\n\n${ASK}` : o.user },
+ {
+ role: "user",
+ content: o.images?.length
+ ? [
+ ...o.images.map((img) => ({ type: "image", source: { type: "base64", media_type: img.mediaType, data: img.data } })),
+ { type: "text", text },
+ ]
+ : text,
+ },
];
let res: MessagesResponse | undefined;
for (let attempt = 0; attempt < (strict ? 2 : 1); attempt++) {
@@ -108,11 +123,11 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean):
// What a local structuredAnswer's prompt is estimated at — the very request
// localAnswer sends (its messages and its format), counted as ollamaChat
// counts it against the cap (release 28 Q3: a caller fits its text first).
-export function structuredPromptEstimate(o: { system: string; user: string; schema: object }): number {
+export function structuredPromptEstimate(o: { system: string; user: string; schema: object; images?: AnswerImage[] }): number {
return promptEstimate({
messages: [
{ role: "system", content: o.system },
- { role: "user", content: o.user },
+ { role: "user", content: o.user, ...(o.images?.length ? { images: o.images.map((i) => i.data) } : {}) },
],
format: o.schema,
});
@@ -128,7 +143,7 @@ async function localAnswer<T>(o: Opts): Promise<T> {
model: o.model,
messages: [
{ role: "system", content: o.system },
- { role: "user", content: o.user },
+ { role: "user", content: o.user, ...(o.images?.length ? { images: o.images.map((i) => i.data) } : {}) },
],
format: o.schema,
signal: o.signal,
diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts
@@ -59,6 +59,12 @@ export const TTS_QUEUE = "tts";
// together (their sweeps would race the day's cap).
export const REPORT_TICK_QUEUE = "report-tick";
+// A frame scan on the Claude API (release 30, controller/frameScan.ts): one
+// at a time machine-wide, apart from the generation lanes — a 4-hour stream's
+// decode and its reads must not hold `draft:api` for an article's draft. A scan
+// on a LOCAL vision model goes on `draft:local` instead (the GPU's lane).
+export const FRAME_SCAN_QUEUE = "frames";
+
// Per-channel queue for channel-local bookkeeping jobs (clean/clear/verify).
export function channelQueueKey(slug: string): string {
return `channel:${slug}`;
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -31,6 +31,7 @@ import {
GENERATION_ROUTES_FIELD_DOCS,
GENERATION_CUT_FIELD_DOCS,
GENERATION_TRIAGE_FIELD_DOCS,
+ GENERATION_FRAMES_FIELD_DOCS,
GENERATION_SETTINGS_FIELD_DOCS,
GENERATION_WEB_FIELD_DOCS,
GENERATION_VERDICTS_FIELD_DOCS,
@@ -305,6 +306,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "generation.verdicts.bar", docs: GENERATION_VERDICT_BAR_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.bar) },
{ path: "generation.verdicts.window", docs: GENERATION_VERDICT_WINDOW_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.window) },
{ path: "generation.triage", docs: GENERATION_TRIAGE_FIELD_DOCS, defaults: fromObject(d.generation.triage) },
+ { path: "generation.frames", docs: GENERATION_FRAMES_FIELD_DOCS, defaults: fromObject(d.generation.frames) },
],
};
}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -92,6 +92,7 @@ export {
GENERATION_VERDICT_BAR_FIELD_DOCS,
GENERATION_VERDICT_WINDOW_FIELD_DOCS,
GENERATION_TRIAGE_FIELD_DOCS,
+ GENERATION_FRAMES_FIELD_DOCS,
type GenerationSettings,
} from "./generationSettings";
export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -10,6 +10,7 @@ import "./archiveOrg-server";
import "./attribution-server";
import "./diarization-server";
import "./digest-server";
+import "./frameScan-server";
import "./metadataHistory-server";
import "./transcriptPin-server";
import "./wayback-server";
@@ -44,7 +45,7 @@ async function scratch(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), "sidecar-"));
}
-test("every declared sidecar filename escapes SUB_FILE_RE, and all twelve are declared", () => {
+test("every declared sidecar filename escapes SUB_FILE_RE, and all fourteen are declared", () => {
assert.deepEqual([...SIDECAR_FILENAMES].sort(), [
"ai-digest.json",
"ai-digest.overrides.json",
@@ -55,6 +56,7 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all twelve are de
"do-not-clean.json",
"download-outcome.json",
"exclude-truncated-check.json",
+ "frame-scan.poker.json",
"metadata.history.json",
"transcribe-outcome.json",
"transcript-pin.json",
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -13,6 +13,8 @@ transcript, channel or person goes in these fixtures, ever.
| --- | --- |
| `llm/fakeAnthropic.mjs` | A fake Messages API: scripted turns (`textTurn`, `toolTurn`, `pauseTurn`, `webSearchBlocks`, `thinkingBlock`, `errorTurn`, or a function of the request). It enforces the Sonnet 5.5 400s (temperature, forced `tool_choice`, `thinking: disabled`), signs thinking blocks so an edited history is refused, needs `x-api-key` = `FAKE_KEY`, and estimates usage, cache reads included. |
| `llm/fakeOllama.mjs` | A fake ollama: `/api/chat` with `format` or tools, the 8k prompt cap and the 12k `num_ctx` cap as 400s, `stream: true` refused, `faultReply()` (`done: false`), the `keep_alive: 0` unload, `/api/tags`, `/api/ps`. |
+| images (both fakes) | Release 30: the fake Anthropic takes `image` blocks (base64 JPEG/PNG/GIF/WebP whose bytes match the media type, in a user turn — else a 400) and counts each at (w·h)/750 tokens; the fake ollama takes a message's `images` (base64 images — else a 400), each counted at `IMAGE_TOKENS` (1200) against the cap. `imagesOf(body)` (each) decodes a request's images with their sizes, for a scripted answer or an assertion. |
+| `frames/syntheticPoker.mjs` | Release 30: a synthetic poker stream for the frame scan — `makeSyntheticPokerStream(dir)` paints a fake client (a lobby, a table whose numbers change, a break, a bust) with ffmpeg's `color` + `drawtext` into a 210-s H.264 file (a keyframe every 2 s); `pokerTruthAt(t)` is what it shows at `t` (a fake model's answer), `SPOKEN_CUES` what the streamer "said" (two numbers that agree with the frames, one that does not). Nothing real: no stream, no client, no frames from the corpus. |
| `draft/corpus.mjs` | Two channels of recordings with cues (`CHANNELS`), posts (`POSTS`), `ORIGIN`, `momentHref`, `postHref`, `cuesOf`, `recordOf`, and `writeDraftCorpus(dir)` — a composed public dir for the MCP's `--local`. |
| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one), `two-line` (a finding's quote and link on the lines under its claim), `fragment` (verbatim quotes that stop mid-thought — on a function word, or under four words — and one whole sentence). |
| `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. |
diff --git a/common/testing/fakes.test.ts b/common/testing/fakes.test.ts
@@ -19,8 +19,11 @@ import {
turn,
textBlock,
webSearchBlocks,
+ imagesOf,
+ imageTokens,
} from "./llm/fakeAnthropic.mjs";
-import { faultReply, jsonReply, startFakeOllama, toolCallsReply } from "./llm/fakeOllama.mjs";
+import { faultReply, jsonReply, startFakeOllama, toolCallsReply, imagesOf as ollamaImagesOf } from "./llm/fakeOllama.mjs";
+import { execFileSync } from "node:child_process";
import { CHANNELS, cuesOf, writeDraftCorpus } from "./draft/corpus.mjs";
import { DERIVED, SWEEPS, convertFixture, deriveFixture } from "./draft/derive";
import { validateReport } from "../lib/report/validate";
@@ -181,6 +184,49 @@ test("fake ollama: format and tool replies, the 8k and num_ctx caps, stream refu
}
});
+// ─── Images (release 30, the frame scan) ───
+
+// A tiny real JPEG and PNG, made by ffmpeg (no binary fixture in the tree).
+function tinyImage(kind: "mjpeg" | "png"): string {
+ return execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=red:s=64x36:d=1", "-frames:v", "1", "-c:v", kind, "-f", "image2pipe", "pipe:1"]).toString("base64");
+}
+
+test("fake Anthropic: an image block must be base64 of the type it names, in a user turn; usage counts it by size", async () => {
+ const jpeg = tinyImage("mjpeg");
+ const png = tinyImage("png");
+ const api = await startFakeAnthropic({ turns: [textTurn("ok")] });
+ try {
+ const img = (media_type: string, data: string) => ({ type: "image", source: { type: "base64", media_type, data } });
+ const ask = (content: unknown[], role = "user") => post(`${api.url}/v1/messages`, { model: "claude-haiku-4-5", max_tokens: 10, messages: [{ role, content }] }, auth);
+ assert.equal((await ask([img("image/jpeg", png)])).status, 400);
+ assert.equal((await ask([img("image/png", "not base64!")])).status, 400);
+ assert.equal((await ask([img("image/tiff", jpeg)])).status, 400);
+ const ok = await ask([img("image/jpeg", jpeg), { type: "text", text: "read it" }]);
+ assert.equal(ok.status, 200);
+ assert.ok(ok.json.usage.input_tokens >= imageTokens(64, 36) && ok.json.usage.input_tokens < 100, String(ok.json.usage.input_tokens));
+ assert.deepEqual(imagesOf(api.requests[api.requests.length - 1]).map((i) => [i.mediaType, i.width, i.height]), [["image/jpeg", 64, 36]]);
+ assert.equal(imageTokens(1280, 720), 1229);
+ } finally {
+ await api.close();
+ }
+});
+
+test("fake ollama: a message's images must be base64 images, each counted at a fixed cost against the cap", async () => {
+ const jpeg = tinyImage("mjpeg");
+ const ol = await startFakeOllama({ models: ["qwen2.5vl:7b"], turns: [jsonReply({ ok: true })] });
+ try {
+ const base = { model: "qwen2.5vl:7b", stream: false, messages: [{ role: "user", content: "read", images: [jpeg] }] };
+ assert.equal((await post(`${ol.url}/api/chat`, { ...base, messages: [{ role: "user", content: "read", images: ["!!"] }] })).status, 400);
+ assert.equal((await post(`${ol.url}/api/chat`, { ...base, messages: [{ role: "user", content: "read", images: Array(7).fill(jpeg) }] })).status, 400);
+ const ok = await post(`${ol.url}/api/chat`, base);
+ assert.equal(ok.status, 200);
+ assert.ok(ok.json.prompt_eval_count >= 1200 && ok.json.prompt_eval_count < 1300);
+ assert.equal(ollamaImagesOf(ol.requests[ol.requests.length - 1])[0].width, 64);
+ } finally {
+ await ol.close();
+ }
+});
+
// ─── Fixtures ───
test("fixtures: every sweep converts with no problems, and every report validates", async () => {
diff --git a/common/testing/frames/syntheticPoker.d.mts b/common/testing/frames/syntheticPoker.d.mts
@@ -0,0 +1,22 @@
+export const SYNTH_TOURNAMENT: string;
+export const SYNTH_DURATION: number;
+export const SYNTH_SPANS: {
+ from: number;
+ to: number;
+ phase: string;
+ tournament?: Record<string, unknown>;
+ hero?: Record<string, unknown>;
+ event?: string;
+}[];
+export function pokerTruthAt(t: number): {
+ phase: string;
+ tournament: Record<string, unknown>;
+ hero: Record<string, unknown>;
+ hand: Record<string, unknown>;
+ event: string | null;
+};
+export function makeSyntheticPokerStream(
+ dir: string,
+ o?: { name?: string; width?: number; height?: number; ffmpeg?: string },
+): Promise<{ file: string; duration: number }>;
+export const SPOKEN_CUES: { start: number; end: number; text: string }[];
diff --git a/common/testing/frames/syntheticPoker.mjs b/common/testing/frames/syntheticPoker.mjs
@@ -0,0 +1,99 @@
+// A synthetic poker stream for the frame scan's tests (release 30, lane P).
+// No real stream, no real poker client: ffmpeg's `color` source and
+// `drawtext` paint a fake client — a lobby, a table whose numbers change on a
+// schedule, a break screen, a bust — into a short H.264 file with a keyframe
+// every two seconds, so the scan's keyframe-only sampling has something to
+// find. `pokerTruthAt(t)` is what each moment shows, for the fake models'
+// answers, and `SPOKEN_CUES` the transcript the streamer "said".
+//
+// const { file, duration } = await makeSyntheticPokerStream(dir);
+// pokerTruthAt(95) → { phase: "table", tournament: {...}, hero: {...} }
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import path from "node:path";
+
+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.
+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: 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 } },
+];
+
+/** The reading a perfect model gives at `t` (the answer schema's shape, `frame` left to the caller). */
+export function pokerTruthAt(t) {
+ const s = SYNTH_SPANS.find((x) => t >= x.from && t < x.to) ?? SYNTH_SPANS[SYNTH_SPANS.length - 1];
+ return {
+ phase: s.phase,
+ tournament: s.tournament ? { ...s.tournament } : {},
+ hero: s.hero ? { ...s.hero } : {},
+ hand: {},
+ event: s.event ?? null,
+ };
+}
+
+// The line a span paints.
+function spanText(s) {
+ if (s.phase === "break") return "BREAK back in 5 minutes";
+ const t = s.tournament ?? {};
+ if (s.phase === "lobby") return `LOBBY ${t.name} Players ${t.playersLeft} of ${t.totalPlayers}`;
+ return `${t.name} Level ${t.level} Blinds ${t.smallBlind} ${t.bigBlind} Left ${t.playersLeft} of ${t.totalPlayers} Stack ${s.hero?.stack ?? ""}${s.event ? " ELIMINATED" : ""}`;
+}
+
+const COLORS = { lobby: "0x123456", table: "0x0b5d1e", break: "0x333333", other: "0x000000" };
+
+/** Write the stream into `dir`; answers its path and length. */
+export async function makeSyntheticPokerStream(dir, o = {}) {
+ const file = path.join(dir, o.name ?? "synthetic-poker.mp4");
+ const w = o.width ?? 1280;
+ const h = o.height ?? 720;
+ // One color source per span, concatenated, each with its own text.
+ const inputs = [];
+ const chains = [];
+ SYNTH_SPANS.forEach((s, i) => {
+ inputs.push("-f", "lavfi", "-i", `color=c=${COLORS[s.phase]}:s=${w}x${h}:r=2:d=${s.to - s.from}`);
+ chains.push(`[${i}:v]drawtext=text='${spanText(s)}':fontsize=36:fontcolor=white:x=40:y=${h / 2}[v${i}]`);
+ });
+ const concat = `${SYNTH_SPANS.map((_, i) => `[v${i}]`).join("")}concat=n=${SYNTH_SPANS.length}:v=1:a=0[out]`;
+ await run(o.ffmpeg ?? "ffmpeg", [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ ...inputs,
+ "-filter_complex",
+ `${chains.join(";")};${concat}`,
+ "-map",
+ "[out]",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "ultrafast",
+ "-g",
+ "4",
+ "-pix_fmt",
+ "yuv420p",
+ file,
+ ]);
+ return { file, duration: SYNTH_DURATION };
+}
+
+// What the streamer says over the synthetic stream: numbers in words, as an
+// ASR transcript writes them. Two agree with the client; the last does not
+// (the frames read 9 left there): a flag.
+export const SPOKEN_CUES = [
+ { start: 5, end: 9, text: "welcome back we're in the synthetic cup" },
+ { start: 31, end: 35, text: "eighty five players left and" },
+ { start: 35, end: 38, text: "the buy in is two hundred bucks" },
+ { start: 92, end: 96, text: "I have forty one thousand now" },
+ { start: 125, end: 130, text: "we're at the final table, there are four players left" },
+];
diff --git a/common/testing/llm/fakeAnthropic.d.mts b/common/testing/llm/fakeAnthropic.d.mts
@@ -33,3 +33,7 @@ export type FakeAnthropic = {
close(): Promise<void>;
};
export function startFakeAnthropic(opts?: { key?: string; strictModels?: string[]; turns?: FakeScripted[] }): Promise<FakeAnthropic>;
+export function imageSize(buf: Buffer): { width: number; height: number } | null;
+export function imageTokens(width: number, height: number): number;
+export function imagesOf(body: any): { mediaType: string; bytes: Buffer; width: number; height: number }[];
+export function imageProblem(body: any): string | null;
diff --git a/common/testing/llm/fakeAnthropic.mjs b/common/testing/llm/fakeAnthropic.mjs
@@ -14,6 +14,8 @@
// turn carrying thinking whose history was edited (or whose block was) is refused,
// so a client must keep history append-only once a thinking block appears;
// - `max_tokens` is required, and `model`, and a non-empty `messages`.
+// - an image block (release 30) is base64 of a JPEG/PNG/GIF/WebP whose bytes
+// match its media type, in a user turn; its usage is (w·h)/750 tokens.
// A missing or wrong `x-api-key` is a 401 authentication_error.
//
// A scripted turn is a response (helpers below), an error (`errorTurn`), or a
@@ -118,6 +120,94 @@ export function signatureProblem(body) {
return null;
}
+// ─── Images (release 30, the frame scan) ───
+
+// A base64 image's size from its bytes (JPEG SOF, PNG IHDR), or null.
+export function imageSize(buf) {
+ if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504e47) return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
+ if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null;
+ let i = 2;
+ while (i + 9 < buf.length) {
+ if (buf[i] !== 0xff) return null;
+ const m = buf[i + 1];
+ const len = buf.readUInt16BE(i + 2);
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };
+ i += 2 + len;
+ }
+ return null;
+}
+
+// What an image costs in input tokens: (w·h)/750 after the API's downscale
+// (long edge ≤ 1568, ≤ ~1.15 MP).
+export function imageTokens(width, height) {
+ let s = 1;
+ if (Math.max(width, height) > 1568) s = 1568 / Math.max(width, height);
+ if (width * height * s * s > 1_150_000) s = Math.sqrt(1_150_000 / (width * height));
+ return Math.ceil((width * s * height * s) / 750);
+}
+
+const IMAGE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
+
+// Every image block of a request's messages, decoded: {mediaType, bytes, width, height}.
+export function imagesOf(body) {
+ const out = [];
+ for (const m of Array.isArray(body?.messages) ? body.messages : []) {
+ if (!Array.isArray(m.content)) continue;
+ for (const b of m.content) {
+ if (b?.type !== "image") continue;
+ const bytes = Buffer.from(String(b.source?.data ?? ""), "base64");
+ out.push({ mediaType: b.source?.media_type, bytes, ...(imageSize(bytes) ?? { width: 0, height: 0 }) });
+ }
+ }
+ return out;
+}
+
+// An image block the real API refuses: not base64, an unknown media type, no
+// data, bytes that are not the image type named, or an image in an assistant turn.
+export function imageProblem(body) {
+ const msgs = Array.isArray(body.messages) ? body.messages : [];
+ for (let i = 0; i < msgs.length; i++) {
+ const m = msgs[i];
+ if (!Array.isArray(m.content)) continue;
+ for (let j = 0; j < m.content.length; j++) {
+ const b = m.content[j];
+ if (b?.type !== "image") continue;
+ const at = `messages.${i}.content.${j}`;
+ if (m.role !== "user") return `${at}: an image is only allowed in a user turn`;
+ const src = b.source ?? {};
+ if (src.type !== "base64") return `${at}.source.type: the fake takes base64 images only`;
+ if (!IMAGE_TYPES.includes(src.media_type)) return `${at}.source.media_type: ${src.media_type} is not an image type`;
+ if (typeof src.data !== "string" || !src.data || /[^A-Za-z0-9+/=]/.test(src.data)) return `${at}.source.data: not base64`;
+ const bytes = Buffer.from(src.data, "base64");
+ const size = imageSize(bytes);
+ const isPng = bytes.length > 4 && bytes.readUInt32BE(0) === 0x89504e47;
+ const isJpeg = bytes.length > 2 && bytes[0] === 0xff && bytes[1] === 0xd8;
+ if ((src.media_type === "image/jpeg" && !isJpeg) || (src.media_type === "image/png" && !isPng) || !size)
+ return `${at}: the image bytes are not a ${src.media_type}`;
+ }
+ }
+ return null;
+}
+
+// A request's messages with every image's data replaced by its token cost, for the usage estimate.
+function withoutImageData(messages) {
+ let tokens = 0;
+ const stripped = (messages ?? []).map((m) =>
+ Array.isArray(m.content)
+ ? {
+ ...m,
+ content: m.content.map((b) => {
+ if (b?.type !== "image") return b;
+ const size = imageSize(Buffer.from(String(b.source?.data ?? ""), "base64"));
+ tokens += size ? imageTokens(size.width, size.height) : 1600;
+ return { type: "image" };
+ }),
+ }
+ : m,
+ );
+ return { stripped, tokens };
+}
+
function requestProblem(body) {
if (!body || typeof body !== "object") return "body: not JSON";
if (!body.model) return "model: required";
@@ -163,7 +253,7 @@ export async function startFakeAnthropic(opts = {}) {
if (req.headers["x-api-key"] !== key) return apiError(res, 401, "authentication_error", "invalid x-api-key");
if (!req.headers["anthropic-version"])
return apiError(res, 400, "invalid_request_error", "anthropic-version: header required");
- const problem = requestProblem(body) ?? strictModelProblem(body, strictModels) ?? signatureProblem(body);
+ const problem = requestProblem(body) ?? strictModelProblem(body, strictModels) ?? signatureProblem(body) ?? imageProblem(body);
if (problem) return apiError(res, 400, "invalid_request_error", problem);
let next = script.shift();
@@ -184,8 +274,10 @@ export async function startFakeAnthropic(opts = {}) {
// (same system and tools, its messages a prefix of these) and writes the
// rest up to its last message.
const head = JSON.stringify([body.system ?? null, body.tools ?? null]);
- const total = tok([body.system ?? null, body.tools ?? null, body.messages]);
- const last = tok(body.messages[body.messages.length - 1]);
+ // An image counts at its token cost, not its base64.
+ const { stripped, tokens: imgTokens } = withoutImageData(body.messages);
+ const total = tok([body.system ?? null, body.tools ?? null, stripped]) + imgTokens;
+ const last = tok(stripped[stripped.length - 1]) + withoutImageData(body.messages.slice(-1)).tokens;
const cached = hasCacheControl(body);
let read = 0;
if (cached) {
diff --git a/common/testing/llm/fakeOllama.d.mts b/common/testing/llm/fakeOllama.d.mts
@@ -32,3 +32,6 @@ export function startFakeOllama(opts?: {
numCtxCap?: number;
turns?: OllamaScripted[];
}): Promise<FakeOllama>;
+export const IMAGE_TOKENS: number;
+export function imagesOf(body: any): { bytes: Buffer; width: number; height: number }[];
+export function imageProblem(body: any): string | null;
diff --git a/common/testing/llm/fakeOllama.mjs b/common/testing/llm/fakeOllama.mjs
@@ -14,17 +14,58 @@
// card fails its test instead. `stream: true` is refused: the clients here read
// one JSON answer. A scripted `faultReply()` answers `done: false` — what a GPU
// fault looks like — which a client must read as a failure, not an answer.
+// A message's `images` (release 30) must be base64 of an image; each counts
+// IMAGE_TOKENS against the cap.
//
// A scripted turn is a reply (helpers below) or a function (body, ctx) → reply.
// When the script runs out the server answers 500 "fake: script exhausted".
import http from "node:http";
+import { imageSize } from "./fakeAnthropic.mjs";
export const PROMPT_CAP_TOKENS = 8192;
export const NUM_CTX_CAP = 12288;
const tok = (v) => Math.ceil(JSON.stringify(v ?? "").length / 4);
+// A vision model's image (release 30): counted at a fixed cost, not its base64.
+export const IMAGE_TOKENS = 1200;
+
+// Every message's `images`, decoded: {bytes, width, height}.
+export function imagesOf(body) {
+ const out = [];
+ for (const m of Array.isArray(body?.messages) ? body.messages : [])
+ for (const d of Array.isArray(m.images) ? m.images : []) {
+ const bytes = Buffer.from(String(d), "base64");
+ out.push({ bytes, ...(imageSize(bytes) ?? { width: 0, height: 0 }) });
+ }
+ return out;
+}
+
+// What ollama refuses: an `images` entry that is not base64 of an image.
+export function imageProblem(body) {
+ for (const [i, m] of (Array.isArray(body?.messages) ? body.messages : []).entries()) {
+ if (m.images === undefined) continue;
+ if (!Array.isArray(m.images)) return `messages.${i}.images: not a list`;
+ for (const d of m.images) {
+ if (typeof d !== "string" || !d || /[^A-Za-z0-9+/=]/.test(d)) return `messages.${i}.images: not base64`;
+ if (!imageSize(Buffer.from(d, "base64"))) return `messages.${i}.images: not an image`;
+ }
+ }
+ return null;
+}
+
+const promptTokensOf = (body) => {
+ let images = 0;
+ const messages = (body.messages ?? []).map((m) => {
+ if (!Array.isArray(m?.images)) return m;
+ images += m.images.length;
+ const { images: _drop, ...rest } = m;
+ return rest;
+ });
+ return tok([messages, body.tools ?? null, body.format ?? null]) + images * IMAGE_TOKENS;
+};
+
export const reply = (content, extra = {}) => ({ message: { role: "assistant", content }, done: true, ...extra });
// A `format`-schema answer: the content is the JSON text.
@@ -91,7 +132,9 @@ export async function startFakeOllama(opts = {}) {
const numCtx = body.options?.num_ctx;
if (typeof numCtx === "number" && numCtx > numCtxCap)
return send(res, 400, { error: `fake: num_ctx ${numCtx} is over the ${numCtxCap} cap` });
- const promptTokens = tok([body.messages, body.tools ?? null, body.format ?? null]);
+ const bad = imageProblem(body);
+ if (bad) return send(res, 400, { error: `fake: ${bad}` });
+ const promptTokens = promptTokensOf(body);
if (promptTokens > promptCap)
return send(res, 400, { error: `fake: prompt ~${promptTokens} tokens is over the ${promptCap} cap` });
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -3,6 +3,8 @@
## [Unreleased]
- **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.
+- **`umtool new <slug> --from <channel>/<video> --seed frames` drafts a supercut from a frame scan.** One clip around each event, cut at the transcript's sentence edges, each with the running stats as its on-screen subtitle ("Level 5 · 9 left · 9,000 chips (22.5 BB)"), and the stats along each clip kept in the manifest's `frameScan` block for a stats overlay (not drawn yet). Review each clip in the bench before keeping it.
- **find-copy can fetch from an archive.org copy that is a single video file.** Such a file's fetch failed with "Requested format is not available" and the copy was then marked as failed. A copy's window is now cut from whatever single file it is, and a copy is marked failed only when the copy itself is gone or refused. `pnpm ops find-copy --json '{"article": "<id>", "retryFailed": true}'` tries copies marked failed again. Needs a restart of the editor.
- **A model can propose verdicts for a fact-check's unruled claims, for you to approve or reject.** `pnpm ops report-draft --json '{"task":"verdicts","article":"<id>"}'` asks each claim with no verdict, with the verdict bench's own prompt, and keeps each proposed verdict, its reason, the model and the prompt version in `verdicts.proposed.json` beside the article, never in `report.json`. It runs only on a model you ticked on the verdict bench (`settings.generation.verdicts.models`, empty until you do), and never sets a verdict itself. umtool's Inbox shows "N verdicts proposed" under Review; **Review verdicts** opens the article, where each proposal has **Approve** (the claim gets that verdict) and **Reject** (the claim stays unruled), with an optional note. A claim you have ruled, or whose proposal you have reviewed, is not asked again. `pnpm ops verdict-review` does the same from the command line. Needs a restart of the editor and umtool.
- **Draft everything can add the on-screen deck first.** Tick **with the deck** beside **Draft everything** on a cut's Media tab (or `umtool chain <article> <n> --draft-all --deck`): before the flips, a step adds the on-screen deck with every setting at its default to a cut that has none, so the flips and threads are drafted on a cut the converter made. A copy of the cut as it was is kept in its revisions first. A cut that already has a deck is left as it is, and the step says "deck added" or "deck already there". Off by default: without the tick, Draft everything is as it was. Needs a restart of umtool.
diff --git a/editor/app/api/ops/_frameScan.test.ts b/editor/app/api/ops/_frameScan.test.ts
@@ -0,0 +1,158 @@
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+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 { 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";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_frameScan.test.ts"
+//
+// The `frame-scan` job (release 30, lane P) end to end in this process: the
+// controller the route adapts, a synthetic poker stream (ffmpeg) saved in a
+// temp saved-video store, its spoken cues on disk, the fake Anthropic server,
+// a temp jobs dir and usage ledger.
+
+const SLUG = "synth-poker";
+const ID = "synthstream1";
+let tmp: string;
+let api: FakeAnthropic;
+let paths: Paths;
+let gen: GenerationSettings;
+let videoDir: string;
+
+const timesOf = (body: any): number[] =>
+ [...JSON.stringify(body.messages[0].content).matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2]));
+const truthTurn = (body: any) => toolTurn("answer", { frames: timesOf(body).map((t, i) => ({ frame: i + 1, ...pokerTruthAt(t) })) });
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "frame-scan-job-"));
+ api = await startFakeAnthropic();
+ const keyFile = path.join(tmp, "anthropic.env");
+ await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
+ await chmod(keyFile, 0o600);
+ const channel = path.join(tmp, "channels", SLUG);
+ videoDir = path.join(channel, "data", ID);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(channel, "config.json"), JSON.stringify({ url: "https://rumble.com/c/synth" }));
+ await writeFile(path.join(videoDir, "transcript.cues.json"), JSON.stringify({ cues: SPOKEN_CUES }));
+ const store = path.join(tmp, "saved-videos", SLUG, ID);
+ await mkdir(store, { recursive: true });
+ const { file } = await makeSyntheticPokerStream(store);
+ await rename(file, path.join(store, "source-media.mp4"));
+ await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-10-15T00:00:00Z", dir: store, file: "source-media.mp4", bytes: 1 }));
+ paths = {
+ jobsDir: path.join(tmp, ".jobs"),
+ channelsDir: path.join(tmp, "channels"),
+ generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"),
+ ollamaUrl: "http://127.0.0.1:9",
+ } as Paths;
+ gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 } });
+});
+
+after(async () => {
+ await api.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const deps = (g: Partial<GenerationSettings> = {}) => ({ paths, settings: () => ({ generation: { ...gen, ...g } }) });
+
+test("the body: a video and a profile; numbers as numbers within their ranges", () => {
+ assert.throws(() => parseFrameScanBody({}), /"slug"/);
+ assert.throws(() => parseFrameScanBody({ slug: "a", id: "../x" }), /"id"/);
+ assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", profile: "chess" }), /"profile" is one of poker/);
+ assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", everySeconds: 0 }), /everySeconds/);
+ assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", from: 50, to: 10 }), /"to" must be after "from"/);
+ assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", framesPerAsk: 12 }), /framesPerAsk/);
+ assert.deepEqual(parseFrameScanBody({ slug: "a", id: "b", hero: " Synth ", maxUsd: 2 }), { slug: "a", id: "b", profile: "poker", hero: "Synth", maxUsd: 2 });
+});
+
+test("the model is the route's; code needs a named one; the cap is within caps.max", () => {
+ assert.equal(frameScanModel(gen), "claude-haiku-4-5");
+ assert.equal(frameScanModel({ ...gen, routes: { ...gen.routes, frames: "local" } }), "qwen2.5vl:7b");
+ assert.throws(() => frameScanModel({ ...gen, routes: { ...gen.routes, frames: "code" } }), /name a "model"/);
+ assert.equal(frameScanModel({ ...gen, routes: { ...gen.routes, frames: "code" } }, "claude-haiku-5-5"), "claude-haiku-5-5");
+ assert.equal(frameScanCap(gen), 5);
+ assert.equal(frameScanCap({ ...gen, frames: { ...gen.frames, maxUsd: 50 } }), 10);
+ assert.throws(() => frameScanCap(gen, 11), /over the settings' max/);
+});
+
+test("a video that is not saved is refused, naming the persist-videos body", async () => {
+ await mkdir(path.join(paths.channelsDir, SLUG, "data", "notsaved1"), { recursive: true });
+ const out = await enqueueFrameScan({ slug: SLUG, id: "notsaved1" }, deps());
+ assert.ok("result" in out && !out.result.ok);
+ assert.match((out.result as { error: string }).error, /no saved video .* pnpm ops persist-videos --json '\{"items":\[\{"slug":"synth-poker","id":"notsaved1"\}\],"format":"original"\}'/);
+});
+
+test("an API scan: a frame-scan job on `frames`, the sidecar beside the video, the cache in data/<id>/frames, the spend in the ledger", async () => {
+ for (let i = 0; i < 10; i++) api.push(truthTurn);
+ const out = await enqueueFrameScan({ slug: SLUG, id: ID, hero: "SynthHero" }, deps());
+ assert.ok("model" in out && out.result.ok, JSON.stringify(out));
+ assert.equal(out.queueKey, "frames");
+ const job = getRegistry().get(out.result.jobId)!;
+ assert.equal(job.kind, "frame-scan");
+ assert.equal(job.channelSlug, SLUG);
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ assert.match(log, /@@frame-scan \{"slug":"synth-poker","id":"synthstream1","profile":"poker","file":"frame-scan.poker.json","frames":21,/);
+ assert.ok(!log.includes(FAKE_KEY));
+ const rec = (await loadFrameScan(videoDir, "poker"))!;
+ assert.ok(rec.derived.events.some((e) => e.kind === "double-up" && e.t === 90));
+ assert.deepEqual(rec.derived.flags.map((f) => f.t), [125]);
+ // A classic channel (no media/): the cache is in data/<id>/frames/poker.
+ const cache = path.join(videoDir, "frames", "poker");
+ assert.ok((await readdir(cache)).some((f) => f.endsWith(".jpg")));
+ const rows = await readGenerationUsage(paths.generationUsageFile);
+ assert.deepEqual(rows.map((r) => [r.task, r.model, r.jobId]), [["frame-scan", "claude-haiku-4-5", out.result.jobId]]);
+ assert.ok(rows[0]!.usd > 0);
+
+ // Evict: the cache goes, the sidecar stays; a re-run decodes again and asks nothing.
+ const ev = await enqueueFrameScan({ slug: SLUG, id: ID, evict: true }, deps());
+ assert.ok("evicted" in ev && ev.evicted.removed && ev.evicted.bytes > 0);
+ await assert.rejects(stat(cache));
+ const asked = api.requests.length;
+ const again = await enqueueFrameScan({ slug: SLUG, id: ID }, deps());
+ assert.ok("model" in again && again.result.ok);
+ void again.result.stream.cancel();
+ assert.equal((await again.result.done).status, "done");
+ assert.equal(api.requests.length, asked);
+ assert.equal((await loadFrameScan(videoDir, "poker"))!.runs.length, 2);
+});
+
+test("a tiered channel (media/ beside data/): the cache is on the media side", async () => {
+ await mkdir(path.join(paths.channelsDir, SLUG, "media"), { recursive: true });
+ try {
+ for (let i = 0; i < 4; i++) api.push(truthTurn);
+ const out = await enqueueFrameScan({ slug: SLUG, id: ID, everySeconds: 60 }, deps());
+ assert.ok("model" in out && out.result.ok, JSON.stringify(out));
+ void out.result.stream.cancel();
+ assert.equal((await out.result.done).status, "done");
+ assert.ok((await readdir(path.join(paths.channelsDir, SLUG, "media", ID, "frames", "poker"))).some((f) => f.endsWith(".jpg")));
+ } finally {
+ await rm(path.join(paths.channelsDir, SLUG, "media"), { recursive: true, force: true });
+ }
+});
+
+test("past the day's cap an API scan is refused; a local route goes on draft:local", async () => {
+ await appendGenerationUsage(paths.generationUsageFile, [
+ { at: new Date().toISOString(), day: utcDay(), jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 },
+ ]);
+ const refused = await enqueueFrameScan({ slug: SLUG, id: ID }, deps());
+ assert.ok("result" in refused && !refused.result.ok);
+ assert.match((refused.result as { error: string }).error, /daily cap/);
+ // The local route: queued on draft:local (its ollama is not there: the job fails, the queue is the point).
+ const local = await enqueueFrameScan({ slug: SLUG, id: ID, model: "qwen2.5vl:7b", everySeconds: 600 }, deps());
+ assert.ok("model" in local && local.result.ok);
+ assert.equal(local.queueKey, "draft:local");
+ void local.result.stream.cancel();
+ await local.result.done;
+});
diff --git a/editor/app/api/ops/frame-scan/route.ts b/editor/app/api/ops/frame-scan/route.ts
@@ -0,0 +1,33 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { FRAME_SCAN_BODY_KEYS, enqueueFrameScan } from "yt-dlp-transcript-common/controller/frameScan";
+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? }
+// -> { ok: true, jobId, model, queueKey } (evict: { ok: true, evicted })
+//
+// The frame scan (release 30, lane P), as a `frame-scan` job: the video's
+// saved container sampled every `everySeconds` (default
+// settings.generation.frames.everySeconds) into a frame cache on the channel's
+// media side, near-duplicate frames skipped, the rest read by a vision model
+// through the profile (poker), and `frame-scan.<profile>.json` written beside
+// the video: readings, the numbers the streamer said, the derived series,
+// events and segments. On `frames` (API) or `draft:local` (a local vision
+// 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}`.
+//
+// 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 (!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]/components/FrameScanControl.tsx b/editor/app/channels/[slug]/videos/[id]/components/FrameScanControl.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../../../../../jobs/actions";
+import { frameScanAction } from "../frameScanActions";
+
+// The Scan button: one frame-scan job for this video (settings.generation's
+// `frames` route and cap). Again after a scan, it resumes: frames already
+// read are not asked again.
+export function FrameScanControl({ slug, videoId, profile, scanned }: { slug: string; videoId: string; profile: string; scanned: boolean }) {
+ return (
+ <StreamActionLog
+ trigger={() => frameScanAction(slug, videoId, profile)}
+ cancelAction={cancelJobAction}
+ buttonLabel={scanned ? "Scan again" : "Scan frames"}
+ runningLabel="Scanning frames…"
+ label={`Scan frames of ${videoId}`}
+ />
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/FrameScanPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/FrameScanPanel.tsx
@@ -0,0 +1,115 @@
+// "Frame scan" (release 30, lane P): what a frame scan read of this video —
+// the phase strip, a small chart per tournament, the events (each a link to
+// the moment on the video's platform), the flags where something said and
+// something read disagree — and the Scan button when the video is saved.
+//
+// Not a registry operation (those are corpus-wide lanes, one panel each
+// below): a scan is asked for one stream at a time. Drawn when the sidecar
+// exists or the video's container is saved; otherwise there is nothing to
+// show and nothing to scan.
+
+import type { FrameScanView } from "../lib/frameScanView";
+import { FrameScanControl } from "./FrameScanControl";
+
+const PHASE_CLASS: Record<string, string> = {
+ table: "bg-success",
+ lobby: "bg-info",
+ break: "bg-warning",
+ other: "bg-muted-foreground/40",
+};
+
+export function FrameScanPanel({
+ slug,
+ videoId,
+ views,
+ canScan,
+}: {
+ slug: string;
+ videoId: string;
+ views: FrameScanView[];
+ canScan: boolean;
+}) {
+ if (!views.length && !canScan) return null;
+ return (
+ <section aria-label="frame scan" data-testid="frame-scan-panel" className="rounded-lg border border-border bg-card p-3 flex flex-col gap-3">
+ <h3 className="text-sm font-semibold">Frame scan</h3>
+ {!views.length && <p className="text-sm text-muted-foreground">Not scanned.</p>}
+ {views.map((v) => (
+ <div key={v.profile} className="flex flex-col gap-3" data-testid={`frame-scan-${v.profile}`}>
+ <p className="text-xs text-muted-foreground" aria-label="frame scan summary">
+ {v.profile} · {v.summary}
+ {v.stopped && <span className="text-warning"> · stopped: {v.stopped}</span>}
+ </p>
+ <div className="flex flex-col gap-1">
+ <div className="relative h-3 w-full rounded bg-muted overflow-hidden" role="img" aria-label="phases">
+ {v.strip.map((s, i) => (
+ <span
+ key={i}
+ title={s.label}
+ data-phase={s.phase}
+ className={`absolute top-0 h-full ${PHASE_CLASS[s.phase] ?? PHASE_CLASS.other}`}
+ style={{ left: `${s.leftPct}%`, width: `${s.widthPct}%` }}
+ />
+ ))}
+ </div>
+ <div className="flex flex-wrap gap-3 text-xs text-muted-foreground">
+ {Object.keys(PHASE_CLASS)
+ .filter((p) => v.strip.some((s) => s.phase === p))
+ .map((p) => (
+ <span key={p} className="flex items-center gap-1">
+ <span className={`inline-block h-2 w-2 rounded-sm ${PHASE_CLASS[p]}`} />
+ {p}
+ </span>
+ ))}
+ </div>
+ </div>
+ {v.tournaments.map((t) => (
+ <div key={t.key} className="flex flex-col gap-1" aria-label={`tournament ${t.name}`}>
+ <div className="text-sm">
+ <span className="font-medium">{t.name}</span> <span className="text-xs text-muted-foreground">{t.span}</span>
+ {t.facts.length > 0 && <span className="text-xs text-muted-foreground"> · {t.facts.join(" · ")}</span>}
+ </div>
+ <div className="flex flex-wrap gap-4">
+ {t.sparks.map((s) => (
+ <figure key={s.label} className="flex flex-col gap-0.5">
+ <svg viewBox="0 0 240 40" width="240" height="40" className="text-primary" role="img" aria-label={`${s.label}, ${s.min} to ${s.max}`}>
+ <polyline points={s.points} fill="none" stroke="currentColor" strokeWidth="1.5" />
+ </svg>
+ <figcaption className="text-xs text-muted-foreground">
+ {s.label}: {s.min.toLocaleString("en-US")}–{s.max.toLocaleString("en-US")}, last {s.last.toLocaleString("en-US")}
+ </figcaption>
+ </figure>
+ ))}
+ </div>
+ </div>
+ ))}
+ {v.events.length > 0 && (
+ <ul className="flex flex-col gap-0.5 text-sm" aria-label="frame scan events">
+ {v.events.map((e, i) => (
+ <li key={i} className="flex gap-2">
+ {e.href ? (
+ <a href={e.href} target="_blank" rel="noreferrer" className="font-mono underline hover:text-foreground">
+ {e.at}
+ </a>
+ ) : (
+ <span className="font-mono">{e.at}</span>
+ )}
+ <span className="font-medium">{e.kind}</span>
+ <span className="text-muted-foreground">{e.detail}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ {v.flags.length > 0 && (
+ <ul className="flex flex-col gap-0.5 text-xs text-warning" aria-label="frame scan flags">
+ {v.flags.map((f, i) => (
+ <li key={i}>{f}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ ))}
+ {canScan && <FrameScanControl slug={slug} videoId={videoId} profile="poker" scanned={views.some((v) => v.profile === "poker")} />}
+ </section>
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/frameScanActions.ts b/editor/app/channels/[slug]/videos/[id]/frameScanActions.ts
@@ -0,0 +1,19 @@
+"use server";
+
+// The video page's Scan button (release 30, lane P): one `frame-scan` job for
+// this video on the poker profile, through the same controller as
+// `pnpm ops frame-scan`. Its refusals (no saved video, the route, the day's
+// cap) come back as the button's error.
+//
+// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file; see
+// operationActions.ts).
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { enqueueFrameScan } from "yt-dlp-transcript-common/controller/frameScan";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+
+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" };
+ return out.result;
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts b/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts
@@ -0,0 +1,51 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { atTime, frameScanView } from "./frameScanView";
+import type { FrameScanRecord } from "yt-dlp-transcript-common/lib/frameScan-server";
+
+const record = (): FrameScanRecord => ({
+ format: "archilyzer-frame-scan",
+ version: 1,
+ profile: "poker",
+ source: { savedVideo: "source-media.mp4", durationSeconds: 200 },
+ sampling: { everySeconds: 10, from: 0, to: 200, width: 1280, keyframesOnly: true, frames: 20, kept: 12, skippedDuplicates: 8 },
+ model: { route: "api", model: "claude-haiku-4-5", promptVersion: 1 },
+ costUsd: 0.0412,
+ runs: [{ at: "2026-10-15T00:00:00Z", model: "claude-haiku-4-5", route: "api", frames: 20, read: 12, failed: 0, costUsd: 0.0412, stopped: "cap" }],
+ readings: Array.from({ length: 12 }, (_, i) => ({ t: i * 10, phase: "table" })),
+ duplicates: [],
+ spoken: [],
+ derived: {
+ tournaments: [{ key: "synthetic cup", name: "Synthetic Cup", from: 30, to: 190, series: { stack: [[30, 20000], [90, 41000], [180, 0]], playersLeft: [[30, 85], [120, 9]] }, facts: { buyIn: 200, totalPlayers: 120 } }],
+ events: [
+ { t: 60, kind: "pot", detail: "takes the pot 1,600 (8 BB)", source: "log", tournament: "synthetic cup" },
+ { t: 90, kind: "double-up", detail: "20,000 → 41,000 chips (2.1×)", source: "series", tournament: "synthetic cup" },
+ ],
+ segments: [{ from: 0, to: 30, phase: "lobby" }, { from: 30, to: 200, phase: "table", tournament: "synthetic cup" }],
+ flags: [{ t: 125, field: "playersLeft", spoken: 4, frame: 9, frameT: 120 }],
+ misreads: [{ t: 40, field: "stack", value: 2000000 }],
+ },
+ updatedAt: "2026-10-15T00:00:00Z",
+});
+
+test("atTime: the platform's own time parameter", () => {
+ assert.equal(atTime("https://www.youtube.com/watch?v=abc", 75.4), "https://www.youtube.com/watch?v=abc&t=75s");
+ assert.equal(atTime("https://rumble.com/v7abc-title.html", 3725), "https://rumble.com/v7abc-title.html?start=3725");
+ assert.equal(atTime("https://www.twitch.tv/videos/1", 3725), "https://www.twitch.tv/videos/1?t=1h2m5s");
+ assert.equal(atTime("https://example.com/v", 9), "https://example.com/v#t=9");
+ assert.equal(atTime(null, 9), null);
+ assert.equal(atTime("not a url", 9), null);
+});
+
+test("frameScanView: strip, charts, events with links, flags, summary", () => {
+ const v = frameScanView(record(), "https://rumble.com/v7abc-title.html");
+ assert.deepEqual(v.strip.map((s) => [s.phase, s.leftPct, s.widthPct]), [["lobby", 0, 15], ["table", 15, 85]]);
+ assert.equal(v.tournaments[0].name, "Synthetic Cup");
+ assert.deepEqual(v.tournaments[0].sparks.map((s) => [s.label, s.min, s.max, s.last]), [["Stack (chips)", 0, 41000, 0], ["Players left", 9, 85, 9]]);
+ assert.match(v.tournaments[0].sparks[0].points, /^0\.0,/);
+ assert.deepEqual(v.tournaments[0].facts, ["buy-in $200", "field 120"]);
+ assert.deepEqual(v.events.map((e) => [e.at, e.kind, e.href]), [["1:30", "double-up", "https://rumble.com/v7abc-title.html?start=90"]]);
+ assert.deepEqual(v.flags, ["2:05 Players left: said 4, the frame at 2:00 reads 9"]);
+ assert.equal(v.summary, "20 frames every 10 s, 12 read (8 duplicates skipped) on claude-haiku-4-5 · $0.04 · 1 misread set aside · 1 smaller pot won");
+ assert.equal(v.stopped, "cap");
+});
diff --git a/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.ts b/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.ts
@@ -0,0 +1,107 @@
+// The video page's "Frame scan" panel, as data (release 30, lane P): a
+// frame-scan sidecar → the phase strip, one small chart per tournament, the
+// events with links to the moment, the flags. Pure, so it is unit-tested and
+// the component only draws.
+
+import type { FrameScanRecord } from "yt-dlp-transcript-common/lib/frameScan-server";
+import { clock, fmtNum } from "yt-dlp-transcript-common/lib/frames/types";
+
+export type StripPart = { phase: string; leftPct: number; widthPct: number; label: string };
+export type Spark = { label: string; points: string; min: number; max: number; last: number };
+export type TournamentView = { key: string; name: string; span: string; sparks: Spark[]; facts: string[] };
+export type EventView = { t: number; at: string; kind: string; detail: string; href: string | null; source: string };
+export type FrameScanView = {
+ profile: string;
+ summary: string;
+ strip: StripPart[];
+ tournaments: TournamentView[];
+ events: EventView[];
+ flags: string[];
+ stopped: string | null;
+};
+
+/** The video's page on its platform at second `t`, when the platform takes a time. */
+export function atTime(url: string | null | undefined, t: number): string | null {
+ if (!url) return null;
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return null;
+ }
+ const s = Math.max(0, Math.floor(t));
+ const host = u.hostname.replace(/^www\./, "");
+ if (host === "youtube.com" || host === "m.youtube.com" || host === "youtu.be") u.searchParams.set("t", `${s}s`);
+ else if (host === "rumble.com") u.searchParams.set("start", String(s));
+ else if (host === "twitch.tv") u.searchParams.set("t", `${Math.floor(s / 3600)}h${Math.floor((s % 3600) / 60)}m${s % 60}s`);
+ else u.hash = `t=${s}`;
+ return u.toString();
+}
+
+const W = 240;
+const H = 40;
+
+// A series as an SVG polyline in a W×H box (a step line: a value holds until the next).
+function spark(label: string, pts: readonly (readonly [number, number, ...unknown[]])[], from: number, to: number): Spark | null {
+ if (pts.length < 1) return null;
+ const vs = pts.map((p) => p[1]);
+ const min = Math.min(...vs);
+ const max = Math.max(...vs);
+ const span = Math.max(1, to - from);
+ const x = (t: number) => (((t - from) / span) * W).toFixed(1);
+ const y = (v: number) => (max === min ? H / 2 : H - ((v - min) / (max - min)) * H).toFixed(1);
+ const out: string[] = [];
+ pts.forEach((p, i) => {
+ if (i > 0) out.push(`${x(p[0])},${y(pts[i - 1][1])}`);
+ out.push(`${x(p[0])},${y(p[1])}`);
+ });
+ out.push(`${x(to)},${y(pts[pts.length - 1][1])}`);
+ return { label, points: out.join(" "), min, max, last: vs[vs.length - 1] };
+}
+
+const SERIES_LABELS: Record<string, string> = { stack: "Stack (chips)", stackBB: "Stack (big blinds)", playersLeft: "Players left", level: "Level" };
+const FACT_LABELS: Record<string, (v: number) => string> = {
+ buyIn: (v) => `buy-in $${fmtNum(v)}`,
+ totalPlayers: (v) => `field ${fmtNum(v)}`,
+ prizePool: (v) => `prize pool $${fmtNum(v)}`,
+ firstPrize: (v) => `first prize $${fmtNum(v)}`,
+ payout: (v) => `payout $${fmtNum(v)}`,
+ position: (v) => `placed ${fmtNum(v)}`,
+ averageStack: (v) => `average stack ${fmtNum(v)}`,
+};
+
+export function frameScanView(r: FrameScanRecord, webpageUrl: string | null): FrameScanView {
+ const end = r.source.durationSeconds ?? r.sampling.to;
+ const total = Math.max(1, end);
+ const strip = r.derived.segments.map((s) => ({
+ phase: s.phase,
+ leftPct: Math.round((s.from / total) * 10_000) / 100,
+ widthPct: Math.max(0.2, Math.round(((s.to - s.from) / total) * 10_000) / 100),
+ label: `${s.phase} ${clock(s.from)}–${clock(s.to)}`,
+ }));
+ const tournaments = r.derived.tournaments.map((t) => ({
+ key: t.key,
+ name: t.name ?? t.key,
+ span: `${clock(t.from)}–${clock(t.to)}`,
+ sparks: ["stack", "playersLeft"].map((f) => spark(SERIES_LABELS[f] ?? f, t.series[f] ?? [], t.from, t.to)).filter((s): s is Spark => s !== null),
+ facts: Object.entries(t.facts).flatMap(([k, v]) => (FACT_LABELS[k] ? [FACT_LABELS[k](v)] : [])),
+ }));
+ // Every pot the hero takes is an event; the list shows the big ones and counts the rest.
+ const pots = r.derived.events.filter((e) => e.kind === "pot").length;
+ const events = r.derived.events.filter((e) => e.kind !== "pot").map((e) => ({
+ t: e.t,
+ at: clock(e.t),
+ kind: e.kind,
+ detail: e.detail,
+ href: atTime(webpageUrl, e.t),
+ source: e.source,
+ }));
+ const flags = r.derived.flags.map((f) => `${clock(f.t)} ${SERIES_LABELS[f.field] ?? f.field}: said ${fmtNum(f.spoken)}, the frame at ${clock(f.frameT)} reads ${fmtNum(f.frame)}`);
+ const last = r.runs[r.runs.length - 1];
+ const summary =
+ `${fmtNum(r.sampling.frames)} frames every ${r.sampling.everySeconds} s, ${fmtNum(r.readings.length)} read` +
+ ` (${fmtNum(r.sampling.skippedDuplicates)} duplicates skipped) on ${r.model.model} · $${r.costUsd.toFixed(2)}` +
+ (r.derived.misreads.length ? ` · ${r.derived.misreads.length} misread${r.derived.misreads.length === 1 ? "" : "s"} set aside` : "") +
+ (pots ? ` · ${pots} smaller pot${pots === 1 ? "" : "s"} won` : "");
+ return { profile: r.profile, summary, strip, tournaments, events, flags, stopped: last?.stopped ?? null };
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -43,6 +43,9 @@ import { RunningJobsList } from "../../../../jobs/components/RunningJobsList";
import { VideoPanel, type VideoFile } from "./components/VideoPanel";
import { OperationPanel } from "./components/OperationPanel";
import { TagsPanel } from "./components/TagsPanel";
+import { FrameScanPanel } from "./components/FrameScanPanel";
+import { frameScanView } from "./lib/frameScanView";
+import { loadFrameScans } from "yt-dlp-transcript-common/lib/frameScan-server";
import { MetadataHistoryDetails } from "./components/MetadataHistoryDetails";
import { RefreshMetadataControl } from "./components/RefreshMetadataControl";
import { loadVideoTags } from "./lib/videoTags";
@@ -185,6 +188,10 @@ export default async function VideoDetailPage({
settings: getSettings(),
});
+ // What a frame scan read of this video (release 30): one small sidecar a
+ // profile, on the corpus disk.
+ const frameScans = await loadFrameScans(videoDir);
+
// The curated tags on this video, with each one's provenance. Reads tags.json
// plus (for rule hits) ONE key out of the transcript index — not a scan.
const tagsView = await loadVideoTags(slug, id);
@@ -206,6 +213,7 @@ export default async function VideoDetailPage({
coverage,
panels,
tagsView,
+ frameScans,
};
};
const drive = config.dataDir?.trim();
@@ -236,6 +244,7 @@ export default async function VideoDetailPage({
coverage,
panels,
tagsView,
+ frameScans,
} = loaded;
const registry = getRegistry();
@@ -362,6 +371,15 @@ export default async function VideoDetailPage({
<TagsPanel view={tagsView} />
+ {/* A frame scan's timeline, and its Scan button when the source
+ container is saved (the scan reads the saved video). */}
+ <FrameScanPanel
+ slug={slug}
+ videoId={id}
+ views={frameScans.map((r) => frameScanView(r, meta.webpageUrl ?? null))}
+ canScan={!!savedVideo}
+ />
+
{/* The external operations' per-video surface is the pipeline stage
cards INSIDE VideoPanel above (download, transcode, transcription).
These are the registry's — one panel per entry, and a fifth entry
diff --git a/editor/app/jobs/components/JobProgressBars.tsx b/editor/app/jobs/components/JobProgressBars.tsx
@@ -162,6 +162,7 @@ const METRIC_LABELS: Record<JobProgressMetric, string> = {
turns: "Model turns",
cards: "Cards",
entries: "Entries",
+ frames: "Frames",
};
// Per-metric glyph for the compact line ("↓ 5/10").
@@ -175,6 +176,7 @@ const METRIC_PREFIX: Record<JobProgressMetric, string> = {
turns: "\u21c4 ",
cards: "\u25a4 ",
entries: "\u2261 ",
+ frames: "\u25a3 ",
};
const METRIC_FILL: Record<JobProgressMetric, string> = {
@@ -187,6 +189,7 @@ const METRIC_FILL: Record<JobProgressMetric, string> = {
turns: "bg-info",
cards: "bg-success/60",
entries: "bg-success/60",
+ frames: "bg-info/60",
};
// One-line textual summary of a job's batch progress, e.g. "↓ 5/10 · ~2m left"
diff --git a/editor/e2e/frame-scan.spec.ts b/editor/e2e/frame-scan.spec.ts
@@ -0,0 +1,74 @@
+import { test, expect } from "@playwright/test";
+import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import { join } from "node:path";
+// By relative path, as report-draft.spec.ts imports common: the kit's fakes
+// and the synthetic poker stream are plain .mjs.
+import { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs";
+import { makeSyntheticPokerStream, pokerTruthAt, SPOKEN_CUES } from "../../common/testing/frames/syntheticPoker.mjs";
+import { resetData, testPaths, writeSettings } from "./helpers";
+
+// The frame scan (release 30, lane P) on the video page: a saved synthetic
+// poker stream (ffmpeg-made), the Scan button, the job against the fake
+// Anthropic (started here; settings point at it with a mode-600 key file),
+// and the "Frame scan" panel it leaves: the phase strip, the events linked to
+// the moment on the video's platform, the flag where a spoken number and a
+// frame disagree.
+
+const SLUG = "test-transcribe";
+const ID = "vidA";
+
+let api: FakeAnthropic;
+let tmp: string;
+
+const timesOf = (body: any): number[] =>
+ [...JSON.stringify(body.messages[0].content).matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2]));
+
+test.beforeAll(async () => {
+ api = await startFakeAnthropic();
+ tmp = await mkdtemp(join(os.tmpdir(), "e2e-frame-scan-"));
+});
+
+test.afterAll(async () => {
+ await api?.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+test("Scan frames on a saved stream: the job, then the panel's phases, events and flags", async ({ page }) => {
+ test.setTimeout(120_000);
+ await resetData("one-transcribe-channel");
+ const keyFile = join(tmp, "anthropic.env");
+ await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
+ await chmod(keyFile, 0o600);
+ await writeSettings({ minFreeDiskGB: 0, generation: { apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 5 } } });
+
+ const videoDir = join(testPaths().transcriptsDir, "channels", SLUG, "data", ID);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(join(videoDir, "metadata.info.json"), JSON.stringify({ id: ID, title: "Synthetic poker stream", webpage_url: "https://rumble.com/v7synth-synthetic-poker.html", duration: 210 }));
+ await writeFile(join(videoDir, "transcript.cues.json"), JSON.stringify({ cues: SPOKEN_CUES }));
+ const store = join(tmp, "saved", SLUG, ID);
+ await mkdir(store, { recursive: true });
+ const { file } = await makeSyntheticPokerStream(store, { name: "source-media.mp4" });
+ await writeFile(join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-10-15T00:00:00Z", dir: store, file: "source-media.mp4", bytes: 1 }));
+ void file;
+ for (let i = 0; i < 10; i++) api.push((body: any) => toolTurn("answer", { frames: timesOf(body).map((t, k) => ({ frame: k + 1, ...pokerTruthAt(t) })) }));
+
+ await page.goto(`/channels/${SLUG}/videos/${ID}`);
+ const panel = page.getByTestId("frame-scan-panel");
+ await expect(panel).toContainText("Not scanned.");
+ await panel.getByRole("button", { name: "Scan frames", exact: true }).click();
+ await expect(page.getByLabel(`Scan frames of ${ID} output`)).toContainText("@@frame-scan", { timeout: 60_000 });
+
+ await page.reload();
+ await expect(panel.getByLabel("frame scan summary")).toContainText("21 frames every 10 s");
+ await expect(panel.getByLabel("frame scan summary")).toContainText("claude-haiku-4-5");
+ await expect(panel.locator('[data-phase="table"]').first()).toBeVisible();
+ await expect(panel.locator('[data-phase="break"]')).toHaveCount(1);
+ const events = panel.getByLabel("frame scan events");
+ await expect(events).toContainText("double-up");
+ await expect(events).toContainText("bust");
+ await expect(events.getByRole("link", { name: "1:30" })).toHaveAttribute("href", "https://rumble.com/v7synth-synthetic-poker.html?start=90");
+ await expect(panel.getByLabel("tournament Synthetic Cup")).toContainText("Stack (chips)");
+ await expect(panel.getByLabel("frame scan flags")).toContainText("said 4, the frame at 2:00 reads 9");
+ await expect(panel.getByRole("button", { name: "Scan again", exact: true })).toBeVisible();
+});
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -145,6 +145,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async
social: "api",
// Verdict proposals (release 29 M8): on a model in verdicts.models only.
verdicts: "api",
+ // The frame scan (release 30): routed like every task.
+ frames: "api",
},
},
},
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -44,7 +44,8 @@ export type GenerationPolicy = PlanGeneration & {
export type GenerationUsageDay = { day: string; usd: number; jobs: number; daily: number };
// The tasks `generate` takes: the policy's (research included, S11).
-export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS, "research"])];
+// Not `frames`: a frame scan is `frame-scan`, not a generation of an article.
+export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS.filter((t) => t !== "frames"), "research"])];
const ARTICLE_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
const JOB_RE = /^[A-Za-z0-9_-]+$/;
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9663,3 +9663,49 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
needs no key of its own. Shown by the export's TranscriptModal ("Partial transcript: N of M min decoded",
`partialTranscriptLine`) and by MCP `get_transcript` / `get_video_metadata` (`salvageCaveat`; the metadata JSON
carries the field). Not on `DisplaySummary` (the summaries pages).
+
+## Release 30 lane P: the frame scan (verified 2026-10-15, branch `r30/frame-scan`)
+
+- **Files.** `channels/<slug>/data/<id>/frame-scan.<profile>.json` (declared with `sidecar()` per profile in
+ `common/lib/frameScan-server.ts`; `poker` is the only profile) — TEXT, never published. The frame CACHE is
+ `channels/<slug>/media/<id>/frames/<profile>/` when the channel has a `media` (dir or link), else
+ `data/<id>/frames/<profile>/` (`frameCacheDirOf`): JPEGs named by centisecond (`t000012340.jpg`) plus
+ `index.json` `{everySeconds, width, keyframesOnly, crop?, frames: [{t, file, hash}]}` (a crop `[x, y, w, h]` is
+ fractions of the picture, applied after `fps` and before the JPEG and the hash). Evictable (`frame-scan {evict}`);
+ deleting the video's `media/<id>/` takes it.
+- **The sidecar**: `{format: "archilyzer-frame-scan", version: 1, profile, source: {savedVideo (basename),
+ durationSeconds}, sampling: {everySeconds, from, to, width, keyframesOnly, crop?, frames, kept, skippedDuplicates},
+ model: {route, model, promptVersion}, hints?: {hero}, costUsd (all runs), runs: [{at, jobId?, model, route, frames, read, failed, costUsd,
+ stopped?: cap|cancelled|errors|maxFrames}], readings: [{t, phase, tournament?, hero?, hand?, log?, event?}] (read
+ frames only; `log` = the client's log lines as shown), duplicates: [[t, the read frame's t]], spoken: [{t, field, value, text, approx?}], derived: {tournaments:
+ [{key, name?, from, to, series: {stack, stackBB, playersLeft, level, position, averageStack, bigBlind: [[t, v] | [t,
+ v, "spoken"]]}, facts}], events: [{t, kind, detail, source: frame|series|log|spoken, tournament?}] (kinds: the frame's
+ banners, double-up, big-loss, bust, final-table, won, pot, big-pot, knockout, buy-in), segments: [{from, to, phase, tournament?}], flags:
+ [{t, field, spoken, frame, frameT, tournament?}], misreads: [{t, field, value}]}, updatedAt}`. Every `t` is SOURCE
+ seconds on the sampling grid (`from + k·everySeconds`); with keyframes-only sampling the picture is the keyframe
+ nearest it.
+- **`hero` and `crop` are the scan's**: given once, kept with the sidecar (`hints`, `sampling.crop`) for later runs;
+ `fresh` drops the readings (not the runs or the spend). For `v7gkv5w` the crop is `[0.0172, 0.1042, 0.694, 0.681]`
+ (the client panel left of the webcam) and the hero `TheQuartering`.
+- **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 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
+ are judged on every kept point, a change needing the reading after it), `pokerSpoken` (`lib/frames/pokerSpoken.ts`
+ over `numberWords.ts`). A spoken number within 90 s of a frame value of its field agrees or is a FLAG; with none it
+ fills the series as `[t, v, "spoken"]` and never makes an event.
+- **The job**: kind `frame-scan` (`needsMedia`), queue `frames` (`FRAME_SCAN_QUEUE`) on the API or `draft:local` on a
+ local model (GPU arbiter; ollama unloaded at the end); refused when `resolveSavedVideo` finds nothing, past
+ `caps.daily`, or with `maxUsd` over `caps.max`; spend to the usage ledger as `task: "frame-scan"`. The log ends
+ `@@frame-scan {…}`. `settings.generation.routes.frames` (code/api/local; `code` = name a model) and
+ `settings.generation.frames {apiModel, localModel, maxUsd, everySeconds}`. `frames` is a GENERATION_TASK but never
+ a report-draft task (`reportDraft.ts` TASKS and the MCP's GENERATE_TASKS leave it out).
+- **Images in `structuredAnswer`**: `images: [{mediaType, data}]` → Claude image blocks before the text; ollama the
+ user message's `images`. `promptEstimate` counts an image at `IMAGE_TOKEN_ESTIMATE` (1200), never its base64.
+- **umtool**: `report-to-video/frames-cut.mjs` (`framesCut`, `frameTotals`, `statsLine`; pure) and `umtool new … --seed
+ frames` write clips with ids `fNN`, `quote: ""`, `onscreen.{title, subtitle}` marked `drafted.onscreen {task: "frames", model: "code"}` (code's: no review row; an
+ edit makes it the operator's),
+ `frameEvents`, and a top-level `frameScan {profile, file, channel, video, tournaments, overlay: [{clip, points: [{at,
+ …frameTotals}]}]}` no render reads yet.
diff --git a/plans/release-30/frame-scan.md b/plans/release-30/frame-scan.md
@@ -0,0 +1,102 @@
+# Release 30, lane P: the frame scan (`r30/frame-scan`)
+
+The operator's ask (2026-10-15): scan a stream on the Jeralyzer, break it into frames and analyse them for a poker
+tournament's progress, toward a supercut with a stats overlay. First stream: `the-quartering-rumble/v7gkv5w`
+(3:45:54, 1920×1080, the saved container `original`).
+
+### P1–P4, as shipped (2026-10-15, lane P, `r30/frame-scan` from `main` `59fdc486`)
+
+Built as the brief's design (generic engine, poker as its first profile), with these as built:
+
+- **Sampling** (`common/lib/frames/sample-server.ts`): one ffmpeg per half hour of stream, keyframes only
+ (`-skip_frame nokey`, `-ss` before `-i`), `fps=1/N` then an optional CROP (fractions `[x, y, w, h]`: the part read and
+ hashed — the poker client, not the webcam beside it), then split into a JPEG at the profile's width (poker 1280) and a
+ 17×16 grey thumbnail on stdout for the dHash. `t` is the grid time in SOURCE seconds. The cache is resumable by grid
+ time (`index.json`, keyed by step, width, decode mode and crop). Measured on `v7gkv5w` (no model): the whole stream,
+ 1,355 frames at 10 s with the crop, in 268 s from the media drive.
+- **Duplicates** (`dhash.ts`): a frame within `dupMaxBits` (poker 2) of the last READ frame is not asked, re-read every
+ `rereadEvery` (6); the derivation reads duplicates as copies. On `v7gkv5w` with the crop: 1,139 of 1,355 kept (0
+ bits: 1,290; 4: 1,039; 6: 929). Without the crop the webcam makes nearly every frame differ.
+- **Reading** (`scan.ts`, `structuredAnswer` with images): up to 4 frames an ask on the API, 1 on a local model; each
+ reading coerced in code (`coercePokerReading`: enums, ranges, card format, misread pairs dropped, the log's lines kept
+ as written). Prompt version 2 (calibrated on the first stream's frames, read locally): the stats header ("position N
+ of M", average stack), the dealer log copied line by line, the hero's bounty, the break countdown, an action label in
+ a name box. Rules only, no worked example (Q0). Capped: the run stops before an ask whose estimate (image tokens from
+ the JPEG's size, the price table) would pass `maxUsd`; three failed asks in a row stop it; a cancelled or cut run keeps
+ what it read (the sidecar is written every 5 asks).
+- **Spoken numbers** (`numberWords.ts`, `pokerSpoken.ts`): the transcript's numbers normalized to digits (words,
+ "$2,750", "311 K", "233k", ordinals after a tens word), then rules: players left, the field, average stack, the
+ hero's stack (scaled ×1000 beside an average said in thousands within half an hour, marked `approx`) and big blinds,
+ the hero's place, buy-in (and the ASR's "buying is"), first prize, prize pool, the blind level said as poker says it
+ (never a bare "level N": the streamer games), blinds. A stack, big-blind count or place said as a supposition ("once
+ I'm down to…", "it's not like I'm sitting on…") is left out. On `v7gkv5w`'s 1,672 cues: 30 readings, every one checked
+ by eye against its cue (scratch only, nothing committed).
+- **Derivation** (`poker.ts` `derivePoker`, pure): tournaments keyed by the name on screen (unnamed readings take the
+ name before; a field-size change over 1.5×, or chips again after the hero was out and away from the table, is another
+ tournament); series per tournament (stack, stack in BB — shown, else stack over the big blind, the blinds carried
+ until they change — players left, level, position, average stack, big blind), a point both neighbours agree against
+ set aside as a misread (an end point only when it disagrees by the square of the ratio; a last 0 is kept); events
+ judged on every kept point, a change needing the reading after it (double-up ×1.8, big loss ½, bust, final table, won),
+ the frame's own banners once a minute, and the log's: the hero's pots (`big-pot` at 25 BB or more), a knockout, a bust
+ ("<hero> has finished the tournament in Nth"); "Blinds are now a/b" and "<name> has finished the tournament in Nth"
+ fill blinds and players left a frame did not show. A spoken number within 90 s of a frame value of its field agrees
+ or is a FLAG; with none it fills the series (`[t, v, "spoken"]`) and never makes an event.
+- **The job** (`controller/frameScan.ts`, kind `frame-scan`, `needsMedia`): queue `frames` on the API, `draft:local` on
+ a local model (GPU arbiter, unloaded after); the model is the body's, else `settings.generation.routes.frames`
+ (`code` = name one) and `settings.generation.frames {apiModel: claude-haiku-4-5, localModel: qwen2.5vl:7b, maxUsd 5,
+ everySeconds 10}`; refused with no saved video (the sentence is the `persist-videos` body), past `caps.daily`, or with
+ `maxUsd` over `caps.max`; spend to the usage ledger (`task: "frame-scan"`); `@@frame-scan {…}` ends the log. Body:
+ `{slug, id, profile?, everySeconds?, from?, to?, maxFrames?, model?, maxUsd?, hero?, framesPerAsk?, crop?, fresh?,
+ evict?}`; `hero` and `crop` are kept with the sidecar for the next run; `fresh` reads every frame again (another model)
+ keeping the runs and the spend; `evict` removes the cache, no job.
+- **Surfaces**: `pnpm ops frame-scan` / `POST /api/ops/frame-scan`; the video page's **Frame scan** panel (phase strip,
+ a stack and players-left chart per tournament, events linked to the moment on the platform — Rumble `?start=`, YouTube
+ `t=`, Twitch `t=XhYmZs` — the flags, the summary; the hero's small pots counted, not listed) and **Scan frames** when
+ the video is saved; the jobs list's `frames` progress. Not a registry operation: those are corpus-wide lanes.
+- **umtool** (`report-to-video/frames-cut.mjs`, ledger-totals' pattern, and `umtool new <slug> --from <channel>/<id>
+ --seed frames`): a clip around each event (bust, final table, knockout, double-up, big pot, big loss, all-in, won;
+ windows widened to the cues' sentence edges within widen's budgets, merged when they touch, at most 20), its
+ on-screen subtitle the running stats (code's draft, `drafted.onscreen` `model: "code"`), and the manifest's
+ `frameScan.overlay` (the stats at each clip's start and every change inside it). No render reads `frameScan` yet.
+- **The test kit**: the fake Anthropic takes and checks image blocks (and counts them at (w·h)/750), the fake ollama a
+ message's `images` (1,200 tokens each against the cap); `testing/frames/syntheticPoker.mjs` paints a fake client with
+ ffmpeg (`color` + `drawtext`) into a 210-s stream, with `pokerTruthAt(t)` and `SPOKEN_CUES`.
+- **OCR** (the brief's option (b)): not added. `tesseract` is not installed and no OCR package is in the tree.
+ `tesseract.js` would be a dependency (the JS, a 4–7 MB wasm core) plus a language file (`eng` fast ≈ 4 MB, best ≈ 15
+ MB) that it downloads from a CDN at first use unless vendored, run in worker threads at roughly 0.1–0.3 s a small
+ region; no system dependency. The first stream's layout is fixed (the hero's stack box, the pot, the 4-line dealer
+ log, the header), so a digits-only reader of those boxes is viable as a second reader beside the model — the next
+ step once a live run shows where the model misreads.
+
+| Commit | What |
+| --- | --- |
+| `ba992f00` | common, mcp: the engine — sampling, dHash, the poker profile, spoken numbers, derivation, images in `structuredAnswer`, `settings.generation.frames` and the `frames` route, the job kind and controller, the sidecar, the fakes' images, the synthetic stream |
+| `77f9720c` | editor, scripts: `pnpm ops frame-scan`, the video page's Frame scan panel and Scan button, COMMANDS.md |
+| `77127aaa` | umtool: `frames-cut.mjs`, `umtool new … --seed frames` |
+| `e8449230` | umtool, plans: the draft's on-screen text is code's; FACTS; CHANGELOG |
+| `1f2b1a0c` | common: the spoken numbers calibrated on the first stream's transcript |
+| `ab82ee65` | common, editor, umtool, mcp, scripts: calibrated on the first stream's frames — the crop, prompt version 2 (header, log, bounty, break countdown), the log's pots, knockouts, busts, blinds and finishing places, generations after a bust, the position and average-stack series, carried blinds, `fresh`, a kept `hero` and `crop`; the mcp preset test names `frames` |
+| (this commit) | editor: the e2e spec's button locators (a StreamActionLog button is named by its text); this record; CHANGELOG |
+
+Gates (from the worktree root; every tsc and suite under the shared heavy lock):
+- tsc: common, editor, mcp, umtool, export, homepage clean (package-scoped through the slice; the recursive run before
+ the last commit — see the report).
+- common: 4253 at the branch's start (1 failing that run, not reproduced) → 4310 at `1f2b1a0c`, all pass; lib/frames
+ 59/59 at `ab82ee65` (the synthetic stream end to end on both fakes, the cap, resume, `fresh`, the crop).
+- editor unit: 310 → 318 at `1f2b1a0c`, all pass; `_frameScan.test.ts` 6/6 and `frameScanView.test.ts` 2/2 at the tip.
+- test:scripts: 1024 (1021 + 3 skipped) → 1029 (1026 + 3 skipped) at `1f2b1a0c`; `frames-cut.test.mjs` 5/5 at the tip.
+- umtool unit: 33 → 33. mcp: 372 with 1 failing at `1f2b1a0c` (the preset test did not name `frames`) → fixed in
+ `ab82ee65` (`generation.test.ts` 16/16).
+- `docs cli` and `settings example` regenerated; `docs files --check`, `docs env --check` clean.
+- editor e2e, one spec: `frame-scan.spec.ts` 1/1 (5.0 s; the e2e build 482 s) — the synthetic stream saved, **Scan
+ frames**, the job against the fake Anthropic, then the panel: 21 frames, the break segment, double-up and bust with the
+ Rumble `?start=90` link, the tournament's chart, the spoken/frame flag. (The first run, 1 failed: the spec named the
+ button by the log's label.)
+- Measured without a model on `v7gkv5w`: the whole stream sampled in 268 s; 1,139 of 1,355 frames kept with the crop.
+
+Found and left:
+- The sampler runs `ffmpeg`/`ffprobe` from PATH, not `paths.ffmpegBin` (`FFMPEG_BIN`): the editor e2e server points
+ `FFMPEG_BIN` at a fake that makes no frames, and the scan needs real ones. A later slice may give the scan its own
+ override.
+- `frameScan.overlay` is data only: no chrome region draws it.
+- OCR of the client's fixed boxes (above) and a per-channel crop/hero setting are next steps.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -118,6 +118,9 @@
// pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'
// pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait
// pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait
+// 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 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}'
@@ -447,6 +450,12 @@ const ACTIONS = [
// maxUsd?, limit?, itemsFrom?}),
// as a bench-verdicts job on draft:local (any local model) or draft:api.
"bench-verdicts",
+ // 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).
+ "frame-scan",
// RECURRING REPORTS (umtool R5): a living report or a dated series on a
// cadence the editor keeps ({action: list | create | update | pause |
// resume | delete | tick-now | reset-triage, …}); tick-now is a
@@ -473,6 +482,9 @@ export const REPORT_TICK_RESULT_MARKER = "@@report-tick ";
// The same for the verdict bench (BENCH_VERDICTS_RESULT_MARKER in
// common/controller/benchVerdicts.ts).
export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts ";
+// The same for a frame scan (FRAME_SCAN_RESULT_MARKER in
+// common/controller/frameScan.ts).
+export const FRAME_SCAN_RESULT_MARKER = "@@frame-scan ";
// The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in
// common/controller/remoteListing.ts).
export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
@@ -701,6 +713,7 @@ export function parseArgs(argv) {
...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}),
...(action === "report-draft" ? { resultMarker: REPORT_DRAFT_RESULT_MARKER } : {}),
...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}),
+ ...(action === "frame-scan" ? { resultMarker: FRAME_SCAN_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
wait,
quiet,
@@ -1412,6 +1425,29 @@ export function usage() {
" (umtool's /tools/bench). The log ends with",
" @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}.",
"",
+ '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"?} -> {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.<profile>.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?}.",
+ "",
'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", …}.',
diff --git a/settings.json.example b/settings.json.example
@@ -255,7 +255,8 @@
"threads": "local",
"youtube": "local",
"social": "local",
- "verdicts": "local"
+ "verdicts": "local",
+ "frames": "api"
},
"models": {
"api": "claude-sonnet-5-5",
@@ -308,6 +309,12 @@
"weak": 3,
"maxEscalationsPerDay": 3,
"maxCandidates": 40
+ },
+ "frames": {
+ "apiModel": "claude-haiku-4-5",
+ "localModel": "qwen2.5vl:7b",
+ "maxUsd": 5,
+ "everySeconds": 10
}
}
}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -33,7 +33,7 @@
// --deck adds the on-screen deck to a cut with none before the flips
// umtool index [--rebuild] [--prune] [--since MS] [--json]
// umtool new <slug> [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>]
-// [--site-origin URL] [--seed chapters] [--brand archilyzer-media]
+// [--site-origin URL] [--seed chapters|frames] [--brand archilyzer-media]
// umtool doctor [--json] exit 1 if the report pipeline is missing a tool
// or the media root is set and not there
// umtool storage [move-out|move-back <project>|--all] [--dry-run] [--json]
@@ -691,7 +691,9 @@ function usage() {
" each draft a report-draft job on --model (else its route); a draft that fails does not stop it;",
" --deck adds a step before the flips: the minimal on-screen deck on a cut with none",
" umtool index [--rebuild] [--prune] [--since MS] [--json]",
- " umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters]",
+ " umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters|frames]",
+ " --seed frames: a draft supercut from the video's frame scan (pnpm ops frame-scan) — a clip",
+ " around each event, the running stats as each clip's subtitle and the frameScan overlay block",
" [--brand archilyzer-media] render.brand: the report-to-video brand preset",
" umtool doctor [--json] exit 1 if the report pipeline is missing a tool",
" or the media root is set and not there; the roots, and a leftover old cache",
@@ -1087,7 +1089,7 @@ async function cmdNew() {
die(
"usage: umtool new <slug> [--kind report-video] [--title T]\n" +
" [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" +
- " [--site-origin <url>] [--seed chapters] [--brand archilyzer-media]",
+ " [--site-origin <url>] [--seed chapters|frames] [--brand archilyzer-media]",
);
}
const kind = val("--kind") ?? "report-video";
@@ -1112,7 +1114,7 @@ async function cmdNew() {
console.log(`${r.dir}`);
if (r.seeded) {
- console.log(` video.manifest.json ${r.seeded} clip(s) SEEDED from digest chapters — review each`);
+ console.log(` video.manifest.json ${r.seeded} clip(s) SEEDED from ${val("--seed") === "frames" ? "the frame scan's events" : "digest chapters"} — review each`);
} else {
console.log(` video.manifest.json an EMPTY timeline — see README.md`);
}
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -6,6 +6,7 @@
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { BRAND_IDS } from "umtool-report-to-video/brand-ids";
+import { framesCut } from "umtool-report-to-video/frames-cut";
import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs";
export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
@@ -171,6 +172,23 @@ export async function chaptersAsClips({ channelsDir, channel, video }) {
}
/**
+ * A frame scan's events, as a draft supercut (release 30): the video's
+ * `frame-scan.<profile>.json` (`pnpm ops frame-scan`) through framesCut —
+ * a clip around each event, cut on the cues' sentence edges — and the scan's
+ * running stats as the manifest's `frameScan` overlay block.
+ */
+export async function framesAsClips({ channelsDir, channel, video, profile = "poker" }) {
+ const dir = path.join(channelsDir, channel, "data", video);
+ const scan = await readJson(path.join(dir, `frame-scan.${profile}.json`));
+ if (!scan) throw new Error(`${channel}/${video} has no frame-scan.${profile}.json — run pnpm ops frame-scan first`);
+ const cuesDoc = await readJson(path.join(dir, "transcript.cues.json"));
+ const cues = Array.isArray(cuesDoc?.cues)
+ ? cuesDoc.cues.filter((c) => c && Number.isFinite(c.start) && Number.isFinite(c.end) && typeof c.text === "string").sort((a, b) => a.start - b.start)
+ : null;
+ return framesCut(scan, { channel, video, cues });
+}
+
+/**
* Write the project. Refuses an existing directory and a slug that will not
* route; everything else it cannot know is written EMPTY so `check` blocks.
*
@@ -196,8 +214,8 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
`could not tell what --from is: "${from}" is neither a .md report, a viewer share URL (…/?v=<channel>%2F<id>&t=<s>), nor a <channel>/<videoId> ref`,
);
}
- if (seed && seed !== "chapters") throw new Error(`--seed must be "chapters", not "${seed}"`);
- if (seed && src?.kind !== "video") throw new Error("--seed chapters needs --from to be a video ref");
+ if (seed && seed !== "chapters" && seed !== "frames") throw new Error(`--seed must be "chapters" or "frames", not "${seed}"`);
+ if (seed && src?.kind !== "video") throw new Error(`--seed ${seed} needs --from to be a video ref`);
if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed");
if (timeline && (!Array.isArray(timeline) || !timeline.every(isBoardClip))) {
throw new Error("a timeline is a list of clips, each { type: \"clip\", id, channel, video, start, end }");
@@ -239,6 +257,17 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
if (!clips.length) notes.push("the digest has no enabled chapters, so the timeline is empty");
}
+ let framesSeeded = false;
+ if (seed === "frames") {
+ const cut = await framesAsClips({ channelsDir, channel: src.channel, video: src.video });
+ doc.timeline = cut.timeline;
+ doc.frameScan = cut.frameScan;
+ seeded = cut.timeline.length;
+ framesSeeded = true;
+ if (cut.skipped) notes.push(`${cut.skipped} lesser event(s) left out (the most important kept)`);
+ if (!cut.timeline.length) notes.push("the frame scan found no events worth a clip, so the timeline is empty");
+ }
+
if (timeline) {
doc.timeline = timeline.map((c) => ({ ...c }));
seeded = doc.timeline.length;
@@ -268,6 +297,19 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
"",
...doc.timeline.map((c) => `- [ ] ${c.id} ${c.channel}/${c.video} ${c.start}–${c.end} ${String(c.quote ?? "").slice(0, 80)}`),
);
+ } else if (seeded && framesSeeded) {
+ lines.push(
+ "## Clips seeded from the frame scan — review each",
+ "",
+ "Every window below is a moment the frame scan derived (a double-up, a bust,",
+ "the final table…) with a margin either side, widened to the transcript's",
+ "sentence edges. The scan reads a model's readings of sampled frames, so an",
+ "event can be wrong: check each in the bench before you keep it. Each clip's",
+ "on-screen subtitle is the running stats there; `frameScan.overlay` holds them",
+ "for a stats overlay (not rendered yet).",
+ "",
+ ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.channel}/${c.video} ${c.start}–${c.end} ${c.onscreen?.title ?? ""}: ${c.onscreen?.subtitle ?? ""}`),
+ );
} else if (seeded) {
lines.push(
"## Clips seeded from digest chapters — review each",
diff --git a/umtool/lib/scaffold-frames.test.mjs b/umtool/lib/scaffold-frames.test.mjs
@@ -0,0 +1,55 @@
+// `umtool new <slug> --from <channel>/<id> --seed frames` (release 30, lane P):
+// the draft supercut from a synthetic frame-scan sidecar in a temp tree.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { scaffoldReportVideo } from "./projects/scaffold.mjs";
+
+const SCAN = {
+ format: "archilyzer-frame-scan",
+ profile: "poker",
+ source: { savedVideo: "source-media.mp4", durationSeconds: 300 },
+ sampling: { everySeconds: 10, from: 0, to: 300 },
+ derived: {
+ tournaments: [{ key: "synthetic cup", name: "Synthetic Cup", from: 30, to: 200, series: { stack: [[30, 20000], [90, 41000], [180, 0]], playersLeft: [[30, 85]] }, facts: {} }],
+ events: [
+ { t: 90, kind: "double-up", detail: "20,000 → 41,000 chips (2.1×)", source: "series" },
+ { t: 180, kind: "bust", detail: "out from 41,000 chips", source: "series" },
+ ],
+ segments: [],
+ flags: [],
+ },
+};
+
+test("--seed frames: a clip per event, the stats as subtitles, the overlay block, a README checklist", async () => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-frames-seed-"));
+ try {
+ const channelsDir = path.join(tmp, "channels");
+ const dir = path.join(channelsDir, "synth-poker", "data", "synthstream1");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "frame-scan.poker.json"), JSON.stringify(SCAN));
+ await writeFile(path.join(dir, "transcript.cues.json"), JSON.stringify({ cues: [{ start: 66, end: 70, text: "Here we go." }, { start: 70, end: 80, text: "all in" }] }));
+ const r = await scaffoldReportVideo({ root: path.join(tmp, "reports"), slug: "poker-cut", from: "synth-poker/synthstream1", seed: "frames", channelsDir });
+ assert.equal(r.seeded, 2);
+ const doc = JSON.parse(await readFile(path.join(r.dir, "video.manifest.json"), "utf8"));
+ assert.deepEqual(doc.timeline.map((c) => [c.id, c.channel, c.video, c.onscreen.title]), [
+ ["f01", "synth-poker", "synthstream1", "Doubles up"],
+ ["f02", "synth-poker", "synthstream1", "Busts out"],
+ ]);
+ assert.equal(doc.timeline[0].onscreen.subtitle, "85 left · 41,000 chips");
+ assert.equal(doc.frameScan.file, "frame-scan.poker.json");
+ assert.equal(doc.frameScan.overlay.length, 2);
+ const readme = await readFile(path.join(r.dir, "README.md"), "utf8");
+ assert.match(readme, /Clips seeded from the frame scan/);
+ await assert.rejects(
+ scaffoldReportVideo({ root: path.join(tmp, "reports"), slug: "poker-cut-2", from: "synth-poker/none", seed: "frames", channelsDir }),
+ /no frame-scan\.poker\.json — run pnpm ops frame-scan first/,
+ );
+ await assert.rejects(scaffoldReportVideo({ root: path.join(tmp, "reports"), slug: "poker-cut-3", seed: "frames", channelsDir }), /--seed frames needs --from/);
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/frames-cut.mjs b/umtool/report-to-video/frames-cut.mjs
@@ -0,0 +1,163 @@
+// A frame scan → a DRAFT supercut (release 30, lane P): the events a frame
+// scan derived (frame-scan.<profile>.json beside the video) become clips of a
+// `video.manifest.json` timeline — a window around each event, cut on the
+// transcript's sentence edges where cues exist, overlapping windows merged —
+// and the scan's running stats become the manifest's `frameScan` block: what
+// a stats overlay draws over each clip (chips, big blinds, players left,
+// level), read at any second by `frameTotals`.
+//
+// Plain ESM with no I/O, ledger-totals.mjs's pattern: the scaffold (`umtool
+// new --seed frames`) calls it with the parsed sidecar, a future chrome region
+// calls `frameTotals` for its numbers, and `node --test` runs it with literals.
+// Every consumer gets the same arithmetic. No render here: the clips are a
+// draft to review in the bench, and the overlay is data until a region draws it.
+
+import { widen } from "yt-dlp-transcript-common/lib/cueWiden.mjs";
+
+/** Events worth a clip, most important first; the rest are left out. */
+export const CUT_EVENT_KINDS = ["won", "bust", "final-table", "knockout", "double-up", "big-pot", "big-loss", "all-in", "eliminated"];
+
+const TITLES = {
+ won: "Wins it",
+ bust: "Busts out",
+ eliminated: "Eliminated",
+ "final-table": "Final table",
+ "double-up": "Doubles up",
+ "big-loss": "Loses half the stack",
+ "all-in": "All in",
+ knockout: "Knocks one out",
+ "big-pot": "Takes a big pot",
+};
+
+export const FRAMES_CUT_DEFAULTS = Object.freeze({ pre: 20, post: 25, maxClips: 20, mergeGap: 5 });
+
+const fmt = (v) => (Number.isInteger(v) ? v.toLocaleString("en-US") : String(Math.round(v * 10) / 10));
+const round2 = (v) => Math.round(v * 100) / 100;
+
+/** The last value of a series at or before `t` (a series is [[t, v, …], …] sorted by t). */
+export function valueAt(series, t) {
+ let out = null;
+ for (const p of series ?? []) {
+ if (p[0] > t) break;
+ out = p[1];
+ }
+ return out;
+}
+
+/**
+ * The running stats at second `t`: the tournament the moment is in and the
+ * last value of each of its series (null where none was read yet). The one
+ * reducer the overlay and the clips' subtitles share.
+ */
+export function frameTotals(scan, t) {
+ const tours = scan?.derived?.tournaments ?? [];
+ const tour = tours.find((x) => t >= x.from && t < x.to) ?? [...tours].reverse().find((x) => x.from <= t) ?? null;
+ if (!tour) return null;
+ const s = tour.series ?? {};
+ return {
+ tournament: tour.key,
+ name: tour.name ?? tour.key,
+ stack: valueAt(s.stack, t),
+ stackBB: valueAt(s.stackBB, t),
+ playersLeft: valueAt(s.playersLeft, t),
+ level: valueAt(s.level, t),
+ };
+}
+
+/** "Level 4 · 60 left · 41,000 chips (137 BB)". */
+export function statsLine(totals) {
+ if (!totals) return "";
+ const parts = [];
+ if (totals.level !== null) parts.push(`Level ${fmt(totals.level)}`);
+ if (totals.playersLeft !== null) parts.push(`${fmt(totals.playersLeft)} left`);
+ if (totals.stack !== null) parts.push(`${fmt(totals.stack)} chips${totals.stackBB !== null ? ` (${fmt(totals.stackBB)} BB)` : ""}`);
+ else if (totals.stackBB !== null) parts.push(`${fmt(totals.stackBB)} BB`);
+ return parts.join(" · ");
+}
+
+/**
+ * The draft: `{ timeline, frameScan, skipped }`. `scan` is the parsed
+ * sidecar; `cues` the video's cues (sorted), or none. A window is
+ * `[t - pre, t + post]`, widened to sentence edges where cues exist, clamped
+ * to the video; windows within `mergeGap` of each other are one clip. At most
+ * `maxClips`, the most important events kept, in time order.
+ */
+export function framesCut(scan, { channel, video, cues = null, at = new Date().toISOString(), ...o } = {}) {
+ const opt = { ...FRAMES_CUT_DEFAULTS, ...o };
+ if (!channel || !video) throw new Error("framesCut needs the channel and the video");
+ const duration = scan?.source?.durationSeconds ?? scan?.sampling?.to ?? Infinity;
+ const rank = (k) => CUT_EVENT_KINDS.indexOf(k);
+ const events = (scan?.derived?.events ?? [])
+ .filter((e) => rank(e.kind) >= 0)
+ // A bust and the "eliminated" banner on the same moment are one event,
+ // and so is one kind seen twice within a minute (the log and the series).
+ .filter((e, _, all) => !(e.kind === "eliminated" && all.some((x) => x.kind === "bust" && Math.abs(x.t - e.t) <= 60)))
+ .filter((e, i, all) => !all.some((x, j) => j < i && x.kind === e.kind && Math.abs(x.t - e.t) <= 60));
+ const chosen = [...events].sort((a, b) => rank(a.kind) - rank(b.kind) || a.t - b.t).slice(0, opt.maxClips);
+ const skipped = events.length - chosen.length;
+ chosen.sort((a, b) => a.t - b.t);
+
+ const windows = chosen.map((e) => {
+ let start = Math.max(0, e.t - opt.pre);
+ let end = Math.min(duration, e.t + opt.post);
+ if (cues?.length) {
+ // Only ever WIDER, and only as far as widen's own budgets (8 s before,
+ // 12 s after): a cue past a silence is not this moment's sentence.
+ const w = widen(cues, start, end, { maxLead: 8, maxTail: 12 });
+ if (w.start <= start && w.start >= start - 8) start = Math.max(0, w.start);
+ if (w.end >= end && w.end <= end + 12) end = Math.min(duration, w.end);
+ }
+ return { start, end, events: [e] };
+ });
+ const merged = [];
+ for (const w of windows) {
+ const last = merged[merged.length - 1];
+ if (last && w.start <= last.end + opt.mergeGap) {
+ last.end = Math.max(last.end, w.end);
+ last.events.push(...w.events);
+ } else merged.push({ ...w, events: [...w.events] });
+ }
+
+ const timeline = merged.map((w, i) => {
+ const lead = [...w.events].sort((a, b) => rank(a.kind) - rank(b.kind))[0];
+ const totals = frameTotals(scan, lead.t);
+ return {
+ type: "clip",
+ id: `f${String(i + 1).padStart(2, "0")}`,
+ channel,
+ video,
+ start: round2(w.start),
+ end: round2(w.end),
+ cite: Math.floor(lead.t),
+ quote: "",
+ onscreen: { title: TITLES[lead.kind] ?? lead.kind, subtitle: statsLine(totals) || lead.detail },
+ // Code's draft (release 28's mark, `model: "code"`): no review row, and
+ // an edit makes it the operator's.
+ drafted: { onscreen: { task: "frames", model: "code", at, attempt: 1 } },
+ frameEvents: w.events.map((e) => ({ t: e.t, kind: e.kind, detail: e.detail })),
+ };
+ });
+
+ // The overlay track: the running stats at each clip's start and at every
+ // change inside it, in SOURCE seconds — what a stats region draws.
+ const overlay = timeline.map((c) => {
+ const changes = new Set([c.start]);
+ const tour = frameTotals(scan, c.cite);
+ const t = (scan?.derived?.tournaments ?? []).find((x) => x.key === tour?.tournament);
+ for (const series of Object.values(t?.series ?? {})) for (const p of series) if (p[0] > c.start && p[0] < c.end) changes.add(p[0]);
+ return { clip: c.id, points: [...changes].sort((a, b) => a - b).map((at) => ({ at, ...frameTotals(scan, at) })) };
+ });
+
+ return {
+ timeline,
+ frameScan: {
+ profile: scan?.profile ?? null,
+ file: scan?.profile ? `frame-scan.${scan.profile}.json` : null,
+ channel,
+ video,
+ tournaments: (scan?.derived?.tournaments ?? []).map((t) => ({ key: t.key, name: t.name ?? t.key, from: t.from, to: t.to })),
+ overlay,
+ },
+ skipped,
+ };
+}
diff --git a/umtool/report-to-video/frames-cut.test.mjs b/umtool/report-to-video/frames-cut.test.mjs
@@ -0,0 +1,95 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { framesCut, frameTotals, statsLine, valueAt } from "./frames-cut.mjs";
+
+// A synthetic frame-scan sidecar (the shape common/lib/frameScan-server.ts writes).
+const scan = () => ({
+ format: "archilyzer-frame-scan",
+ profile: "poker",
+ source: { savedVideo: "source-media.mp4", durationSeconds: 400 },
+ sampling: { everySeconds: 10, from: 0, to: 400 },
+ derived: {
+ tournaments: [
+ {
+ key: "synthetic cup",
+ name: "Synthetic Cup",
+ from: 30,
+ to: 200,
+ series: { stack: [[30, 20000], [90, 41000], [120, 9000], [180, 0]], stackBB: [[30, 100], [90, 136.7], [120, 22.5]], playersLeft: [[30, 85], [90, 60], [120, 9]], level: [[30, 3], [90, 4], [120, 5]] },
+ facts: {},
+ },
+ { key: "viewer $1000", name: "Viewer $1000", from: 250, to: 400, series: { stack: [[250, 1500], [300, 3100, "spoken"]] }, facts: {} },
+ ],
+ events: [
+ { t: 35, kind: "buy-in", detail: "said", source: "spoken" },
+ { t: 90, kind: "double-up", detail: "20,000 → 41,000 chips (2.1×)", source: "series" },
+ { t: 120, kind: "big-loss", detail: "41,000 → 9,000 chips", source: "series" },
+ { t: 120, kind: "final-table", detail: "9 players left", source: "series" },
+ { t: 180, kind: "bust", detail: "out from 9,000 chips", source: "series" },
+ { t: 180, kind: "eliminated", detail: "shown on screen", source: "frame" },
+ ],
+ segments: [],
+ flags: [],
+ },
+});
+
+test("valueAt, frameTotals, statsLine: the running stats at a second", () => {
+ assert.equal(valueAt([[30, 1], [90, 2]], 89), 1);
+ assert.equal(valueAt([[30, 1]], 10), null);
+ const at100 = frameTotals(scan(), 100);
+ assert.deepEqual(at100, { tournament: "synthetic cup", name: "Synthetic Cup", stack: 41000, stackBB: 136.7, playersLeft: 60, level: 4 });
+ assert.equal(statsLine(at100), "Level 4 · 60 left · 41,000 chips (136.7 BB)");
+ assert.equal(frameTotals(scan(), 310).stack, 3100);
+ assert.equal(frameTotals(scan(), 5), null);
+ assert.equal(statsLine(null), "");
+});
+
+test("framesCut: a clip around each event, overlapping windows merged, the most important event titles it", () => {
+ const { timeline, frameScan, skipped } = framesCut(scan(), { channel: "synth", video: "s1" });
+ assert.equal(skipped, 0);
+ // 90 (70–115) and 120 (100–145) overlap: one clip; 180 alone (the banner folded into the bust).
+ assert.deepEqual(timeline.map((c) => [c.id, c.start, c.end, c.cite, c.onscreen.title]), [
+ ["f01", 70, 145, 120, "Final table"],
+ ["f02", 160, 205, 180, "Busts out"],
+ ]);
+ assert.deepEqual(timeline[0].frameEvents.map((e) => e.kind), ["double-up", "final-table", "big-loss"]);
+ assert.equal(timeline[0].onscreen.subtitle, "Level 5 · 9 left · 9,000 chips (22.5 BB)");
+ assert.equal(timeline[1].quote, "");
+ assert.equal(timeline[0].drafted.onscreen.model, "code");
+ assert.equal(frameScan.file, "frame-scan.poker.json");
+ assert.deepEqual(frameScan.overlay[0].points.map((p) => [p.at, p.stack]), [[70, 20000], [90, 41000], [120, 9000]]);
+ assert.equal(frameScan.tournaments.length, 2);
+});
+
+test("framesCut: cut on sentence edges where cues exist, clamped to the video", () => {
+ const cues = [
+ { start: 60, end: 66, text: "so I shove." },
+ { start: 66, end: 72, text: "He calls with" },
+ { start: 72, end: 80, text: "queens and I hold." },
+ { start: 140, end: 150, text: "nine left now" },
+ { start: 150, end: 152, text: "here we go." },
+ ];
+ const { timeline } = framesCut(scan(), { channel: "synth", video: "s1", cues, pre: 20, post: 25 });
+ assert.equal(timeline[0].start, 66);
+ assert.equal(timeline[0].end, 152);
+});
+
+test("framesCut: at most maxClips, the most important kept, in time order", () => {
+ const { timeline, skipped } = framesCut(scan(), { channel: "synth", video: "s1", maxClips: 2, pre: 1, post: 1 });
+ assert.equal(skipped, 2);
+ assert.deepEqual(timeline.map((c) => c.onscreen.title), ["Final table", "Busts out"]);
+ assert.throws(() => framesCut(scan(), {}), /channel and the video/);
+});
+
+test("framesCut: a big pot and a knockout are clips; a plain pot is not; one kind twice within a minute is one", () => {
+ const sc = scan();
+ sc.derived.events = [
+ { t: 30, kind: "pot", detail: "takes the pot 1,600 (8 BB)", source: "log" },
+ { t: 60, kind: "big-pot", detail: "takes the pot 12,000 (60 BB)", source: "log" },
+ { t: 150, kind: "knockout", detail: "SynthHero knocked out Villain", source: "log" },
+ { t: 180, kind: "bust", detail: "out", source: "series" },
+ { t: 200, kind: "bust", detail: "SynthHero has finished the tournament in 9th", source: "log" },
+ ];
+ const { timeline } = framesCut(sc, { channel: "synth", video: "s1", pre: 5, post: 5 });
+ assert.deepEqual(timeline.map((c) => [c.cite, c.onscreen.title]), [[60, "Takes a big pot"], [150, "Knocks one out"], [180, "Busts out"]]);
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -26,6 +26,7 @@
"./deck": "./deck.mjs",
"./drafts-review": "./drafts-review.mjs",
"./factcheck": "./factcheck.mjs",
+ "./frames-cut": "./frames-cut.mjs",
"./ledger-totals": "./ledger-totals.mjs",
"./lint": "./lint.mjs",
"./local-media": "./local-media.mjs",