Archilyzer · Source

archilyzer

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

commit 9e9f9e990dd6ab02033f47dfa2dbaa9f72d9761d
parent 05348da09cf3062fe9d66e749c4fef9dc90ca003
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 16:40:33 -0400

common: a person corrects a frame reading with no model, and the channel report tallies the audio audit's verdicts

- lib/frames/corrections.ts: a reading's correction (`set` field → value, or
  `misread`), checked per field kind, kept beside the model's readings in the
  sidecar's `corrections` and laid over them by deriveOf (a duplicate copies
  the corrected reading; a misread is copied nowhere). Every run and every
  re-derive keeps them.
- controller/frameCorrections.ts: frameReadingAt (the reading nearest a
  second, as read and as used) and correctFrameReading (only what differs is
  stored; re-derives at once; refused while a scan of the video is queued or
  running). frameScanBusy factored out of the rederive path.
- channelSnapshot: `audioIntegrity` {clean, damaged, undecodable, stale,
  lastCheckedAt} over every audio-integrity.json, read where the bucket
  already reads it.

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

Diffstat:
Mcommon/controller/audioAudit.test.ts | 6++++++
Mcommon/controller/channelSnapshot.ts | 47++++++++++++++++++++++++++++++++++++++++++++---
Acommon/controller/frameCorrections.test.ts | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/frameCorrections.ts | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/frameScan.ts | 12++++++++----
Mcommon/lib/frameScan-server.ts | 10+++++++++-
Acommon/lib/frames/corrections.test.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/frames/corrections.ts | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/frames/scan.ts | 25++++++++++++++++++++-----
9 files changed, 754 insertions(+), 13 deletions(-)

