Archilyzer · Source

archilyzer

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

commit 16a8993f3e7b0e494f1200292fa8f317ec9aa714
parent ae4eb5b30d1924fac50583cf9c2dc3f8b13f0241
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 18:09:15 -0400

common, editor, umtool, mcp, scripts: the frame scan calibrated on the first stream's frames (read locally, nothing committed) — a crop ([x, y, w, h] fractions: the part read and hashed, the poker client and not the webcam), prompt version 2 (the stats header, the dealer log copied line by line, the hero's bounty, the break countdown, an action label in a name box), the log's pots (big at 25 BB), knockouts, busts, blinds and finishing places, another tournament after the hero is out, the position, average-stack and big-blind series, blinds carried until they change, `fresh` (read again, another model), `hero` and `crop` kept for the next run; the panel counts the small pots; the supercut takes big pots and knockouts and folds one kind seen twice in a minute; the mcp preset test names `frames`; ops help, COMMANDS.md, FACTS

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

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/frameScan.ts | 20++++++++++++++++++--
Mcommon/lib/frameScan-server.ts | 4+++-
Mcommon/lib/frames/poker.test.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/frames/poker.ts | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/frames/sample-server.ts | 35++++++++++++++++++++++++++++++-----
Mcommon/lib/frames/scan.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/frames/scan.ts | 25+++++++++++++++++++------
Mcommon/lib/frames/types.ts | 7++++---
Meditor/app/api/ops/frame-scan/route.ts | 2+-
Meditor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts | 7+++++--
Meditor/app/channels/[slug]/videos/[id]/lib/frameScanView.ts | 7+++++--
Aeditor/e2e/frame-scan.spec.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/generation.test.ts | 2++
Mplans/FACTS.md | 19++++++++++++-------
Mscripts/archilyzer-ops.mjs | 6+++++-
Mumtool/report-to-video/frames-cut.mjs | 10+++++++---
Mumtool/report-to-video/frames-cut.test.mjs | 13+++++++++++++
18 files changed, 437 insertions(+), 45 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -151,7 +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"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | | `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "verdict", "at", "note"?} -&gt; {proposal}. "verdict" and "at" are the proposal you were shown (its verdicts.proposed.json entry): a compare-and-set, refused (409) when the proposal was replaced or reviewed since, its claim changed (the proposal is stale) or was ruled meanwhile. approve sets the claim's verdict to it (through the registry); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'` | | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | -| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "evict"?} -&gt; {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.&lt;profile&gt;.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'` | +| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?} -&gt; {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.&lt;profile&gt;.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -&gt; {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -&gt; {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | ### Usage, flags and environment diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts @@ -11,6 +11,10 @@ // 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 @@ -35,7 +39,7 @@ 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, removeFrameCache } from "../lib/frames/sample-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"; @@ -44,7 +48,7 @@ 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", "evict"] as const; +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) { @@ -65,6 +69,8 @@ export type FrameScanBody = { maxUsd?: number; hero?: string; framesPerAsk?: number; + crop?: Crop; + fresh?: boolean; evict?: boolean; }; @@ -110,6 +116,14 @@ export function parseFrameScanBody(b: Record<string, unknown>): FrameScanBody { 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; @@ -222,6 +236,8 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame 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, diff --git a/common/lib/frameScan-server.ts b/common/lib/frameScan-server.ts @@ -38,8 +38,10 @@ export type FrameScanRecord = { version: 1; profile: string; source: { savedVideo: string; durationSeconds: number | null }; - sampling: { everySeconds: number; from: number; to: number; width: number; keyframesOnly: boolean; frames: number; kept: number; skippedDuplicates: number }; + 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>)[]; diff --git a/common/lib/frames/poker.test.ts b/common/lib/frames/poker.test.ts @@ -173,3 +173,69 @@ 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 @@ -41,9 +41,13 @@ export type PokerReading = { prizePool?: number; position?: number; payout?: number; + averageStack?: number; }; - hero?: { stack?: number; bb?: number; seat?: number; cards?: string[] }; + 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; }; @@ -72,16 +76,18 @@ const READING_SCHEMA = { prizePool: num, position: int, payout: num, + averageStack: num, }, }, hero: { type: "object", - properties: { stack: num, stackInBigBlinds: num, seat: int, cards }, + 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"], @@ -102,11 +108,14 @@ export function pokerSystem(hints: { hero?: string } = {}): string { "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 for a break, a paused or a starting-soon screen; other for anything else (a camera, a desktop, a browser, a chat).", + "- 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; level the blind level's number; smallBlind, bigBlind and ante the current blinds; playersLeft and totalPlayers the field (as in a players-left or a rank-of-field display); position the hero's rank in the field when shown; payout the money the hero has won or is guaranteed, when shown; prizePool when shown.", + "- 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.", @@ -142,6 +151,16 @@ const prune = <T extends Record<string, unknown>>(o: T): T | 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; @@ -162,6 +181,7 @@ export function coercePokerReading(raw: unknown): PokerReading | null { 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; @@ -169,7 +189,7 @@ export function coercePokerReading(raw: unknown): PokerReading | null { } 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) }); + 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; @@ -178,6 +198,8 @@ export function coercePokerReading(raw: unknown): PokerReading | null { 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; } @@ -193,15 +215,21 @@ const MISREAD: Record<string, AgreeRule> = { 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"]); +const SPOKEN_SERIES = new Set(["stack", "stackBB", "playersLeft", "level", "position", "averageStack", "bigBlind"]); const SPOKEN_WINDOW_S = 90; const FINAL_TABLE = 9; @@ -219,17 +247,35 @@ function keyReadings(rs: readonly R[]): { keys: (string | null)[]; names: Map<st 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); @@ -258,6 +304,9 @@ const FIELDS: { field: string; of: (r: R) => number | 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 })); @@ -266,15 +315,22 @@ 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 }): Derived { - const rs = [...readingsIn].sort((a, b) => a.t - b.t); +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[]>(); - rs.forEach((r, i) => { + // 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); }); @@ -319,7 +375,7 @@ export function derivePoker(readingsIn: readonly R[], spoken: readonly SpokenRea 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), ...spokenEvents(spoken)].sort((a, b) => a.t - b.t || a.kind.localeCompare(b.kind)); + 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) }; } @@ -397,6 +453,80 @@ function seriesEvents(tournaments: readonly DerivedTournament[], full: ReadonlyM 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[] { @@ -435,7 +565,8 @@ function crossCheck(tournaments: DerivedTournament[], spoken: readonly SpokenRea export const POKER_PROFILE: FrameProfile<PokerReading> = { id: "poker", - promptVersion: 1, + // 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, diff --git a/common/lib/frames/sample-server.ts b/common/lib/frames/sample-server.ts @@ -27,9 +27,29 @@ 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`; @@ -87,7 +107,11 @@ function runCapture(cmd: string, args: string[], signal?: AbortSignal): Promise< } /** 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 }): string[] { +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", @@ -101,7 +125,7 @@ export function batchArgs(o: { source: string; start: number; seconds: number; e "-i", o.source, "-filter_complex", - `[0:v]fps=1/${o.every}:round=near,split=2[a][b];[a]scale=${o.width}:-2:flags=area[big];[b]scale=${THUMB_W}:${THUMB_H}:flags=area,format=gray[small]`, + `[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", @@ -131,6 +155,7 @@ export async function sampleFrames(o: { every: number; width: number; keyframesOnly?: boolean; + crop?: Crop; batchSeconds?: number; ffmpeg?: string; signal?: AbortSignal; @@ -140,7 +165,7 @@ export async function sampleFrames(o: { 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; + 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[])); @@ -148,7 +173,7 @@ export async function sampleFrames(o: { } 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, frames: [] }; + 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; @@ -167,7 +192,7 @@ export async function sampleFrames(o: { 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 }), + 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); diff --git a/common/lib/frames/scan.test.ts b/common/lib/frames/scan.test.ts @@ -268,3 +268,33 @@ test("maxFrames bounds a scan's range and says so", async () => { 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 @@ -19,7 +19,7 @@ import { CancelledError } from "../llm/anthropic"; import { PromptTooLargeError } from "../llm/ollama"; import { duplicatesOf } from "./dhash"; import { frameProfile } from "./profiles"; -import { probeDuration, sampleFrames, type FrameIndex } from "./sample-server"; +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"; @@ -44,7 +44,13 @@ export type FrameScanOptions = { 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; @@ -125,7 +131,9 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr log(`the range would be over ${maxFrames} frames: scanning ${from}–${to} s only (raise maxFrames or everySeconds)`); } - log(`sampling ${from}–${Math.round(to)} s every ${every} s at ${profile.width} px wide into ${o.cacheDir}`); + // 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, @@ -134,6 +142,7 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr 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 }), @@ -142,12 +151,14 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr 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]>(); - for (const r of prev?.readings ?? []) readings.set(r.t, r); + 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]); - const system = profile.system(o.hints ?? {}); + // 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; @@ -158,7 +169,7 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr // 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>(); - for (const [t, src] of prev?.duplicates ?? []) if (t < from || t >= to) dupPairs.set(t, src); + 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); @@ -184,17 +195,19 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr 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 } : {}) }), + derived: profile.derive(expanded as never, spoken, { everySeconds: every, ...(duration !== null ? { durationSeconds: duration } : {}), ...(hints.hero ? { hero: hints.hero } : {}) }), updatedAt: now().toISOString(), }; }; diff --git a/common/lib/frames/types.ts b/common/lib/frames/types.ts @@ -33,8 +33,9 @@ export type DerivedEvent = { t: number; kind: string; detail: string; - // Where it came from: the model's reading of a frame, the series, or the transcript. - source: "frame" | "series" | "spoken"; + // 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; }; @@ -83,7 +84,7 @@ export type FrameProfile<R extends { phase: string }> = { // 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 }): Derived; + derive(readings: (R & { t: number })[], spoken: SpokenReading[], o: { everySeconds: number; durationSeconds?: number; hero?: string }): Derived; }; export const FRAME_SCAN_FORMAT = "archilyzer-frame-scan"; diff --git a/editor/app/api/ops/frame-scan/route.ts b/editor/app/api/ops/frame-scan/route.ts @@ -6,7 +6,7 @@ import { jobResponse, ops } from "../_lib"; export const dynamic = "force-dynamic"; // POST { slug, id, profile?, everySeconds?, from?, to?, maxFrames?, model?, -// maxUsd?, hero?, framesPerAsk?, evict? } +// 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 diff --git a/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts b/editor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts @@ -17,7 +17,10 @@ const record = (): FrameScanRecord => ({ 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: 90, kind: "double-up", detail: "20,000 → 41,000 chips (2.1×)", source: "series", tournament: "synthetic cup" }], + 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 }], @@ -43,6 +46,6 @@ test("frameScanView: strip, charts, events with links, flags, summary", () => { 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"); + 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 @@ -86,7 +86,9 @@ export function frameScanView(r: FrameScanRecord, webpageUrl: string | null): Fr 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)] : [])), })); - const events = r.derived.events.map((e) => ({ + // 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, @@ -99,6 +101,7 @@ export function frameScanView(r: FrameScanRecord, webpageUrl: string | null): Fr 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` : ""); + (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/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 of ${ID}` }).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 frames of ${ID}` })).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/plans/FACTS.md b/plans/FACTS.md @@ -9611,18 +9611,23 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `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, frames: [{t, file, hash}]}`. Evictable (`frame-scan {evict}`); + `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, frames, kept, skippedDuplicates}, model: - {route, model, promptVersion}, costUsd (all runs), runs: [{at, jobId?, model, route, frames, read, failed, costUsd, - stopped?: cap|cancelled|errors|maxFrames}], readings: [{t, phase, tournament?, hero?, hand?, event?}] (read frames - only), duplicates: [[t, the read frame's t]], spoken: [{t, field, value, text, approx?}], derived: {tournaments: - [{key, name?, from, to, series: {stack, stackBB, playersLeft, level: [[t, v] | [t, v, "spoken"]]}, facts}], events: - [{t, kind, detail, source: frame|series|spoken, tournament?}], segments: [{from, to, phase, tournament?}], flags: + 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. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -119,6 +119,7 @@ // 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"}' @@ -1424,7 +1425,10 @@ export function usage() { " 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), "evict"?} -> {jobId, model,', + ' 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", diff --git a/umtool/report-to-video/frames-cut.mjs b/umtool/report-to-video/frames-cut.mjs @@ -15,7 +15,7 @@ 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", "double-up", "big-loss", "all-in", "eliminated"]; +export const CUT_EVENT_KINDS = ["won", "bust", "final-table", "knockout", "double-up", "big-pot", "big-loss", "all-in", "eliminated"]; const TITLES = { won: "Wins it", @@ -25,6 +25,8 @@ const TITLES = { "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 }); @@ -87,8 +89,10 @@ export function framesCut(scan, { channel, video, cues = null, at = new Date().t 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. - .filter((e, _, all) => !(e.kind === "eliminated" && all.some((x) => x.kind === "bust" && Math.abs(x.t - e.t) <= 60))); + // 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); diff --git a/umtool/report-to-video/frames-cut.test.mjs b/umtool/report-to-video/frames-cut.test.mjs @@ -80,3 +80,16 @@ test("framesCut: at most maxClips, the most important kept, in time order", () = 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"]]); +});