Archilyzer · Source

archilyzer

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

commit 923da42d00776d6f63d1c174e30c7d78abc25767
parent 034176331b0896382d79d099afd7908a575fd7e0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 17:13:35 -0400

editor, scripts: the frame scan's surfaces (release 30, lane P) — `pnpm ops frame-scan` (POST /api/ops/frame-scan: a frame-scan job, or `evict` the frame cache; the log's @@frame-scan result printed by --wait), and the video page's "Frame scan" panel: the phase strip, a stack and players-left chart per tournament, the events linked to the moment on the video's platform, the flags where a spoken number and a frame disagree, and a Scan button when the video is saved; the jobs list labels the `frames` progress; COMMANDS.md

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

Diffstat:
MCOMMANDS.md | 1+
Aeditor/app/api/ops/_frameScan.test.ts | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/frame-scan/route.ts | 33+++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/components/FrameScanControl.tsx | 20++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/components/FrameScanPanel.tsx | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/frameScanActions.ts | 19+++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/lib/frameScanView.test.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/lib/frameScanView.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 18++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 32++++++++++++++++++++++++++++++++
10 files changed, 548 insertions(+), 0 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"?} -&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}'` | | `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/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?, 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,48 @@ +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: 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"); + 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,104 @@ +// 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)] : [])), + })); + const events = r.derived.events.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` : ""); + 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 @@ -42,6 +42,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"; @@ -182,6 +185,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); @@ -202,6 +209,7 @@ export default async function VideoDetailPage({ coverage, panels, tagsView, + frameScans, }; }; const drive = config.dataDir?.trim(); @@ -231,6 +239,7 @@ export default async function VideoDetailPage({ coverage, panels, tagsView, + frameScans, } = loaded; const registry = getRegistry(); @@ -356,6 +365,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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -118,6 +118,8 @@ // 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","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 +449,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 +481,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 +712,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, @@ -1407,6 +1419,26 @@ 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), "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", …}.',