diff --git a/common/controller/audioAudit.test.ts b/common/controller/audioAudit.test.ts @@ -240,6 +240,10 @@ test("the report: damaged untranscribed held audio is corruptHeldAudio, out of d assert.deepEqual(snap.buckets.corruptHeldAudio, ["bbbb0000002"]); assert.deepEqual(snap.buckets.downloadedNoTranscript, ["aaaa0000001"]); assert.deepEqual(snap.buckets.corruptFullSource, ["dddd0000004"]); + // The channel's tally of the audit's verdicts (release 32): the page's counts. + const { lastCheckedAt, ...tally } = snap.audioIntegrity!; + assert.deepEqual(tally, { clean: 1, damaged: 2, undecodable: 0, stale: 0 }); + assert.ok(lastCheckedAt && !Number.isNaN(Date.parse(lastCheckedAt))); // A transcribed damaged file is not in the bucket (its transcript stands)… assert.ok(!snap.buckets.corruptHeldAudio.includes("cccc0000003")); // …unless its transcript is a salvage. @@ -259,6 +263,8 @@ test("the report: damaged untranscribed held audio is corruptHeldAudio, out of d const snap3 = await generateChannelSnapshot(f.paths, SLUG); assert.deepEqual(snap3.buckets.corruptHeldAudio, ["cccc0000003"]); assert.ok(snap3.buckets.downloadedNoTranscript.includes("bbbb0000002")); + assert.equal(snap3.audioIntegrity?.stale, 1); + assert.equal(snap3.audioIntegrity?.damaged, 1); await rm(f.root, { recursive: true, force: true }); }); diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -59,7 +59,9 @@ import { loadAudioIntegrity } from "../lib/audioIntegrity-server"; import { AUDIO_INTEGRITY_FILENAME, integrityMatches, + integrityVerdict, isDamagedIntegrity, + type AudioIntegrityVerdict, } from "../lib/audioIntegrity"; import { chatOnlyIdsFrom, @@ -106,6 +108,19 @@ export type ExcludedFromDownload = { private: string[]; }; +// The audio audit's verdicts over a channel's video dirs (release 32, lane +// R3): one count per audio-integrity.json — clean, damaged or undecodable by +// the rule in force (integrityVerdict), or stale when the record no longer +// speaks for the file (gone, or a different size). `lastCheckedAt` is the +// newest record's checkedAt. +export type AudioIntegrityTally = { + clean: number; + damaged: number; + undecodable: number; + stale: number; + lastCheckedAt?: string; +}; + export type ChannelSnapshot = { generatedAt: string; totals: { @@ -435,6 +450,9 @@ export type ChannelSnapshot = { // fifth gate: the real gate needs a live probe, and folding a guess into the // hero figure would move the sidebar badge and /cleanup's Est. reclaim too. reclaimableAtRiskBytes?: number; + // The audio audit's verdicts over the channel (release 32). Optional: older + // snapshots lack it; readers show nothing until the next regen. + audioIntegrity?: AudioIntegrityTally; }; // The four holds, in sweep order. Same shape for bytes and for counts. @@ -1037,13 +1055,22 @@ export async function generateChannelSnapshot( // file is gone or its size changed (the size is the lstat above; no // extra stat — an unknown size, a drive not answering, counts the name). let heldAudioDamaged = false; + // The record's standing for the channel's audit tally (release 32): + // its verdict by the rule in force, or stale when it no longer speaks + // for the file. + let integrityState: AudioIntegrityVerdict | "stale" | null = null; + let integrityCheckedAt: string | null = null; if (files.entries.includes(AUDIO_INTEGRITY_FILENAME)) { const integrity = await loadAudioIntegrity(dir); - heldAudioDamaged = + const current = integrity !== null && files.audioFiles.includes(integrity.file) && - integrityMatches(integrity, { name: integrity.file, size: audioSizes[integrity.file] }) && - isDamagedIntegrity(integrity); + integrityMatches(integrity, { name: integrity.file, size: audioSizes[integrity.file] }); + heldAudioDamaged = current && isDamagedIntegrity(integrity); + if (integrity) { + integrityState = current ? integrityVerdict(integrity) : "stale"; + integrityCheckedAt = integrity.checkedAt; + } } // Only transcribed (non-untranscribable) dirs can have a truncated // transcript; skip the cues.json read for everything else. @@ -1105,6 +1132,8 @@ export async function generateChannelSnapshot( outcome, salvaged, heldAudioDamaged, + integrityState, + integrityCheckedAt, coverage, vttProvenance, digest, @@ -1222,6 +1251,9 @@ export async function generateChannelSnapshot( const incompleteTranscript: string[] = []; const salvagedTranscript: string[] = []; const corruptHeldAudio: string[] = []; + // The audio audit's verdicts over the channel (release 32): every + // audio-integrity.json, by the rule in force. + const audioIntegrity: AudioIntegrityTally = { clean: 0, damaged: 0, undecodable: 0, stale: 0 }; const shortAudio: string[] = []; const autoSubsOnly: string[] = []; const downloadedAutoSubsOnly: string[] = []; @@ -1268,11 +1300,19 @@ export async function generateChannelSnapshot( outcome, salvaged, heldAudioDamaged, + integrityState, + integrityCheckedAt, coverage, vttProvenance, digest, } of perVideo) { if (isVideoTranscribed(files)) transcribed++; + if (integrityState) { + audioIntegrity[integrityState]++; + if (integrityCheckedAt && (!audioIntegrity.lastCheckedAt || integrityCheckedAt > audioIntegrity.lastCheckedAt)) { + audioIntegrity.lastCheckedAt = integrityCheckedAt; + } + } if (isVideoDownloaded(files)) downloaded++; totalMediaBytes += mediaBytes; totalTextBytes += textBytes; @@ -1810,6 +1850,7 @@ export async function generateChannelSnapshot( heldAudioBytes, heldAudioCounts, reclaimableAtRiskBytes, + audioIntegrity, }; await writeChannelSnapshot(paths, slug, snapshot); diff --git a/common/controller/frameCorrections.test.ts b/common/controller/frameCorrections.test.ts @@ -0,0 +1,115 @@ +// The video page's reading correction (release 32, lane R3), over a temp +// channel: the reading nearest a second (a duplicate shown as its copy), a +// save that keeps only what differs from the model's reading, a misread, a +// clear — each re-deriving at once, with no model and no frame. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { syntheticPokerHighlights } from "../testing/frames/pokerReadings.mjs"; +import { frameScanSidecar, loadFrameScan, type FrameScanRecord } from "../lib/frameScan-server"; +import type { Paths } from "../lib/paths"; +import { correctFrameReading, frameReadingAt } from "./frameCorrections"; + +const SLUG = "synth-channel"; +const ID = "vid1"; +const fx = syntheticPokerHighlights(); +const NOW = () => new Date("2026-10-16T12:00:00Z"); + +async function setup(): Promise<{ paths: Paths; videoDir: string; done: () => Promise<void> }> { + const root = await mkdtemp(path.join(os.tmpdir(), "frame-corrections-")); + const channelsDir = path.join(root, "channels"); + const videoDir = path.join(channelsDir, SLUG, "data", ID); + await mkdir(videoDir, { recursive: true }); + // 2905 is a duplicate of the read frame at 2900. + const rec = { + format: "archilyzer-frame-scan", + version: 1, + profile: "poker", + source: { savedVideo: "source-media.mp4", durationSeconds: 3000 }, + sampling: { everySeconds: 10, from: 0, to: 3000, width: 1280, keyframesOnly: true, frames: 300, kept: 299, skippedDuplicates: 1 }, + model: { route: "api", model: "claude-haiku-4-5", promptVersion: 3 }, + hints: { hero: fx.hero }, + costUsd: 0.5, + runs: [], + readings: fx.readings, + duplicates: [[2905, 2900]], + spoken: fx.spoken, + derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] }, + updatedAt: "2026-10-15T00:00:00Z", + } as unknown as FrameScanRecord; + await frameScanSidecar("poker").write(videoDir, rec); + return { paths: { channelsDir } as Paths, videoDir, done: () => rm(root, { recursive: true, force: true }) }; +} + +test("frameReadingAt: the nearest reading, its fields as read and as used, the seconds either side; refusals", async () => { + const { paths, done } = await setup(); + try { + const r = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 1003 }); + assert.ok(r.ok, JSON.stringify(r)); + assert.equal(r.view.t, 1000); + assert.equal(r.view.prev, 990); + assert.equal(r.view.next, 1010); + assert.equal(r.view.copyOf, null); + const stack = r.view.fields.find((f) => f.path === "hero.stack")!; + assert.equal(stack.read, 0); + assert.equal(stack.value, 0); + assert.equal(stack.corrected, false); + const dup = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 2906 }); + assert.ok(dup.ok); + assert.equal(dup.view.t, 2905); + assert.equal(dup.view.copyOf, 2900); + assert.equal(dup.view.prev, 2900); + assert.match(((await frameReadingAt(paths, { slug: SLUG, id: "nope", t: 1 })) as { error: string }).error, /has no frame-scan\.poker\.json/); + assert.match(((await frameReadingAt(paths, { slug: "../x", id: ID, t: 1 })) as { error: string }).error, /channel slug/); + } finally { + await done(); + } +}); + +test("correctFrameReading: only what differs is kept; the derivation uses it at once; a misread; a clear; the model's reading untouched", async () => { + const { paths, videoDir, done } = await setup(); + try { + const before = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 1500 }); + assert.ok(before.ok); + // The form sends every field; only the stack differs. + const set = Object.fromEntries(before.view.fields.map((f) => [f.path, f.value])); + set["hero.stack"] = "133,333"; + const saved = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set }, { now: NOW }); + assert.ok(saved.ok, JSON.stringify(saved)); + assert.deepEqual(saved.correction, { t: 1500, at: "2026-10-16T12:00:00.000Z", by: "person", set: { "hero.stack": 133333 } }); + assert.equal(saved.view.fields.find((f) => f.path === "hero.stack")!.corrected, true); + let rec = (await loadFrameScan(videoDir, "poker"))!; + assert.deepEqual(rec.corrections, [saved.correction]); + assert.equal((rec.readings.find((r) => r.t === 1500)!.hero as { stack: number }).stack, 120000, "the model's reading stays as read"); + assert.equal(rec.rederivedAt, "2026-10-16T12:00:00.000Z"); + assert.ok(rec.derived.tournaments.length >= 1, "derived again"); + + // The reading at 2900 set aside (its duplicate at 2905 with it). + const mis = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 2900, misread: true, note: "not the hero's seat" }, { now: NOW }); + assert.ok(mis.ok); + assert.equal(mis.view.misread, true); + const dup = await frameReadingAt(paths, { slug: SLUG, id: ID, t: 2905 }); + assert.ok(dup.ok && dup.view.misread, "a duplicate of a misread is set aside too"); + rec = (await loadFrameScan(videoDir, "poker"))!; + assert.deepEqual(rec.corrections!.map((c) => c.t), [1500, 2900]); + assert.ok(rec.derived.events.every((e) => e.t !== 2900), JSON.stringify(rec.derived.events.filter((e) => e.t >= 2890))); + + // A save that differs in nothing removes the correction; a clear does too. + const same = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set: { "hero.stack": 120000 } }, { now: NOW }); + assert.ok(same.ok && same.correction === null); + const cleared = await correctFrameReading(paths, { slug: SLUG, id: ID, t: 2900, clear: true }, { now: NOW }); + assert.ok(cleared.ok); + rec = (await loadFrameScan(videoDir, "poker"))!; + assert.equal(rec.corrections, undefined); + + // Refusals. + assert.match(((await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1234, misread: true })) as { error: string }).error, /no frame was read at 1234 s/); + assert.match(((await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set: { "hero.stack": -5 } })) as { error: string }).error, /Hero stack/); + assert.match(((await correctFrameReading(paths, { slug: SLUG, id: ID, t: 1500, set: { bogus: 1 } })) as { error: string }).error, /"bogus" is not a field/); + } finally { + await done(); + } +}); diff --git a/common/controller/frameCorrections.ts b/common/controller/frameCorrections.ts @@ -0,0 +1,198 @@ +// A PERSON CORRECTS A FRAME READING, with no model (release 32, lane R3): the +// video page's Frame scan panel opens the reading at a second, shows what the +// model read beside what the derivation now uses, and saves the person's +// values (or "misread") into the sidecar's `corrections` +// (lib/frames/corrections.ts) — then works `derived` out again at once, as +// `frame-scan {rederive: true}` does. Never while a scan of the video is +// queued or running (it writes the same sidecar). +// +// Only what differs from the model's reading is stored, so a form may send +// every field it shows; a save that differs in nothing (and is not a misread) +// removes the correction. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { frameScanSidecar, type FrameScanRecord } from "../lib/frameScan-server"; +import { isFrameProfile } from "../lib/frames/profiles"; +import { rederiveRecord } from "../lib/frames/scan"; +import { + CorrectionInputError, + checkCorrectionSet, + correctableFields, + correctedReading, + readField, + upsertCorrection, + type CorrectableField, + type CorrectionValue, + type ReadingCorrection, +} from "../lib/frames/corrections"; +import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments"; +import { frameScanBusy, loadCues, rederivedSummary, type FrameScanRederived } from "./frameScan"; + +type Reading = FrameScanRecord["readings"][number]; + +export type FrameReadingField = CorrectableField & { + // What the model read (undefined: not shown), and what the derivation uses. + read: CorrectionValue; + value: CorrectionValue; + corrected: boolean; +}; + +export type FrameReadingView = { + profile: string; + t: number; + // A duplicate frame: the read frame it copies. + copyOf: number | null; + correction: ReadingCorrection | null; + misread: boolean; + fields: FrameReadingField[]; + // The grid seconds before and after, for stepping. + prev: number | null; + next: number | null; +}; + +const norm = (v: unknown): CorrectionValue => (v === undefined || v === "" ? null : (v as CorrectionValue)); +const same = (a: unknown, b: unknown) => JSON.stringify(norm(a)) === JSON.stringify(norm(b)); + +function gridOf(rec: FrameScanRecord): number[] { + const ts = new Set<number>(rec.readings.map((r) => r.t)); + for (const [t] of rec.duplicates ?? []) ts.add(t); + return [...ts].sort((a, b) => a - b); +} + +// The model's reading at `t` (a duplicate's is its source's, at `t`). +function modelReadingAt(rec: FrameScanRecord, t: number): { reading: Reading; copyOf: number | null } | null { + const byT = new Map(rec.readings.map((r) => [r.t, r])); + const own = byT.get(t); + if (own) return { reading: own, copyOf: null }; + const dup = (rec.duplicates ?? []).find(([d]) => d === t); + const src = dup ? byT.get(dup[1]) : undefined; + return src ? { reading: { ...src, t }, copyOf: dup![1] } : null; +} + +function videoDirOf(paths: Paths, slug: string, id: string): string { + return path.join(paths.channelsDir, slug, "data", id); +} + +function checkRef(o: { slug: unknown; id: unknown; profile?: unknown }): { slug: string; id: string; profile: string } { + if (typeof o.slug !== "string" || !isSafeChannelSegment(o.slug)) throw new CorrectionInputError(`"slug" must be a channel slug`); + if (typeof o.id !== "string" || !isSafeIdSegment(o.id)) throw new CorrectionInputError(`"id" must be a video id`); + const profile = o.profile ?? "poker"; + if (!isFrameProfile(profile)) throw new CorrectionInputError(`"${String(profile)}" is not a frame-scan profile`); + return { slug: o.slug, id: o.id, profile }; +} + +function viewOf(rec: FrameScanRecord, t: number): FrameReadingView | null { + const model = modelReadingAt(rec, t); + if (!model) return null; + // The derivation lays a correction made at a copy's second, or at its + // source's, over the copy (deriveOf); the panel shows the same. + const corrections = rec.corrections ?? []; + const own = corrections.find((c) => c.t === t) ?? null; + const fromSource = model.copyOf !== null ? (corrections.find((c) => c.t === model.copyOf) ?? null) : null; + let effective: Reading | null = model.reading; + if (fromSource) effective = effective && correctedReading(effective, fromSource); + if (own) effective = effective && correctedReading(effective, own); + const grid = gridOf(rec); + const i = grid.indexOf(t); + return { + profile: rec.profile, + t, + copyOf: model.copyOf, + correction: own, + misread: effective === null, + fields: correctableFields(rec.profile).map((f) => { + const read = norm(readField(model.reading, f.path)); + const value = effective ? norm(readField(effective, f.path)) : read; + return { ...f, read, value, corrected: !same(read, value) }; + }), + prev: i > 0 ? grid[i - 1]! : null, + next: i >= 0 && i < grid.length - 1 ? grid[i + 1]! : null, + }; +} + +/** The reading nearest `t` (a read frame or a duplicate), as the panel shows it. */ +export async function frameReadingAt( + paths: Paths, + raw: { slug: unknown; id: unknown; profile?: unknown; t: unknown }, +): Promise<{ ok: true; view: FrameReadingView } | { ok: false; error: string }> { + let ref; + try { + ref = checkRef(raw); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const t = typeof raw.t === "number" ? raw.t : Number(raw.t); + if (!Number.isFinite(t) || t < 0) return { ok: false, error: "give a time, in seconds or h:mm:ss" }; + const sidecar = frameScanSidecar(ref.profile); + const rec = await sidecar.load(videoDirOf(paths, ref.slug, ref.id)); + if (!rec) return { ok: false, error: `${ref.slug}/${ref.id} has no ${sidecar.filename}` }; + const grid = gridOf(rec); + if (grid.length === 0) return { ok: false, error: "the scan holds no readings" }; + const nearest = grid.reduce((best, x) => (Math.abs(x - t) < Math.abs(best - t) ? x : best), grid[0]!); + return { ok: true, view: viewOf(rec, nearest)! }; +} + +export type CorrectFrameReadingResult = + | { ok: true; correction: ReadingCorrection | null; view: FrameReadingView; rederived: FrameScanRederived } + | { ok: false; error: string }; + +/** + * Save a person's correction of the reading at `t` and re-derive. + * set field → value (every field a form shows may be sent; only the + * ones that differ from the model's reading are kept) + * misread the whole reading set aside + * clear the correction at `t` removed + */ +export async function correctFrameReading( + paths: Paths, + raw: { slug: unknown; id: unknown; profile?: unknown; t: unknown; set?: unknown; misread?: unknown; clear?: unknown; note?: unknown }, + o: { now?: () => Date } = {}, +): Promise<CorrectFrameReadingResult> { + let ref; + let set: Record<string, CorrectionValue> | undefined; + try { + ref = checkRef(raw); + set = checkCorrectionSet(ref.profile, raw.set); + if (raw.misread !== undefined && typeof raw.misread !== "boolean") throw new CorrectionInputError(`"misread" is true or false`); + if (raw.clear !== undefined && typeof raw.clear !== "boolean") throw new CorrectionInputError(`"clear" is true or false`); + if (raw.note !== undefined && typeof raw.note !== "string") throw new CorrectionInputError(`"note" is text`); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const t = typeof raw.t === "number" ? raw.t : NaN; + if (!Number.isFinite(t)) return { ok: false, error: `"t" is the reading's second` }; + if (frameScanBusy(ref.slug, ref.id)) { + return { ok: false, error: `a frame scan of ${ref.slug}/${ref.id} is queued or running — correct it when the scan is done (it writes the sidecar)` }; + } + const videoDir = videoDirOf(paths, ref.slug, ref.id); + const sidecar = frameScanSidecar(ref.profile); + const rec = await sidecar.load(videoDir); + if (!rec) return { ok: false, error: `${ref.slug}/${ref.id} has no ${sidecar.filename} — scan it first` }; + const model = modelReadingAt(rec, t); + if (!model) return { ok: false, error: `no frame was read at ${t} s` }; + + let correction: ReadingCorrection | null = null; + if (raw.clear !== true) { + const diff: Record<string, CorrectionValue> = {}; + for (const [p, v] of Object.entries(set ?? {})) if (!same(readField(model.reading, p), v)) diff[p] = v; + const note = typeof raw.note === "string" ? raw.note.replace(/\s+/g, " ").trim().slice(0, 300) : ""; + if (raw.misread === true || Object.keys(diff).length > 0) { + correction = { + t, + at: (o.now ?? (() => new Date()))().toISOString(), + by: "person", + ...(raw.misread === true ? { misread: true as const } : {}), + ...(Object.keys(diff).length ? { set: diff } : {}), + ...(note ? { note } : {}), + }; + } + } + const corrections = upsertCorrection(rec.corrections, t, correction); + const withCorrections: FrameScanRecord = { ...rec, corrections }; + if (!corrections.length) delete withCorrections.corrections; + const cues = await loadCues(videoDir); + const out = rederiveRecord(withCorrections, { ...(cues ? { cues } : {}), ...(o.now ? { now: o.now } : {}) }); + await sidecar.write(videoDir, out); + return { ok: true, correction, view: viewOf(out, t)!, rederived: rederivedSummary(rec, out, sidecar.filename) }; +} diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts @@ -196,6 +196,13 @@ export function rederivedSummary(before: FrameScanRecord, after: FrameScanRecord }; } +/** Is a frame scan of this video queued or running? (It writes the sidecar.) */ +export function frameScanBusy(slug: string, id: string): boolean { + return getRegistry() + .list() + .some((j) => j.kind === FRAME_SCAN_JOB_KIND && j.channelSlug === slug && j.videoId === id && (j.status === "queued" || j.status === "running")); +} + /** A video's cues (`transcript.cues.json`), sorted, or undefined. */ export async function loadCues(videoDir: string): Promise<Cue[] | undefined> { try { @@ -225,10 +232,7 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame return { evicted: { dir: cacheDir, removed: await removeFrameCache(cacheDir), bytes } }; } if (body.rederive) { - const busy = getRegistry() - .list() - .some((j) => j.kind === FRAME_SCAN_JOB_KIND && j.channelSlug === body.slug && j.videoId === body.id && (j.status === "queued" || j.status === "running")); - if (busy) return refuse(`a frame scan of ${body.slug}/${body.id} is queued or running — re-derive when it is done (it writes the sidecar)`); + if (frameScanBusy(body.slug, body.id)) return refuse(`a frame scan of ${body.slug}/${body.id} is queued or running — re-derive when it is done (it writes the sidecar)`); const sidecar = frameScanSidecar(body.profile); const rec = await sidecar.load(videoDir); if (!rec) return refuse(`${body.slug}/${body.id} has no ${sidecar.filename} to re-derive — scan it first`); diff --git a/common/lib/frameScan-server.ts b/common/lib/frameScan-server.ts @@ -18,6 +18,7 @@ import { lstat } from "node:fs/promises"; import { sidecar, sidecarField, type Sidecar } from "./sidecar-server"; import { FRAME_PROFILE_IDS } from "./frames/profiles"; import { FRAME_SCAN_FORMAT, type Derived, type SpokenReading } from "./frames/types"; +import { coerceCorrections, type ReadingCorrection } from "./frames/corrections"; export const frameScanFilename = (profile: string) => `frame-scan.${profile}.json`; @@ -52,6 +53,9 @@ export type FrameScanRecord = { updatedAt: string; // When `derived` was last worked out again from the readings (no model). rederivedAt?: string; + // A person's corrections of readings (release 32, lib/frames/corrections.ts): + // kept beside the model's readings, laid over them by the derivation. + corrections?: ReadingCorrection[]; }; const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v); @@ -61,8 +65,12 @@ export function coerceFrameScan(v: unknown): FrameScanRecord | null { if (!Array.isArray(v.readings) || !isObj(v.derived) || !isObj(v.sampling) || !isObj(v.source)) return null; const d = v.derived as Record<string, unknown>; if (!Array.isArray(d.tournaments) || !Array.isArray(d.events) || !Array.isArray(d.segments)) return null; + const corrections = coerceCorrections(v.corrections); + const { corrections: _raw, ...rest } = v as Record<string, unknown>; + void _raw; return { - ...(v as unknown as FrameScanRecord), + ...(rest as unknown as FrameScanRecord), + ...(corrections.length ? { corrections } : {}), runs: Array.isArray(v.runs) ? (v.runs as FrameScanRun[]) : [], spoken: Array.isArray(v.spoken) ? (v.spoken as SpokenReading[]) : [], duplicates: Array.isArray(v.duplicates) ? (v.duplicates as [number, number][]).filter((p) => Array.isArray(p) && p.length === 2) : [], diff --git a/common/lib/frames/corrections.test.ts b/common/lib/frames/corrections.test.ts @@ -0,0 +1,126 @@ +// A person's corrections of frame readings (release 32, lane R3): checked by +// field kind, laid over the readings by the derivation (the person's value +// wins; a misread is set aside, and its duplicates with it), kept across a +// re-derive, and never written over the model's readings. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { syntheticPokerHighlights } from "../../testing/frames/pokerReadings.mjs"; +import { derivePoker, type PokerReading } from "./poker"; +import { deriveOf, rederiveRecord } from "./scan"; +import { + CorrectionInputError, + applyCorrections, + checkCorrectionSet, + coerceCorrections, + upsertCorrection, + type ReadingCorrection, +} from "./corrections"; +import { coerceFrameScan, type FrameScanRecord } from "../frameScan-server"; + +type R = PokerReading & { t: number }; +const fx = syntheticPokerHighlights(); +const AT = "2026-10-16T00:00:00.000Z"; +const person = (t: number, more: Partial<ReadingCorrection>): ReadingCorrection => ({ t, at: AT, by: "person", ...more }); + +test("checkCorrectionSet: each field by its kind; unknown fields and bad values refused with the field's name", () => { + assert.deepEqual(checkCorrectionSet("poker", { "hero.stack": "12,400", "tournament.playersLeft": 85, phase: "table", "hero.cards": "as kd", log: "a\n\n b " }), { + "hero.stack": 12400, + "tournament.playersLeft": 85, + phase: "table", + "hero.cards": ["As", "Kd"], + log: ["a", "b"], + }); + assert.deepEqual(checkCorrectionSet("poker", { "hand.pot": "", "tournament.name": " Synth Cup " }), { "hand.pot": null, "tournament.name": "Synth Cup" }); + assert.equal(checkCorrectionSet("poker", {}), undefined); + assert.throws(() => checkCorrectionSet("poker", { "hero.name": "x" }), CorrectionInputError); + assert.throws(() => checkCorrectionSet("poker", { "hero.stack": -1 }), /Hero stack: a number/); + assert.throws(() => checkCorrectionSet("poker", { "tournament.playersLeft": 8.5 }), /Players left: a whole number/); + assert.throws(() => checkCorrectionSet("poker", { phase: null }), /Phase: is required/); + assert.throws(() => checkCorrectionSet("poker", { phase: "dealing" }), /Phase: one of/); + assert.throws(() => checkCorrectionSet("poker", { "hero.cards": "Ax" }), /"Ax" is not a card/); +}); + +test("applyCorrections: a set field takes the person's value, null removes it, a misread is dropped; idempotent", () => { + const rs: R[] = [ + { t: 0, phase: "table", hero: { stack: 100 }, tournament: { playersLeft: 9 } }, + { t: 10, phase: "table", hero: { stack: 999999 } }, + { t: 20, phase: "lobby" }, + ]; + const cs = [person(0, { set: { "tournament.playersLeft": null, "tournament.blinds.bb": 200 } }), person(10, { misread: true }), person(20, { set: { phase: "break" } })]; + const once = applyCorrections(rs, cs); + assert.deepEqual(once, [ + { t: 0, phase: "table", hero: { stack: 100 }, tournament: { blinds: { bb: 200 } } }, + { t: 20, phase: "break" }, + ]); + assert.deepEqual(applyCorrections(once, cs), once); + // The model's readings are untouched. + assert.deepEqual(rs[0].tournament, { playersLeft: 9 }); + // A cleared field that leaves its object empty takes the object with it. + assert.deepEqual(applyCorrections([{ t: 5, phase: "table", hero: { stack: 1 } }], [person(5, { set: { "hero.stack": null } })]), [{ t: 5, phase: "table" }]); +}); + +test("deriveOf: the derivation over the corrected readings is the derivation of the readings as the person says they are", () => { + const readings = fx.readings as R[]; + const cs: ReadingCorrection[] = []; + for (let t = 1500; t < 1600; t += 10) cs.push(person(t, { set: { "hero.stack": 133333 } })); + cs.push(person(2900, { misread: true })); + const byHand = readings + .filter((r) => r.t !== 2900) + .map((r) => (r.t >= 1500 && r.t < 1600 ? { ...r, hero: { ...(r.hero ?? {}), stack: 133333 } } : r)); + const o = { everySeconds: 10, hero: fx.hero }; + const got = deriveOf("poker", readings, [], fx.spoken, { ...o, corrections: cs }); + assert.deepEqual(got, derivePoker(byHand, fx.spoken, o)); + assert.notDeepEqual(got, deriveOf("poker", readings, [], fx.spoken, o)); + assert.ok(got.tournaments[0].series.stack.some(([t, v]) => t === 1500 && v === 133333), "the person's stack is in the series"); +}); + +test("deriveOf: a duplicate copies the corrected reading; a misread is copied nowhere; a correction at the duplicate's own second applies to it", () => { + const rs: R[] = [ + { t: 0, phase: "table", hero: { stack: 100 } }, + { t: 10, phase: "table", hero: { stack: 200 } }, + ]; + const dups: [number, number][] = [[20, 10], [30, 0]]; + const seen: R[][] = []; + const spy = (cs: ReadingCorrection[]) => { + const corrected = applyCorrections(rs, cs); + const byT = new Map(corrected.map((r) => [r.t, r])); + const copies = dups.flatMap(([t, s]) => (byT.get(s) ? [{ ...byT.get(s)!, t }] : [])); + seen.push(applyCorrections([...corrected, ...copies], cs).sort((a, b) => a.t - b.t)); + return deriveOf("poker", rs, dups, [], { everySeconds: 10, corrections: cs }); + }; + const a = spy([person(10, { set: { "hero.stack": 250 } }), person(0, { misread: true }), person(20, { set: { "hero.stack": 260 } })]); + assert.deepEqual(seen[0], [ + { t: 10, phase: "table", hero: { stack: 250 } }, + { t: 20, phase: "table", hero: { stack: 260 } }, + ]); + assert.deepEqual(a, derivePoker(seen[0], [], { everySeconds: 10 })); +}); + +test("the sidecar keeps the corrections (one per second, the newest) and a re-derive applies them", () => { + const rec = { + format: "archilyzer-frame-scan", + version: 1, + profile: "poker", + source: { savedVideo: "source-media.mp4", durationSeconds: 3000 }, + sampling: { everySeconds: 10, from: 0, to: 3000, width: 1280, keyframesOnly: true, frames: 300, kept: 300, skippedDuplicates: 0 }, + model: { route: "api", model: "claude-haiku-4-5", promptVersion: 3 }, + hints: { hero: fx.hero }, + costUsd: 0, + runs: [], + readings: fx.readings, + duplicates: [], + spoken: fx.spoken, + derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] }, + updatedAt: AT, + corrections: [person(2900, { set: { "hero.stack": 5 } }), person(2900, { misread: true }), { t: "x" }, { t: 5, at: AT, by: "person" }], + }; + const coerced = coerceFrameScan(rec) as FrameScanRecord; + assert.deepEqual(coerced.corrections, [person(2900, { misread: true })]); + const out = rederiveRecord(coerced); + assert.deepEqual(out.corrections, coerced.corrections); + assert.deepEqual(out.derived, derivePoker((fx.readings as R[]).filter((r) => r.t !== 2900), fx.spoken, { everySeconds: 10, durationSeconds: 3000, hero: fx.hero })); + assert.equal(out.readings.length, fx.readings.length, "the model's readings are kept as read"); + assert.deepEqual(coerceCorrections(undefined), []); + assert.deepEqual(upsertCorrection([person(1, { misread: true }), person(3, { misread: true })], 1, null), [person(3, { misread: true })]); +}); diff --git a/common/lib/frames/corrections.ts b/common/lib/frames/corrections.ts @@ -0,0 +1,228 @@ +// A PERSON'S CORRECTION OF A FRAME READING (release 32, lane R3): a scan can +// be fixed with no model. A vision model read each kept frame into a reading; +// where it read a field wrong (a stack off by a digit, the wrong players-left +// number, a blinds line misread), a person sets the field to what the frame +// shows, or sets the whole reading aside as a misread. The correction is kept +// BESIDE the model's readings in the sidecar (`corrections`), never written +// over them, and the derivation reads the readings with the corrections laid +// over them — the person's value wins. The derivation's own rules are +// unchanged (P2's guarantees: a flagged reading makes no event, one +// tournament until a confirmed bust), so a corrected value goes through the +// same smoothing a read one does. +// +// Pure: types, the per-profile field table, the check and the overlay. + +import { POKER_FRAME_EVENTS, POKER_PHASES } from "./poker"; + +export type CorrectionValue = number | string | string[] | null; + +export type ReadingCorrection = { + // The grid second of the reading (a read frame's, or a duplicate's). + t: number; + // When the person saved it (ISO). + at: string; + by: "person"; + // The whole reading set aside: the derivation never sees it (nor a + // duplicate that copies it). + misread?: true; + // Field path → the value the frame shows; null: the frame does not show it. + set?: Record<string, CorrectionValue>; + note?: string; +}; + +export type CorrectableField = { + path: string; + label: string; + kind: "whole" | "number" | "text" | "lines" | "cards" | "enum"; + options?: readonly string[]; + // phase is the one a reading must have. + required?: boolean; +}; + +// The fields a person may correct, per profile, in the order a form shows them. +export const CORRECTABLE_FIELDS: Readonly<Record<string, readonly CorrectableField[]>> = { + poker: [ + { path: "phase", label: "Phase", kind: "enum", options: POKER_PHASES, required: true }, + { path: "tournament.name", label: "Tournament", kind: "text" }, + { path: "tournament.level", label: "Level", kind: "whole" }, + { path: "tournament.blinds.sb", label: "Small blind", kind: "number" }, + { path: "tournament.blinds.bb", label: "Big blind", kind: "number" }, + { path: "tournament.blinds.ante", label: "Ante", kind: "number" }, + { path: "tournament.playersLeft", label: "Players left", kind: "whole" }, + { path: "tournament.totalPlayers", label: "Field", kind: "whole" }, + { path: "tournament.position", label: "Position", kind: "whole" }, + { path: "tournament.averageStack", label: "Average stack", kind: "whole" }, + { path: "tournament.prizePool", label: "Prize pool", kind: "number" }, + { path: "tournament.payout", label: "Payout", kind: "number" }, + { path: "hero.stack", label: "Hero stack", kind: "whole" }, + { path: "hero.bb", label: "Hero stack (big blinds)", kind: "number" }, + { path: "hero.bounty", label: "Hero bounty", kind: "number" }, + { path: "hero.cards", label: "Hero cards", kind: "cards" }, + { path: "hand.pot", label: "Pot", kind: "whole" }, + { path: "hand.action", label: "Action", kind: "text" }, + { path: "event", label: "Event", kind: "enum", options: POKER_FRAME_EVENTS }, + { path: "log", label: "Log lines", kind: "lines" }, + ], +}; + +export function correctableFields(profile: string): readonly CorrectableField[] { + return CORRECTABLE_FIELDS[profile] ?? []; +} + +export class CorrectionInputError extends Error { + constructor(message: string) { + super(message); + this.name = "CorrectionInputError"; + } +} + +const CARD = /^(?:[2-9TJQKA])[shdc]$/; +const MAX_NUMBER = 1e12; + +// One field's value, checked against its kind. null clears the field (not shown). +export function checkCorrectionValue(field: CorrectableField, v: unknown): CorrectionValue { + const fail = (m: string): never => { + throw new CorrectionInputError(`${field.label}: ${m}`); + }; + if (v === null || v === undefined || v === "") { + if (field.required) fail("is required"); + return null; + } + switch (field.kind) { + case "whole": + case "number": { + const n = typeof v === "number" ? v : typeof v === "string" ? Number(v.replace(/[,\s]/g, "")) : NaN; + if (!Number.isFinite(n) || n < 0 || n > MAX_NUMBER) fail("a number, 0 or more"); + if (field.kind === "whole" && !Number.isInteger(n)) fail("a whole number"); + return n; + } + case "text": { + if (typeof v !== "string") fail("text"); + const s = (v as string).replace(/\s+/g, " ").trim().slice(0, 200); + return s || null; + } + case "enum": { + if (typeof v !== "string" || !(field.options ?? []).includes(v)) fail(`one of ${(field.options ?? []).join(", ")}`); + return v as string; + } + case "lines": { + const list = Array.isArray(v) ? v : typeof v === "string" ? v.split("\n") : null; + if (!list || list.some((l) => typeof l !== "string")) fail("lines of text"); + const out = (list as string[]).map((l) => l.replace(/\s+/g, " ").trim().slice(0, 300)).filter(Boolean); + if (out.length > 40) fail("at most 40 lines"); + return out.length ? out : null; + } + case "cards": { + const list = Array.isArray(v) ? v : typeof v === "string" ? v.split(/[\s,]+/) : null; + if (!list || list.some((c) => typeof c !== "string")) fail("cards like As Kd"); + const out = (list as string[]).filter(Boolean).map((c) => (c.length === 2 ? c[0].toUpperCase() + c[1].toLowerCase() : c)); + const bad = out.find((c) => !CARD.test(c)); + if (bad) fail(`"${bad}" is not a card (rank then suit: As, Td, 9c)`); + if (new Set(out).size !== out.length) fail("a card twice"); + if (out.length > 6) fail("at most 6 cards"); + return out.length ? out : null; + } + } +} + +// The `set` of a correction, checked: only the profile's fields, each value by +// its kind. Empty → undefined. +export function checkCorrectionSet(profile: string, raw: unknown): Record<string, CorrectionValue> | undefined { + if (raw === undefined || raw === null) return undefined; + if (typeof raw !== "object" || Array.isArray(raw)) throw new CorrectionInputError(`"set" is an object of field → value`); + const fields = new Map(correctableFields(profile).map((f) => [f.path, f])); + const out: Record<string, CorrectionValue> = {}; + for (const [k, v] of Object.entries(raw as Record<string, unknown>)) { + const f = fields.get(k); + if (!f) throw new CorrectionInputError(`"${k}" is not a field a ${profile} reading has (${[...fields.keys()].join(", ")})`); + out[k] = checkCorrectionValue(f, v); + } + return Object.keys(out).length ? out : undefined; +} + +/** A reading's value at a dotted path (undefined when absent). */ +export function readField(reading: Record<string, unknown>, p: string): unknown { + let cur: unknown = reading; + for (const k of p.split(".")) { + if (!cur || typeof cur !== "object" || Array.isArray(cur)) return undefined; + cur = (cur as Record<string, unknown>)[k]; + } + return cur; +} + +// A copy of `reading` with `p` set (or, for null, removed — and an object left +// empty removed with it). +function writeField<T extends Record<string, unknown>>(reading: T, p: string, v: CorrectionValue): T { + const keys = p.split("."); + const root: Record<string, unknown> = { ...reading }; + const chain: Record<string, unknown>[] = [root]; + let cur = root; + for (const k of keys.slice(0, -1)) { + const next = cur[k]; + const copy = next && typeof next === "object" && !Array.isArray(next) ? { ...(next as Record<string, unknown>) } : {}; + cur[k] = copy; + cur = copy; + chain.push(cur); + } + const last = keys[keys.length - 1]!; + if (v === null) delete cur[last]; + else cur[last] = Array.isArray(v) ? [...v] : v; + // Prune objects the clear left empty, innermost first. + for (let i = chain.length - 1; i > 0; i--) { + if (Object.keys(chain[i]!).length === 0) delete chain[i - 1]![keys[i - 1]!]; + } + return root as T; +} + +/** One reading with a correction laid over it; null when it is set aside. */ +export function correctedReading<T extends { t: number; phase: string }>(reading: T, c: ReadingCorrection | undefined): T | null { + if (!c) return reading; + if (c.misread) return null; + let out = reading; + for (const [p, v] of Object.entries(c.set ?? {})) out = writeField(out, p, v); + return out; +} + +/** + * Readings with the person's corrections laid over them (by `t`): a misread is + * dropped, a set field takes the person's value. Idempotent — applying the + * same corrections again changes nothing — so a scan can apply them before + * and after it expands its duplicates. + */ +export function applyCorrections<T extends { t: number; phase: string }>(readings: readonly T[], corrections: readonly ReadingCorrection[] | undefined): T[] { + if (!corrections?.length) return [...readings]; + const byT = new Map(corrections.map((c) => [c.t, c])); + const out: T[] = []; + for (const r of readings) { + const c = correctedReading(r, byT.get(r.t)); + if (c) out.push(c); + } + return out; +} + +/** Corrections as stored: well-formed ones only, one per t (the newest), sorted. */ +export function coerceCorrections(v: unknown): ReadingCorrection[] { + if (!Array.isArray(v)) return []; + const byT = new Map<number, ReadingCorrection>(); + for (const c of v) { + if (!c || typeof c !== "object" || typeof (c as ReadingCorrection).t !== "number" || !Number.isFinite((c as ReadingCorrection).t)) continue; + const x = c as ReadingCorrection; + const set = x.set && typeof x.set === "object" && !Array.isArray(x.set) ? x.set : undefined; + if (!x.misread && !set) continue; + byT.set(x.t, { + t: x.t, + at: typeof x.at === "string" ? x.at : "", + by: "person", + ...(x.misread ? { misread: true as const } : {}), + ...(set ? { set } : {}), + ...(typeof x.note === "string" && x.note ? { note: x.note } : {}), + }); + } + return [...byT.values()].sort((a, b) => a.t - b.t); +} + +/** The corrections with `c` in place of any at its t (or, for `null` at t, without it). */ +export function upsertCorrection(list: readonly ReadingCorrection[] | undefined, t: number, c: ReadingCorrection | null): ReadingCorrection[] { + const rest = (list ?? []).filter((x) => x.t !== t); + return (c ? [...rest, c] : rest).sort((a, b) => a.t - b.t); +} diff --git a/common/lib/frames/scan.ts b/common/lib/frames/scan.ts @@ -22,6 +22,7 @@ import { frameProfile } from "./profiles"; import { probeDuration, sampleFrames, type Crop, type FrameIndex } from "./sample-server"; import { FRAME_SCAN_FORMAT, type Cue, type Derived, type FrameRef, type SpokenReading } from "./types"; import type { FrameScanRecord, FrameScanRun } from "../frameScan-server"; +import { applyCorrections, type ReadingCorrection } from "./corrections"; export const DEFAULT_EVERY_SECONDS = 10; export const DEFAULT_MAX_FRAMES = 5000; @@ -120,15 +121,20 @@ export function deriveOf( readings: FrameScanRecord["readings"], duplicates: readonly [number, number][], spoken: SpokenReading[], - o: { everySeconds: number; durationSeconds?: number | null; hero?: string }, + o: { everySeconds: number; durationSeconds?: number | null; hero?: string; corrections?: readonly ReadingCorrection[] }, ): Derived { const profile = frameProfile(profileId); - const byT = new Map(readings.map((r) => [r.t, r])); + // A person's corrections (release 32) first, so a duplicate copies the + // corrected reading (and a reading set aside is copied nowhere); then again + // over the copies, for a correction made at a duplicate's own second. + const corrected = applyCorrections(readings, o.corrections); + const byT = new Map(corrected.map((r) => [r.t, r])); + const read = new Set(readings.map((r) => r.t)); const copies = duplicates.flatMap(([t, src]) => { const r = byT.get(src); - return r && !byT.has(t) ? [{ ...r, t }] : []; + return r && !read.has(t) ? [{ ...r, t }] : []; }); - const expanded = [...readings, ...copies].sort((a, b) => a.t - b.t); + const expanded = applyCorrections([...corrected, ...copies], o.corrections).sort((a, b) => a.t - b.t); return profile.derive(expanded as never, spoken, { everySeconds: o.everySeconds, ...(o.durationSeconds !== null && o.durationSeconds !== undefined ? { durationSeconds: o.durationSeconds } : {}), @@ -155,6 +161,7 @@ export function rederiveRecord(rec: FrameScanRecord, o: { cues?: Cue[]; hero?: s everySeconds: rec.sampling.everySeconds, durationSeconds: rec.source.durationSeconds, hero: hints?.hero, + ...(rec.corrections?.length ? { corrections: rec.corrections } : {}), }), rederivedAt: at, updatedAt: at, @@ -253,7 +260,15 @@ export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Pr readings: all, duplicates, spoken, - derived: deriveOf(profile.id, all, duplicates, spoken, { everySeconds: every, durationSeconds: duration, hero: hints.hero }), + derived: deriveOf(profile.id, all, duplicates, spoken, { + everySeconds: every, + durationSeconds: duration, + hero: hints.hero, + ...(prev?.corrections?.length ? { corrections: prev.corrections } : {}), + }), + // A person's corrections outlive every run, a fresh one included: they + // say what a frame at that second shows. + ...(prev?.corrections?.length ? { corrections: prev.corrections } : {}), updatedAt: now().toISOString(), }; };