Archilyzer · Source

archilyzer

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

commit f57df351ce3e5fb3f9707ef5fb3d9c1823691fe7
parent a5d1204556aef8b84ab532f5c7688e99992a00f2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 17 Oct 2026 02:30:13 -0400

Merge r32/rulings: the operator's rulings of 2026-10-17 — bench v3 meanings reversal with dedupe off by default; Wayback-only citations OK (recorded); a Wayback capture counts as found only when its stream answers; a corrupt full source gets its full audio attempts before any salvage, the salvage marked partial everywhere

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

Diffstat:
MCOMMANDS.md | 8++++----
MREPORT.md | 12++++++------
Mcommon/bin/archilyzer.ts | 4++--
Mcommon/bin/reports-bench-verdicts.ts | 6+++++-
Mcommon/controller/benchVerdicts.ts | 6+++++-
Mcommon/controller/channelSnapshot.test.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/channelSnapshot.ts | 28++++++++++++++++++++++++++++
Acommon/controller/fullAudioFirst.test.ts | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/fullAudioFirst.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/transcribeOne.ts | 26+++++++++++++++++++++++---
Mcommon/lib/archiveOrgClient.ts | 27+++++++++++++++++++++++++--
Acommon/lib/fullAudioFirst-server.ts | 17+++++++++++++++++
Acommon/lib/fullAudioFirst.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/docs.ts | 4++--
Mcommon/lib/report/draft/bench/bench.test.ts | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/report/draft/bench/items.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/lib/report/draft/bench/prompt.ts | 147++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/lib/report/draft/bench/run.ts | 33+++++++++++++++++++++++----------
Mcommon/lib/report/draft/bench/score.ts | 5+++++
Mcommon/lib/report/draft/bench/store.ts | 2++
Mcommon/lib/report/draft/tasks/verdicts.test.ts | 17++++++++++++-----
Mcommon/lib/report/draft/tasks/verdicts.ts | 15++++++++-------
Mcommon/lib/report/verdicts.mjs | 34+++++++++++++++++++++-------------
Mcommon/lib/report/verdicts.ts | 8++++----
Mcommon/lib/waybackClient.test.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/waybackClient.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/publish/findCopy.test.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/publish/findCopy.ts | 37+++++++++++++++++++++++++++++++++----
Mcommon/publish/findCopyScope.test.ts | 26++++++++++++++++++++++++++
Mcommon/testing/README.md | 2+-
Mcommon/testing/web/fakeWayback.d.mts | 10+++++++++-
Mcommon/testing/web/fakeWayback.mjs | 22++++++++++++++++++++++
Mcommon/views/pipeline/channelFlow.test.ts | 18++++++++++++++++++
Mcommon/views/pipeline/channelFlow.ts | 37+++++++++++++++++++++++++++++++++++--
Mcommon/ytdlp/downloadOneManaged.ts | 23+++++++++++++++++++++++
Mcommon/ytdlp/storedUrlManaged.test.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 3+++
Meditor/app/api/ops/_benchVerdicts.test.ts | 12++++++++----
Meditor/app/api/ops/_verdicts.test.ts | 2+-
Meditor/app/api/ops/bench-verdicts/route.ts | 5+++--
Meditor/app/api/ops/transcribe-one/route.ts | 4+++-
Meditor/app/channels/[slug]/components/VideoListPane.tsx | 6++++--
Meditor/app/channels/[slug]/lib/videoRows.ts | 3+++
Meditor/app/channels/[slug]/lib/videoRowsServer.ts | 1+
Meditor/app/channels/[slug]/videos/[id]/components/SalvagedTranscriptNotice.tsx | 11++++++++++-
Meditor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx | 24+++++++++++++++++++++++-
Meditor/app/channels/[slug]/videos/[id]/components/cards/PerFileTranscribeRow.tsx | 25+++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/e2e/full-audio-first.spec.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/search.test.ts | 8++++++++
Mmcp/src/server.ts | 10++++++++--
Mplans/FACTS.md | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aplans/release-30/V.md | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-32/rulings.md | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 13++++++++++---
Mumtool/app/tools/bench/page.tsx | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/e2e/fixtures/bench-fixture.mjs | 13++++++++++++-
Mumtool/e2e/verdict-bench.spec.ts | 12+++++++++++-
Mumtool/lib/bench.ts | 30++++++++++++++++++++++++++----
59 files changed, 2041 insertions(+), 166 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -37,7 +37,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/&lt;id&gt;/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) | | `archilyzer reports delete` | `<articleId> [--iteration <n>] [--apply] [--force] [--json]` | delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration) | | `archilyzer reports respell` | `<articleId> --heard <form,…> --reads <word> [--bracket] [--note <text>] [--iteration <n>] [--apply] [--json]` | correct what the transcripts mishear across an article's quotes: each heard form (words, case-insensitive, a plural s carried) reads as --reads in the quotes of iteration n's report.json (default: the iteration the current report came from), the article's report.json when it is that report, and the iteration's video manifest (burned-in quotes, flip cards) — plainly, or bracketed (\[K-Cup\]) with --bracket; the report's own words plainly. Each file gains `respellings`, which every quote check (compose, verify-quotes, the video's cut-to-quote) applies to the transcript before comparing, so a corrected quote verifies as its original did. A dry run printing every change as before → after unless --apply, which backs each file up to the project's revisions/ first (exit 1 when nothing would change; 2 for usage, or no such article or iteration) | -| `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage) | +| `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--dedupe] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode, --limit or --dedupe with it); --dedupe asks a claim that repeats an earlier one (the same text over the same cited spans) once — without it every claim is asked. The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage) | | `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) | | `archilyzer frames rederive` | `<slug>/<id> [--profile poker] [--hero <name>] [--dry] [--json]` | work a frame scan's derived timeline (tournaments, series, events, flags) out again from the readings frame-scan.&lt;profile&gt;.json already holds and the video's cues — no model, no frame, no editor — and write it back (--dry: print what would change, write nothing). Not while a scan of the video is running (it writes the same file): with an editor up, `pnpm ops frame-scan --json '{"slug","id","rederive":true}'` checks that (exit 1 when there is no sidecar; 2 for usage) | | `archilyzer reports import-sweep` | `<report.json> --article <id> --question <question> [--sweep <sweep.md>] [--channels <a,b>] [--model <m>] [--from <where>] [--minutes <n>] [--apply]` | a report made outside the editor's report-draft jobs (a Claude Code session's /sweep, a task routed to code) becomes the next iteration of its article through the iterations store: kind sweep, status done, $0, its question, channels and minutes, `imported` naming where it came from (--from, default claude-code; --model default claude-code); its report.json the file given (id set to the article's, audience dropped), refused unless it parses as a report; never made current (umtool's Iterations tab, or `umtool chain <id> <n>`); a new id makes an article in the making. A dry run printing the plan unless --apply (exit 1 when refused; 2 for usage) | @@ -120,7 +120,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | | `sync` | sync lists a channel and downloads what is new, as its Sync button does: {"slug"}. "full": true runs the periodic whole-listing sweep now (else the configured cadence decides); "queueKey" picks another queue. On the channel's platform queue, paced like its downloads. | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` | | `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | | -| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | +| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | | | `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | | @@ -146,7 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | -| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. | | +| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | @@ -160,7 +160,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` | | `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` | +| `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, limit or dedupe with it), "dedupe"? (true: a claim repeating an earlier one, the same text over the same cited spans, is asked once; default: every claim is asked)} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | | `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -&gt; {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.&lt;profile&gt;.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` | | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -&gt; {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/&lt;slug&gt;.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` | | `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" \| "add-spelling", …}. 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. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `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"}'` | diff --git a/REPORT.md b/REPORT.md @@ -111,13 +111,13 @@ The shared vocabulary (`common/lib/report/verdicts.mjs` — the one copy; report | Verdict | Means | Default label | Default colour | |---|---|---|---| -| `CORROBORATED` | the substance of the claim is shown by the cited words. Framing, emphasis, or a detail the transcript does not show does not demote it. | Corroborated | `#3fbf7f` | -| `PARTLY` | a part of the claim is shown by the transcript to be overstated or wrong. A part that is only not shown does not make a claim PARTLY. | Partly true | `#e3b23c` | -| `CONTRADICTED` | the substance of the claim is shown to be wrong: the transcript shows the opposite of it, or something that cannot be true at the same time. | Contradicted | `#e5534b` | -| `NOT_FOUND` | the claim could be checked against what was said, and its substance is not in the transcript shown: the topic may come up without what the claim says about it. | Not found | `#8b93a7` | -| `UNTESTABLE` | the claim is an opinion, a judgement, a prediction, or anything else a transcript cannot show to be true or false. | Untestable | `#7d8fd6` | +| `CORROBORATED` | every part of the claim is shown by the cited evidence in substance: other words, a softer phrasing or a hedge still count. | Corroborated | `#3fbf7f` | +| `PARTLY` | some parts of the claim are shown and at least one is not: it is not in the evidence, or the evidence shows it wrong (a different number, date or person, or words put in quotation marks that are not the speaker's). | Partly true | `#e3b23c` | +| `CONTRADICTED` | no part of the claim is shown, and the evidence shows a part wrong: the opposite of it, or something that cannot be true at the same time. | Contradicted | `#e5534b` | +| `NOT_FOUND` | no part of the claim is shown or shown wrong by the evidence: the topic may come up without what the claim says about it. | Not found | `#8b93a7` | +| `UNTESTABLE` | the claim is an opinion, a judgement, a prediction, or anything else a record cannot show to be true or false. | Untestable | `#7d8fd6` | -In doubt between CORROBORATED and PARTLY: CORROBORATED, unless a part of the claim is shown overstated or wrong. The meanings are the operator's standard; the verdict bench's prompt and the verdict proposals read the same sentences. +A claim's parts are the separate things it says were said or done: a statement, an event, a number, a date, words it puts in quotation marks as someone's. A word that only describes what was said (its tone, motive or importance) is not a part, and neither is a fact about the world outside what was said (whether a thing said is true). A part about how often something was said, or that it was never said, is shown when the evidence is consistent with it and does not show otherwise. The meanings are the operator's standard; the verdict bench's prompt and the verdict proposals read the same sentences. ## Iterations diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -431,8 +431,8 @@ export const COMMANDS: Command[] = [ { path: ["reports", "bench-verdicts"], usage: - "--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json] the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage)", - flags: { report: "string", models: "string", window: "string", "window-mode": "string", "max-usd": "string", limit: "string", "items-from": "string", run: "string", dry: "boolean", here: "boolean", wait: "boolean", json: "boolean" }, + "--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--dedupe] [--run <id>] [--dry] [--here] [--wait] [--json] the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode, --limit or --dedupe with it); --dedupe asks a claim that repeats an earlier one (the same text over the same cited spans) once — without it every claim is asked. The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage)", + flags: { report: "string", models: "string", window: "string", "window-mode": "string", "max-usd": "string", limit: "string", "items-from": "string", dedupe: "boolean", run: "string", dry: "boolean", here: "boolean", wait: "boolean", json: "boolean" }, run: async (ctx) => (await import("./reports-bench-verdicts")).benchRow(ctx), }, { diff --git a/common/bin/reports-bench-verdicts.ts b/common/bin/reports-bench-verdicts.ts @@ -1,11 +1,13 @@ // `archilyzer reports bench-verdicts --models a,b,c [--report <id>,…] [--window 60] // [--window-mode seconds|turn] [--max-usd 5] [--limit n] [--items-from <run>] -// [--run <id>] [--dry] [--here] [--wait] [--json]` +// [--dedupe] [--run <id>] [--dry] [--here] [--wait] [--json]` // (release 28 M7; release 29 V1) — the verdict bench: every ruled claim of the // registry's fact-checks asked of each model, one claim per call, and scored // against the operator's rulings (lib/report/draft/bench/). V1: `--window-mode // turn` (the cited speaker's turn, bounded by --window), a stratified `--limit` // (by the operator's verdict), `--items-from <run>` (that run's exact items). +// `--dedupe` asks a repeated claim once (off by default: every claim is asked; +// operator ruling 2026-10-17). // // --dry lists the items (key, the operator's verdict, quotes, cues — no // claim text unless --json) and the skipped claims with their @@ -72,6 +74,7 @@ export function benchOptionsOf(flags: Record<string, FlagValue>): BenchOptions { } if (typeof flags["items-from"] === "string") o.itemsFrom = flags["items-from"]; if (typeof flags.run === "string") o.runId = flags.run; + if (flags.dedupe === true) o.dedupe = true; validateBenchOptions(o); if (o.runId !== undefined && !isBenchRunId(o.runId)) throw new BenchInputError("--run is a run id: lowercase letters, digits and dashes"); return o; @@ -170,6 +173,7 @@ export async function benchMain(flags: Record<string, FlagValue>, deps: BenchDep if (opts.limit !== undefined) body.limit = opts.limit; if (opts.windowMode !== undefined) body.windowMode = opts.windowMode; if (opts.itemsFrom !== undefined) body.itemsFrom = opts.itemsFrom; + if (opts.dedupe) body.dedupe = true; return deps.runOps(["bench-verdicts", "--json", JSON.stringify(body), ...(flags.wait === true ? ["--wait"] : [])]); } diff --git a/common/controller/benchVerdicts.ts b/common/controller/benchVerdicts.ts @@ -54,7 +54,7 @@ import { llmConfigOf } from "./reportDraft"; export const BENCH_VERDICTS_JOB_KIND = "bench-verdicts"; export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts "; -export const BENCH_VERDICTS_BODY_KEYS = ["run", "reports", "models", "window", "windowMode", "maxUsd", "limit", "itemsFrom"] as const; +export const BENCH_VERDICTS_BODY_KEYS = ["run", "reports", "models", "window", "windowMode", "maxUsd", "limit", "itemsFrom", "dedupe"] as const; const fail = (msg: string): never => { throw new BenchInputError(msg); @@ -94,6 +94,10 @@ export function parseBenchVerdictsBody(b: Record<string, unknown>): BenchOptions if (!isBenchRunId(b.itemsFrom)) fail(`"itemsFrom" is a run id: lowercase letters, digits and dashes`); out.itemsFrom = b.itemsFrom as string; } + if (b.dedupe !== undefined) { + if (typeof b.dedupe !== "boolean") fail(`"dedupe" is true or false`); + out.dedupe = b.dedupe as boolean; + } validateBenchOptions(out); return out; } diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts @@ -910,3 +910,59 @@ test("a salvage transcript is salvagedTranscript; its corrupt full source stays await rm(dir, { recursive: true, force: true }); } }); + +// Release 32 R8: the snapshot's `fullAudio` counts the stored-URL download +// attempts of each corrupt full source whose record stores a trusted media URL, +// and lists the untranscribed ones still owed one (`awaiting`). +test("fullAudio: a stored-URL channel's corrupt full sources, their attempts, the ones awaiting full audio", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "ttb-snap-fullaudio-")); + try { + const paths = { channelsDir: path.join(dir, "channels") } as Paths; + const make = async (slug: string, url: string, extra: object = {}) => { + const channelDir = path.join(paths.channelsDir, slug); + const ids = ["aaaa0000001", "bbbb0000002", "cccc0000003"]; + for (const id of ids) await mkdir(path.join(channelDir, "data", id), { recursive: true }); + await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "transcribe", url, ...extra })); + await writeFile(path.join(channelDir, "playlist"), ids.map((id) => `https://odysee.com/v:${id}`).join("\n")); + const put = (id: string, name: string, body: unknown) => + writeFile(path.join(channelDir, "data", id, name), typeof body === "string" ? body : JSON.stringify(body)); + const stored = { n: 1, kind: "stored-url-ranged", handling: "transcribe", usedCookies: false, ytdlpExitCode: 1 }; + const cfs = (id: string, n: number) => ({ + videoId: id, + status: "corrupt-full-source", + startedAt: "2026-10-01T00:00:00.000Z", + finishedAt: "2026-10-01T00:01:00.000Z", + attempts: Array.from({ length: n }, () => stored), + }); + const salvaged = { source: "audio.mp4", decodedSeconds: 100, totalSeconds: 600, gaps: [[100, 600]] }; + const odysee = url.startsWith("https://odysee.com/"); + for (const id of ids) { + await put(id, "metadata.info.json", { + id, + duration: 600, + webpage_url: odysee ? `https://odysee.com/synthetic:${id}` : `https://www.youtube.com/watch?v=${id}`, + formats: [{ url: `https://player.odycdn.com/v6/streams/${id}/a.mp4`, protocol: "https" }], + }); + await put(id, "audio.mp4", "x"); + } + await put("aaaa0000001", "download-outcome.json", cfs("aaaa0000001", 0)); + await put("bbbb0000002", "download-outcome.json", cfs("bbbb0000002", 2)); + await put("cccc0000003", "download-outcome.json", cfs("cccc0000003", 1)); + await put("cccc0000003", "transcript.json", "{}"); + await put("cccc0000003", "transcribe-outcome.json", { videoId: "cccc0000003", transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }); + }; + await make("ody", "https://odysee.com/@synth:1"); + await make("yt", "https://www.youtube.com/@synth/videos"); + await make("never", "https://odysee.com/@synth:2", { storedUrlDownloads: "never" }); + const ody = await generateChannelSnapshot(paths, "ody"); + assert.deepEqual(ody.fullAudio, { + of: 2, + attempts: { aaaa0000001: 0, bbbb0000002: 2, cccc0000003: 1 }, + awaiting: ["aaaa0000001"], + }); + assert.equal((await generateChannelSnapshot(paths, "yt")).fullAudio, undefined, "no record stores a trusted media URL"); + assert.equal((await generateChannelSnapshot(paths, "never")).fullAudio, undefined, "the channel says never"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -87,6 +87,8 @@ import { deriveChannelSets } from "./channelSets"; import { readTranscriptCoverage } from "./normalizeTranscript"; import { resolveCaptionsProvenance } from "../lib/subtitleProvenance"; import { isIncompleteTranscript } from "../lib/transcriptCoverage"; +import { storedMediaUrl } from "../lib/storedMediaUrl-server"; +import { FULL_AUDIO_ATTEMPTS, fullAudioAttemptsOf } from "../lib/fullAudioFirst"; // THE PER-OPERATION WORK LISTS, keyed by operation id. // @@ -182,6 +184,14 @@ export type ChannelSnapshot = { // reason: no live snapshot is regenerated by the slice that added them, so // every reader falls back to the bucket fold until a channel's next regen. backfill?: ChannelSnapshotOperations; + // FULL AUDIO BEFORE A SALVAGE (release 32 R8, lib/fullAudioFirst.ts), on a + // transcribe-handling channel whose stored-URL mode is not "never": every + // corrupt full source whose record stores a trusted media URL (one metadata + // read for each corrupt full source, none for any other video) — its + // stored-URL download attempts so far (`attempts`, by id), of `of`, and the + // untranscribed ones still owed one (`awaiting` — no salvage until then). + // Omitted when there are none. + fullAudio?: { of: number; attempts: Record<string, number>; awaiting: string[] }; buckets: { noTranscript: string[]; downloadedNoTranscript: string[]; @@ -1043,6 +1053,10 @@ export async function generateChannelSnapshot( const excludedFromTruncatedCheck = await isExcludedFromTruncatedCheck(dir); const outcome = await loadDownloadOutcome(dir); + // Release 32 R8: a corrupt full source's record stores a trusted media + // URL (full audio before a salvage) — one metadata read, for those only. + const storedUrlTrusted = + outcome?.status === "corrupt-full-source" ? (await storedMediaUrl(dir)) !== null : false; // A salvage transcript says so in its transcribe-outcome.json (release // 30, lane Q). Only a whisper transcript can be one, so only those // with the sidecar pay the small read. @@ -1130,6 +1144,7 @@ export async function generateChannelSnapshot( doNotClean, excludedFromTruncatedCheck, outcome, + storedUrlTrusted, salvaged, heldAudioDamaged, integrityState, @@ -1251,6 +1266,10 @@ export async function generateChannelSnapshot( const incompleteTranscript: string[] = []; const salvagedTranscript: string[] = []; const corruptHeldAudio: string[] = []; + // Release 32 R8: full audio before a salvage (the snapshot's `fullAudio`). + const fullAudioChannel = config?.handling === "transcribe" && config.storedUrlDownloads !== "never"; + const fullAudioAttempts: Record<string, number> = {}; + const fullAudioAwaiting: 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 }; @@ -1298,6 +1317,7 @@ export async function generateChannelSnapshot( backfill, effectiveAvailability, outcome, + storedUrlTrusted, salvaged, heldAudioDamaged, integrityState, @@ -1381,6 +1401,11 @@ export async function generateChannelSnapshot( if (salvaged) salvagedTranscript.push(id); if (outcome?.status === "corrupt-full-source") { corruptFullSource.push(id); + if (fullAudioChannel && storedUrlTrusted) { + const n = fullAudioAttemptsOf(outcome); + fullAudioAttempts[id] = n; + if (n < FULL_AUDIO_ATTEMPTS && !salvaged && !isVideoTranscribed(files)) fullAudioAwaiting.push(id); + } continue; } // Held audio the audit found damaged (release 31, lane A). Untranscribed, @@ -1823,6 +1848,9 @@ export async function generateChannelSnapshot( : {}), }, digestEngines, + ...(Object.keys(fullAudioAttempts).length + ? { fullAudio: { of: FULL_AUDIO_ATTEMPTS, attempts: fullAudioAttempts, awaiting: fullAudioAwaiting.sort() } } + : {}), backfill: { ...backfillCounts, ...bucketLaneEntries }, undownloadedIds, excludedFromDownload, diff --git a/common/controller/fullAudioFirst.test.ts b/common/controller/fullAudioFirst.test.ts @@ -0,0 +1,153 @@ +// Full audio before a salvage (release 32 R8): the rule (pure), the reader, the +// controller's loop, and transcribeOne's refusal of an early automatic salvage. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fullAudioFirst.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import type { DownloadAttempt, DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { FULL_AUDIO_ATTEMPTS, fullAudioAttemptsOf, fullAudioFirstRefusal, fullAudioLine, fullAudioState } from "../lib/fullAudioFirst"; +import { fullAudioGate } from "../lib/fullAudioFirst-server"; +import { fullAudioFirst } from "./fullAudioFirst"; +import { transcribeOneVideo } from "./transcribeOne"; +import { TranscribeError } from "./transcribeError"; +import type { Paths } from "../lib/paths"; +import type { Worker } from "../lib/workers"; + +const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; +const stored = (n: number): DownloadAttempt[] => + Array.from({ length: n }, () => ({ n: 1, kind: "stored-url-ranged" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 1 })); +const cfs = (storedAttempts: number, status: DownloadOutcomeRecord["status"] = "corrupt-full-source"): DownloadOutcomeRecord => ({ + videoId: CLAIM, + status, + startedAt: "2026-10-15T00:00:00.000Z", + finishedAt: "2026-10-15T01:00:00.000Z", + attempts: [{ n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, ...stored(storedAttempts)], +}); + +test("the rule: stored-URL attempts counted; owed until FULL_AUDIO_ATTEMPTS; not applicable off the allowlist, never, or another handling", () => { + assert.equal(FULL_AUDIO_ATTEMPTS, 2); + assert.equal(fullAudioAttemptsOf(cfs(0)), 0); + assert.equal(fullAudioAttemptsOf(cfs(3)), 3); + assert.equal(fullAudioAttemptsOf(null), 0); + assert.deepEqual(fullAudioState(cfs(0), { storedUrlTrusted: true }), { attempts: 0, of: 2, exhausted: false }); + assert.deepEqual(fullAudioState(cfs(1), { storedUrlTrusted: true, handling: "transcribe" }), { attempts: 1, of: 2, exhausted: false }); + assert.deepEqual(fullAudioState(cfs(2), { storedUrlTrusted: true }), { attempts: 2, of: 2, exhausted: true }); + assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: false }), null, "no trusted stored URL"); + assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: true, mode: "never" }), null, "an explicit never"); + assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: true, handling: "youtube" }), null); + assert.equal(fullAudioState(cfs(0, "ok"), { storedUrlTrusted: true }), null, "not a corrupt full source"); + assert.equal(fullAudioLine({ attempts: 1, of: 2 }), "full audio attempts: 1 of 2"); + assert.match(fullAudioFirstRefusal({ attempts: 0, of: 2, exhausted: false }), /^Full audio first \(full audio attempts: 0 of 2\)/); +}); + +async function videoDir(o: { record?: DownloadOutcomeRecord; formats?: unknown[]; config?: object } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "full-audio-")); + const channel = path.join(root, "channels", "c"); + const dir = path.join(channel, "data", CLAIM); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(channel, "config.json"), JSON.stringify(o.config ?? { handling: "transcribe", url: "https://odysee.com/@synth:1" })); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ + id: CLAIM, + webpage_url: `https://odysee.com/synthetic-stream:${CLAIM}`, + formats: o.formats ?? [{ url: "https://player.odycdn.com/v6/streams/x/y.mp4", protocol: "https", ext: "mp4" }], + }), + ); + if (o.record) await writeFile(path.join(dir, "download-outcome.json"), JSON.stringify(o.record)); + await writeFile(path.join(dir, "audio.mp4"), "kept malformed"); + return { root, dir, done: () => rm(root, { recursive: true, force: true }) }; +} + +test("the reader: the record's status and its trusted stored URL", async () => { + const a = await videoDir({ record: cfs(1) }); + const b = await videoDir({ record: cfs(0), formats: [{ url: "https://cdn.example/x.mp4", protocol: "https" }] }); + const c = await videoDir({ record: cfs(0, "ok") }); + try { + assert.deepEqual(await fullAudioGate(a.dir), { attempts: 1, of: 2, exhausted: false }); + assert.deepEqual(await fullAudioGate(a.dir, { mode: "never" }), null); + assert.equal(await fullAudioGate(b.dir), null, "a host off the CDN list is not trusted"); + assert.equal(await fullAudioGate(c.dir), null); + } finally { + await Promise.all([a.done(), b.done(), c.done()]); + } +}); + +test("the loop: downloads the owed attempts — clean stops it; exhausted lets the salvage follow; a refusal with attempts owed stops with an error; not applicable downloads nothing", async () => { + const states = (seq: (number | null)[]) => { + let i = 0; + return async () => { + const n = seq[Math.min(i++, seq.length - 1)]; + return n === null ? null : { attempts: n, of: 2, exhausted: n >= 2 }; + }; + }; + const rec = (status: DownloadOutcomeRecord["status"], failureClass?: DownloadOutcomeRecord["failureClass"]) => ({ ...cfs(0, status), ...(failureClass ? { failureClass } : {}) }); + const log: string[] = []; + let calls = 0; + const base = { videoDir: "/x", onLog: (l: string) => log.push(l) }; + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([null]), download: async () => (calls++, rec("ok")) }), "not-needed"); + assert.equal(calls, 0); + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([0, 1]), download: async () => (calls++, rec("ok-audio-checked")) }), "clean"); + assert.equal(calls, 1); + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([0, 1, 2]), download: async () => (calls++, rec("corrupt-full-source")) }), "exhausted"); + assert.equal(calls, 2, "both owed attempts, then the salvage"); + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([2]), download: async () => (calls++, rec("ok")) }), "exhausted"); + assert.equal(calls, 0, "attempts already made: nothing downloaded"); + + calls = 0; + await assert.rejects( + fullAudioFirst({ ...base, gate: states([0, 1]), download: async () => (calls++, rec("failed", "rate_limit")) }), + /refused the download \(rate limited; full audio attempts: 1 of 2\)/, + ); + assert.equal(calls, 1, "a refusal is not hammered"); + + // A refusal that made the last owed attempt: the salvage may follow. + assert.equal(await fullAudioFirst({ ...base, gate: states([1, 2]), download: async () => rec("failed", "rate_limit") }), "exhausted"); + assert.ok(log.some((l) => l.startsWith("Full audio first (full audio attempts: 0 of 2)"))); +}); + +const worker: Worker = { id: "w1", name: "fake", kind: "local", enabled: true, priority: 0, appId: "whisper-cpp", config: { bin: "/bin/false", model: "m.bin" } }; + +test("transcribeOne: an automatic salvage of a corrupt full source with attempts owed is refused (no-audio); salvage: true still forces one", async () => { + const v = await videoDir({ record: cfs(1) }); + try { + const err = await transcribeOneVideo({ paths: {} as Paths, videoDir: v.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, onLog: () => {} }).then( + (x) => x, + (e) => e, + ); + assert.ok(err instanceof TranscribeError, String(err)); + assert.equal(err.failureClass, "no-audio"); + assert.match(err.message, /Full audio first \(full audio attempts: 1 of 2\)/); + // Forced: the gate is not asked (the engine here is /bin/false — some other failure, never the refusal). + const forced = await transcribeOneVideo({ paths: { ffmpegBin: "/bin/false", ffprobeBin: "/bin/false" } as Paths, videoDir: v.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, salvage: true, onLog: () => {} }).then( + (x) => x, + (e) => e, + ); + assert.doesNotMatch(String((forced as Error)?.message ?? forced), /Full audio first/); + } finally { + await v.done(); + } + // The channel says never: release 30's automatic salvage (not refused by the gate). + const n = await videoDir({ record: cfs(0), config: { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "never" } }); + try { + const r = await transcribeOneVideo({ paths: { ffmpegBin: "/bin/false", ffprobeBin: "/bin/false" } as Paths, videoDir: n.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, onLog: () => {} }).then( + (x) => x, + (e) => e, + ); + assert.doesNotMatch(String((r as Error)?.message ?? r), /Full audio first/); + } finally { + await n.done(); + } +}); diff --git a/common/controller/fullAudioFirst.ts b/common/controller/fullAudioFirst.ts @@ -0,0 +1,74 @@ +// FULL AUDIO BEFORE A SALVAGE, for a transcription that would salvage +// (operator ruling 2026-10-17, release 32 R8; the rule: lib/fullAudioFirst.ts). +// +// The editor's Transcribe (and `pnpm ops transcribe-one`) on a corrupt full +// source whose record stores a trusted media URL first makes the full-audio +// attempts that are still owed: each a managed download (`download`, the +// caller's downloadOneManaged with `storedUrl: "only"` — the corrupt-source +// refetch around R7's ranged reader, its audio check and its 20-minute gap), +// until one comes back clean or FULL_AUDIO_ATTEMPTS are on record. Then the +// transcription runs: in full after a clean download, as a salvage once the +// attempts are exhausted. +// +// not-needed the rule does not apply (not a corrupt full source, no trusted +// stored URL, a stored-URL mode of never): transcribe as before +// clean a download came back clean: the audio is whole +// exhausted every attempt made, none clean: the salvage may follow +// +// A refusal (rate limit) with attempts still owed stops here with an error that +// says so — the next Transcribe tries again; nothing is hammered. A cancel +// stops at once. + +import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { FULL_AUDIO_ATTEMPTS, fullAudioLine, type FullAudioState } from "../lib/fullAudioFirst"; +import { fullAudioGate } from "../lib/fullAudioFirst-server"; +import type { StoredUrlMode } from "../lib/storedMediaUrl"; + +export type FullAudioFirstResult = "not-needed" | "clean" | "exhausted"; + +export async function fullAudioFirst(o: { + videoDir: string; + handling?: string; + mode?: StoredUrlMode; + onLog: (line: string) => void; + signal?: AbortSignal; + download: () => Promise<DownloadOutcomeRecord>; + // Tests: the gate's reading (default: the video dir's). + gate?: (videoDir: string) => Promise<FullAudioState | null>; +}): Promise<FullAudioFirstResult> { + const gate = + o.gate ?? + ((dir: string) => + fullAudioGate(dir, { ...(o.handling ? { handling: o.handling } : {}), ...(o.mode ? { mode: o.mode } : {}) })); + let state = await gate(o.videoDir); + if (!state) return "not-needed"; + // At most the owed attempts: a download that records no stored-URL attempt + // (it should not happen) cannot loop. + for (let i = 0; i < FULL_AUDIO_ATTEMPTS && !state.exhausted; i++) { + if (o.signal?.aborted) throw abortError(); + o.onLog(`Full audio first (${fullAudioLine(state)}): downloading from the stored media URL before any salvage.`); + const record = await o.download(); + if (record.status.startsWith("ok")) { + o.onLog("The stored media URL's download is clean: the audio is transcribed in full."); + return "clean"; + } + if (o.signal?.aborted) throw abortError(); + const next = await gate(o.videoDir); + if (!next) return "not-needed"; + state = next; + if (record.failureClass === "rate_limit" && !state.exhausted) { + throw new Error( + `The stored media URL refused the download (rate limited; ${fullAudioLine(state)}). ` + + `The salvage waits for the full-audio attempts: transcribe again later.`, + ); + } + o.onLog(`The download ended ${record.status}${record.failureClass ? ` (${record.failureClass})` : ""}; ${fullAudioLine(state)}.`); + } + return state.exhausted ? "exhausted" : "not-needed"; +} + +function abortError(): Error { + const err = new Error("full-audio download aborted"); + err.name = "AbortError"; + return err; +} diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -24,6 +24,9 @@ import { resolveSavedVideo } from "../lib/savedVideo-server"; import { writeTranscribeOutcome } from "../lib/transcribeOutcome-server"; import type { TranscriptSalvage } from "../lib/transcribeOutcome"; import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; +import { fullAudioGate } from "../lib/fullAudioFirst-server"; +import { fullAudioFirstRefusal } from "../lib/fullAudioFirst"; +import { readChannelConfigFile } from "./channels"; import { SALVAGE_WAV_FILENAME, describeSalvage, @@ -174,8 +177,9 @@ export type TranscribeOneOptions = { // what is missing in transcribe-outcome.json's `salvaged`. Asked for by // `transcribe-one {"salvage": true}`; AUTOMATIC for a video whose download // outcome is corrupt-full-source (its file is known to be malformed, and a - // plain run fails at the first bad window), or whose held audio the audio - // audit found damaged (release 31). False forces a plain run. + // plain run fails at the first bad window) — once its full-audio attempts + // are made (release 32 R8, lib/fullAudioFirst.ts) — or whose held audio the + // audio audit found damaged (release 31). False forces a plain run. salvage?: boolean; }; @@ -235,10 +239,26 @@ export async function transcribeOneVideo( // said not to — or when the file about to be read is held audio the audio // audit found damaged (release 31, lane A: its audio-integrity.json still // speaks for this very file). +// +// FULL AUDIO FIRST (operator ruling 2026-10-17, release 32 R8): a corrupt full +// source whose record stores a trusted media URL is not salvaged automatically +// until FULL_AUDIO_ATTEMPTS stored-URL downloads were made +// (lib/fullAudioFirst.ts) — the run is refused as "no-audio" (a batch skips +// it, no failure recorded). `salvage: true` still forces one. async function salvageWanted(opts: TranscribeOneOptions, resolvedAudio: string): Promise<boolean> { if (opts.salvage !== undefined) return opts.salvage; const outcome = await loadDownloadOutcome(opts.videoDir).catch(() => null); - if (outcome?.status === "corrupt-full-source") return true; + if (outcome?.status === "corrupt-full-source") { + // The channel's config.json, beside data/<id>/: its handling and its + // stored-URL mode (an explicit "never" keeps the old behaviour). + const config = await readChannelConfigFile(path.join(path.dirname(path.dirname(opts.videoDir)), "config.json")).catch(() => null); + const gate = await fullAudioGate(opts.videoDir, { + ...(config?.handling ? { handling: config.handling } : {}), + ...(config?.storedUrlDownloads ? { mode: config.storedUrlDownloads } : {}), + }); + if (gate && !gate.exhausted) throw new TranscribeError(fullAudioFirstRefusal(gate), "no-audio"); + return true; + } const damage = await heldAudioDamage(opts.videoDir).catch(() => null); return damage !== null && damage.file === resolvedAudio; } diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -86,6 +86,9 @@ export type DownloadFileOpts = { const RETRYABLE = new Set([429, 502, 503, 504]); +// How much of a file `probe` asks for. +export const PROBE_BYTES = 1024; + function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> { return new Promise((resolve, reject) => { if (signal?.aborted) return reject(signal.reason ?? new Error("aborted")); @@ -153,7 +156,7 @@ export class ArchiveOrgClient { } // One GET, with the gap before it and the retry policy around it. - private async getOnce(url: string, accept: string, signal?: AbortSignal): Promise<Response> { + private async getOnce(url: string, accept: string, signal?: AbortSignal, extraHeaders: Record<string, string> = {}): Promise<Response> { let lastError = ""; for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) { const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); @@ -165,7 +168,7 @@ export class ArchiveOrgClient { res = await this.deps.fetch(url, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout, redirect: "follow", - headers: { accept, "user-agent": ARCHIVE_ORG_USER_AGENT }, + headers: { accept, "user-agent": ARCHIVE_ORG_USER_AGENT, ...extraHeaders }, }); } catch (err) { if (signal?.aborted) throw err; @@ -203,6 +206,26 @@ export class ArchiveOrgClient { }); } + // Whether `url` serves bytes: ONE ranged GET of its first `PROBE_BYTES` + // (release 32 R8, the Wayback "found" check), through the same chain, gap + // and back-off; the body is never read past those bytes. Answers the status + // (200 or 206 when it serves, with its content type), or the refusal's status + // when it answered an error that is not retried (404, 410, 403 …). Throws + // ArchiveOrgRequestError `rateLimited` when it kept refusing (429/503). + probe(url: string, signal?: AbortSignal): Promise<{ ok: boolean; status: number; contentType: string | null }> { + return this.serial(async () => { + try { + const res = await this.getOnce(url, "*/*", signal, { range: `bytes=0-${PROBE_BYTES - 1}` }); + const contentType = res.headers.get("content-type"); + await res.body?.cancel().catch(() => {}); + return { ok: true, status: res.status, contentType }; + } catch (e) { + if (e instanceof ArchiveOrgRequestError && e.status !== null) return { ok: false, status: e.status, contentType: null }; + throw e; + } + }); + } + getJson(url: string, signal?: AbortSignal): Promise<unknown> { return this.serial(async () => { const res = await this.getOnce(url, "application/json", signal); diff --git a/common/lib/fullAudioFirst-server.ts b/common/lib/fullAudioFirst-server.ts @@ -0,0 +1,17 @@ +// The reader of a video's full-audio state (lib/fullAudioFirst.ts): its +// download record and whether its record stores a trusted media URL. + +import { loadDownloadOutcome } from "./downloadOutcome-server"; +import { fullAudioState, type FullAudioState } from "./fullAudioFirst"; +import { storedMediaUrl } from "./storedMediaUrl-server"; +import type { StoredUrlMode } from "./storedMediaUrl"; + +export async function fullAudioGate( + videoDir: string, + o: { handling?: string; mode?: StoredUrlMode } = {}, +): Promise<FullAudioState | null> { + const record = await loadDownloadOutcome(videoDir).catch(() => null); + if (record?.status !== "corrupt-full-source") return null; + const stored = await storedMediaUrl(videoDir); + return fullAudioState(record, { storedUrlTrusted: stored !== null, ...o }); +} diff --git a/common/lib/fullAudioFirst.ts b/common/lib/fullAudioFirst.ts @@ -0,0 +1,67 @@ +// FULL AUDIO BEFORE A SALVAGE (operator ruling 2026-10-17; release 32 R8). +// +// A corrupt-full-source video (release 30, lane Q: the download completed, its +// audio stayed malformed) used to be salvage-transcribed as soon as anyone +// transcribed it. The ruling: a partial transcript is fine and stays marked, +// but only once the full audio has been tried. For a record whose platform +// serves its stored media URL (lib/storedMediaUrl.ts, STORED_URL_PLATFORMS), +// the corrupt-source path first downloads from that URL — R7's ranged reader +// with the audio check (ytdlp/storedUrlDownload.ts) — FULL_AUDIO_ATTEMPTS +// times, paced by R7's gap (STORED_URL_NEW_FILE_GAP_MS), and only then may a +// salvage transcript be made. A clean download retires a salvage already made +// (corruptRefetch.ts, release 30's rule). +// +// AN ATTEMPT is a `stored-url-ranged` attempt in the video's download record: +// a refetch appends its attempts to the corrupt-full-source record, so the +// count is the video's whole stored-URL history. A refusal (429) counts: the +// ruling is a number of attempts, not of successes. +// +// NOT APPLICABLE (null): a video that is not a corrupt full source, a record +// with no trusted stored URL, a channel that is not transcribe handling, or a +// stored-URL mode of "never" (the request's, else the channel's +// `storedUrlDownloads` — an explicit never keeps release 30's behaviour). +// +// Pure: the reader is fullAudioFirst-server.ts. + +import type { DownloadOutcomeRecord } from "./downloadOutcome"; +import type { StoredUrlMode } from "./storedMediaUrl"; + +export const FULL_AUDIO_ATTEMPTS = 2; + +export type FullAudioState = { + // Stored-URL full-download attempts made so far. + attempts: number; + of: number; + // Every attempt made: a salvage may follow. + exhausted: boolean; +}; + +export function fullAudioAttemptsOf(record: Pick<DownloadOutcomeRecord, "attempts"> | null | undefined): number { + return (record?.attempts ?? []).filter((a) => a.kind === "stored-url-ranged").length; +} + +export function fullAudioState( + record: Pick<DownloadOutcomeRecord, "status" | "attempts"> | null | undefined, + o: { storedUrlTrusted: boolean; handling?: string; mode?: StoredUrlMode }, +): FullAudioState | null { + if (record?.status !== "corrupt-full-source") return null; + if (!o.storedUrlTrusted || o.mode === "never") return null; + if (o.handling !== undefined && o.handling !== "transcribe") return null; + const attempts = fullAudioAttemptsOf(record); + return { attempts, of: FULL_AUDIO_ATTEMPTS, exhausted: attempts >= FULL_AUDIO_ATTEMPTS }; +} + +// "full audio attempts: 1 of 2" +export function fullAudioLine(s: Pick<FullAudioState, "attempts" | "of">): string { + return `full audio attempts: ${s.attempts} of ${s.of}`; +} + +// What a transcription that would salvage too early says (transcribeOne's +// refusal; the editor's Transcribe downloads the attempts first). +export function fullAudioFirstRefusal(s: FullAudioState): string { + return ( + `Full audio first (${fullAudioLine(s)}): a salvage transcript waits until the stored media URL ` + + `has been tried ${s.of} times. Transcribe from the video page downloads them first; ` + + `transcribe with salvage to make the partial transcript now.` + ); +} diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts @@ -23,7 +23,7 @@ import { sectionSchema, slideSchema, } from "./schema"; -import { VERDICT_DEFAULTS, VERDICT_LABEL_MAX, VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS } from "./verdicts"; +import { VERDICT_DEFAULTS, VERDICT_LABEL_MAX, VERDICT_MEANINGS, VERDICT_PARTS_RULE, VERDICTS } from "./verdicts"; export function renderReportMarkdown(): string { const out: string[] = []; @@ -151,7 +151,7 @@ export function renderReportMarkdown(): string { out.push(`| \`${v}\` | ${cell(VERDICT_MEANINGS[v])} | ${cell(d.label)} | \`${d.color}\` |`); } out.push(""); - out.push(`${VERDICT_TIE_RULE} The meanings are the operator's standard; the verdict bench's prompt and the verdict proposals read the same sentences.`); + out.push(`${VERDICT_PARTS_RULE} The meanings are the operator's standard; the verdict bench's prompt and the verdict proposals read the same sentences.`); out.push(""); out.push("## Iterations"); out.push(""); diff --git a/common/lib/report/draft/bench/bench.test.ts b/common/lib/report/draft/bench/bench.test.ts @@ -16,6 +16,7 @@ import { LOCAL_PROMPT_CAP, passesBar, planVerdictBench, + validateBenchOptions, readBenchRun, runVerdictBench, scoreBench, @@ -27,11 +28,19 @@ import { markedScore, stratifiedLimit, turnOf, + readVerdictAnswer, + verdictOfParts, + sectionNamesVerdict, + EVIDENCE_MAX, + EVIDENCE_QUOTE_MAX, + PARTS_MAX, + PART_MAX, + REASON_MAX, type BenchAsk, type BenchItem, type BenchResult, } from "./index"; -import { VERDICT_MEANINGS, VERDICT_TIE_RULE } from "../../verdicts"; +import { VERDICT_MEANINGS, VERDICT_PARTS_RULE } from "../../verdicts"; import { CLAIM_FIELD_DOCS } from "../../schema"; import { renderReportMarkdown } from "../../docs"; import { promptEstimate } from "../../../llm/ollama"; @@ -69,6 +78,18 @@ async function store(mutate?: (r: any) => void) { return { dir, paths, done: () => rm(dir, { recursive: true, force: true }) }; } +// A v3 answer (the parts and their findings) that makes verdict `v`. +function answerOf(v: Verdict, reason: string) { + const parts: Record<Verdict, { part: string; finding: string }[]> = { + CORROBORATED: [{ part: "what she said", finding: "shown" }], + PARTLY: [{ part: "what she said", finding: "shown" }, { part: "the rest", finding: "not shown" }], + CONTRADICTED: [{ part: "what she said", finding: "shown wrong" }], + NOT_FOUND: [{ part: "what she said", finding: "not shown" }], + UNTESTABLE: [], + }; + return { parts: parts[v], checkable: v !== "UNTESTABLE", reason }; +} + const claimOf = (user: string) => /^Claim: (.*)$/m.exec(user)?.[1] ?? ""; // The synthetic claims' texts, to answer by. @@ -235,14 +256,14 @@ test("run: Sonnet over the fake API, qwen over the fake ollama — answers writt for (let i = 0; i < 7; i++) { api.push((body: any) => { const id = texts[claimOf(userOf(body))]!; - return toolTurn("answer", { verdict: id === "r05" ? "PARTLY" : TRUTH[id], reason: `ruled on ${id} ${"x".repeat(400)}` }); + return toolTurn("answer", answerOf(id === "r05" ? "PARTLY" : TRUTH[id]!, `ruled on ${id} ${"x".repeat(400)}`)); }); } // qwen: always CORROBORATED, and r03's answer is not JSON (twice: the retry too). for (let i = 0; i < 8; i++) { ol.push((body: any) => { const id = texts[claimOf(body.messages[1].content)]!; - return id === "r03" ? reply("I think it is partly true") : jsonReply({ verdict: "CORROBORATED", reason: "she says so" }); + return id === "r03" ? reply("I think it is partly true") : jsonReply(answerOf("CORROBORATED", "she says so")); }); } try { @@ -293,7 +314,7 @@ test("run: Sonnet over the fake API, qwen over the fake ollama — answers writt test("run: the cap is checked before each API call — past it the run stops capped, with what it did", async () => { const s = await store(); const api = await startFakeAnthropic(); - for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "ok" })); + for (let i = 0; i < 7; i++) api.push(toolTurn("answer", answerOf("CORROBORATED", "ok"))); try { // One call costs about a cent at Opus 5.5's price; a two-cent cap stops early. const out = await runVerdictBench( @@ -324,7 +345,7 @@ test("run: a re-run with the same id resumes — answered pairs skipped, failed const api = await startFakeAnthropic(); const llm = { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }; // First run: r01–r03 answered, then three 400s in a row (not retried) stop the model. - for (let i = 0; i < 3; i++) api.push((body: any) => toolTurn("answer", { verdict: TRUTH[texts[claimOf(userOf(body))]!], reason: "ok" })); + for (let i = 0; i < 3; i++) api.push((body: any) => toolTurn("answer", answerOf(TRUTH[texts[claimOf(userOf(body))]!]!, "ok"))); for (let i = 0; i < 3; i++) api.push(errorTurn(400, "invalid_request_error", "a bad request")); try { const first = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm }); @@ -334,7 +355,7 @@ test("run: a re-run with the same id resumes — answered pairs skipped, failed assert.equal(first.summary.score.models[0]!.errors, 3); assert.equal(first.summary.score.models[0]!.asked, 6); // The re-run asks only the four not answered (three failed, one never asked). - for (let i = 0; i < 4; i++) api.push((body: any) => toolTurn("answer", { verdict: TRUTH[texts[claimOf(userOf(body))]!], reason: "ok" })); + for (let i = 0; i < 4; i++) api.push((body: any) => toolTurn("answer", answerOf(TRUTH[texts[claimOf(userOf(body))]!]!, "ok"))); const again = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm }); assert.equal(api.requests.length, 10); const asked = api.requests.slice(6).map((b: any) => texts[claimOf(userOf(b))]); @@ -392,19 +413,21 @@ function stubAsk(answers: (model: string, id: string) => unknown, texts: Record< return { ask, asked }; } -test("V1 prompt: the meanings are the shared module's, the tie rule is in, reason before verdict, the context shown, a version", async () => { +test("V1/v3 prompt: the meanings are the shared module's, the parts rule is in, parts before the reason, the context shown, a version", async () => { for (const v of VERDICTS) assert.ok(VERDICT_BENCH_SYSTEM.includes(`- ${v}: ${VERDICT_MEANINGS[v]}`), v); - assert.ok(VERDICT_BENCH_SYSTEM.includes(VERDICT_TIE_RULE)); + assert.ok(VERDICT_BENCH_SYSTEM.includes(VERDICT_PARTS_RULE)); assert.match(VERDICT_MEANINGS.CORROBORATED, /substance/); - assert.match(VERDICT_MEANINGS.PARTLY, /shown .* overstated or wrong/); + assert.match(VERDICT_MEANINGS.PARTLY, /some parts .* at least one is not/); assert.ok(!/example|e\.g\./i.test(VERDICT_BENCH_SYSTEM)); - assert.deepEqual(Object.keys(VERDICT_ANSWER_SCHEMA.properties), ["reason", "verdict"]); - assert.deepEqual(VERDICT_ANSWER_SCHEMA.required, ["reason", "verdict"]); + assert.deepEqual(Object.keys(VERDICT_ANSWER_SCHEMA.properties), ["parts", "checkable", "reason"]); + assert.deepEqual(VERDICT_ANSWER_SCHEMA.required, ["parts", "checkable", "reason"]); + // The model names no verdict: the schema has none. + assert.ok(!("verdict" in VERDICT_ANSWER_SCHEMA.properties)); assert.equal(typeof PROMPT_VERSION, "string"); // The same sentences in REPORT.md and the claim's docs: nowhere else spells them out. const md = renderReportMarkdown(); for (const v of VERDICTS) assert.ok(md.includes(VERDICT_MEANINGS[v]), `REPORT.md lacks ${v}'s meaning`); - assert.ok(md.includes(VERDICT_TIE_RULE)); + assert.ok(md.includes(VERDICT_PARTS_RULE)); assert.match(CLAIM_FIELD_DOCS.verdict, /what each means/); // The context: the report's title, the section, each quote's speaker (the channel) and date. const s = await store(); @@ -453,7 +476,7 @@ test("V1 items: the turn mode — the speaker's segments, else a pause or a >> c assert.deepEqual(turnOf(cues, segs, { start: 5, end: 7 }, 0, 100), { from: 4, to: 13, bound: "speaker" }); const s = await store((r) => { - // r01 cites a missing citation and a post beside its span: both dropped, the claim kept. + // r01 cites a missing citation (dropped) and a post beside its span (v3: its evidence), the claim kept. r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "a post" }; r.sections[0].claims[0].citations = ["q01", "p1", "gone"]; // r02's second citation is a recording with no cues: dropped. @@ -466,11 +489,11 @@ test("V1 items: the turn mode — the speaker's segments, else a pause or a >> c assert.deepEqual( secs.dropped.map((d) => [d.key, d.citation, d.reason]), [ - ["synth-ruled/r01", "p1", "not a video or audio citation"], ["synth-ruled/r01", "gone", "not in the report's citations"], ["synth-ruled/r02", "q99", "the recording has no cues"], ], ); + assert.deepEqual(secs.items.find((i) => i.claim === "r01")!.evidence!.map((e) => e.citation), ["p1"]); assert.ok(secs.items.every((i) => i.windows.every((w) => w.bound === "seconds"))); // Turn mode over the synthetic cues (0.2 s apart: one long turn) is bounded by the window. const turn = await benchItemsOf(reports, { cuesOf, windowS: 10, windowMode: "turn" }); @@ -511,7 +534,7 @@ test("V1 run: the injected ask, reason before verdict, a per-call trace; --items const s = await store(); const texts = await claimTexts(); // Sonnet right everywhere; qwen says PARTLY on r01, right elsewhere. - const { ask, asked } = stubAsk((model, id) => ({ reason: `on ${id}`, verdict: model === "qwen3:8b" && id === "r01" ? "PARTLY" : TRUTH[id] }), texts); + const { ask, asked } = stubAsk((model, id) => answerOf(model === "qwen3:8b" && id === "r01" ? "PARTLY" : TRUTH[id]!, `on ${id}`), texts); const root = benchRootOf(s.paths); try { const first = await runVerdictBench({ runId: "vb-one", models: ["claude-sonnet-5-5", "qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask }); @@ -520,7 +543,7 @@ test("V1 run: the injected ask, reason before verdict, a per-call trace; --items assert.equal(first.summary.promptVersion, PROMPT_VERSION); assert.equal(first.summary.windowMode, "seconds"); assert.match(first.summary.itemsHash!, /^[0-9a-f]{16}$/); - assert.deepEqual(Object.keys(asked[0]!.schema.properties), ["reason", "verdict"]); + assert.deepEqual(Object.keys(asked[0]!.schema.properties), ["parts", "checkable", "reason"]); // The trace: a start line and one line per call with the prompt the model saw and its answer. const trace = (await readFile(path.join(root, "vb-one", "trace.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.equal(trace[0].t, "start"); @@ -528,7 +551,7 @@ test("V1 run: the injected ask, reason before verdict, a per-call trace; --items const calls = trace.filter((l) => l.t === "call"); assert.equal(calls.length, 14); assert.ok(calls[0].user.startsWith("Report: ")); - assert.deepEqual(calls[0].answer, { reason: "on r01", verdict: "CORROBORATED" }); + assert.deepEqual(calls[0].answer, answerOf("CORROBORATED", "on r01")); // A run from vb-one's items: the same items, the same hash; only qwen asked. asked.length = 0; @@ -613,3 +636,115 @@ test("V1 score: not-CORROBORATED precision and recall; two runs compared; the op assert.notEqual(benchItemsHash([one]), benchItemsHash([{ ...one, text: "The article says otherwise." }])); assert.notEqual(benchItemsHash([one]), benchItemsHash([{ ...one, quotes: [{ ...one.quotes[0]!, end: 3 }] }])); }); + +test("v3 answer: the verdict follows from the parts in code; the counts and lengths are held in code", () => { + const P = (...f: string[]) => f.map((finding, i) => ({ part: `p${i}`, finding: finding as "shown" })); + assert.equal(verdictOfParts(P("shown", "shown"), true), "CORROBORATED"); + assert.equal(verdictOfParts(P("shown", "not shown"), true), "PARTLY"); + assert.equal(verdictOfParts(P("shown", "shown wrong"), true), "PARTLY"); + assert.equal(verdictOfParts(P("shown wrong", "not shown"), true), "CONTRADICTED"); + assert.equal(verdictOfParts(P("shown wrong"), true), "CONTRADICTED"); + assert.equal(verdictOfParts(P("not shown", "not shown"), true), "NOT_FOUND"); + assert.equal(verdictOfParts(P("shown"), false), "UNTESTABLE"); + assert.equal(verdictOfParts([], false), "UNTESTABLE"); + assert.equal(verdictOfParts([], true), null); + + // Too many parts, a part too long, a reason too long: cut. A part with an + // unknown finding is not a part. + const many = Array.from({ length: PARTS_MAX + 3 }, (_, i) => ({ part: `${"w".repeat(PART_MAX + 50)}${i}`, finding: "shown" })); + const a = readVerdictAnswer({ parts: [{ part: "x", finding: "maybe" }, ...many], checkable: true, reason: "r".repeat(REASON_MAX + 99) }); + assert.ok(a.ok); + if (a.ok) { + assert.equal(a.parts.length, PARTS_MAX); + assert.ok(a.parts.every((p) => p.part.length === PART_MAX)); + assert.equal(a.reason.length, REASON_MAX); + assert.equal(a.verdict, "CORROBORATED"); + } + // The parts past the limit never count: a "not shown" seventh part leaves it CORROBORATED. + const seventh = readVerdictAnswer({ parts: [...many.slice(0, PARTS_MAX), { part: "late", finding: "not shown" }], checkable: true, reason: "ok" }); + assert.ok(seventh.ok && seventh.verdict === "CORROBORATED"); + // Untestable with no parts; failures named. + const u = readVerdictAnswer({ parts: [], checkable: false, reason: "an opinion" }); + assert.ok(u.ok && u.verdict === "UNTESTABLE"); + assert.deepEqual(readVerdictAnswer({ parts: [], checkable: true, reason: "x" }), { ok: false, error: "no part with a finding", reason: "x" }); + assert.equal(readVerdictAnswer({ parts: [{ part: "a", finding: "shown" }], checkable: true, reason: " " }).ok, false); + assert.equal(readVerdictAnswer({ verdict: "CORROBORATED", reason: "a v2 answer" }).ok, false); + assert.equal(readVerdictAnswer(null).ok, false); +}); + +test("v3 items: a claim's posts and pages are its evidence (quoted, never a note); a heading naming a verdict withheld; a repeated claim asked once", async () => { + assert.equal(sectionNamesVerdict("Corroborated, with clips"), true); + assert.equal(sectionNamesVerdict("Only partially so"), true); + assert.equal(sectionNamesVerdict("Not found anywhere"), true); + assert.equal(sectionNamesVerdict("NOT_FOUND"), true); + assert.equal(sectionNamesVerdict("Found on the stream"), false); + assert.equal(sectionNamesVerdict("The bakery"), false); + assert.equal(sectionNamesVerdict(undefined), false); + + const long = "y".repeat(EVIDENCE_QUOTE_MAX + 40); + const s = await store((r) => { + r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "the oven ran hot all week", label: "post, 2026-01-06", speaker: "synth-kitchen", date: "2026-01-06" }; + r.citations.g1 = { kind: "page", url: "https://example.invalid/a", title: "A page", quote: long, note: "the checker's own comment" }; + r.citations.s1 = { kind: "source", source: "the-article", quote: "the claim's own sentence" }; + for (let i = 0; i < EVIDENCE_MAX; i++) r.citations[`px${i}`] = { kind: "post", channel: "synth-kitchen-posts", id: `px-${i}`, quote: `post ${i}` }; + r.sections[0].claims[1].citations = ["q02", "p1", "g1", "s1"]; + r.sections[0].claims[2].citations = ["q03", ...Array.from({ length: EVIDENCE_MAX }, (_, i) => `px${i}`), "p1"]; + r.sections[1].title = "Only partially so"; + }); + try { + const reports = await benchReportsOf(s.paths); + const { items, dropped } = await benchItemsOf(reports, { cuesOf }); + const r02 = items.find((i) => i.claim === "r02")!; + assert.deepEqual(r02.evidence!.map((e) => [e.citation, e.kind]), [["p1", "post"], ["g1", "page"]]); + assert.equal(r02.evidence![1]!.quote.length, EVIDENCE_QUOTE_MAX); + assert.equal(r02.evidence![1]!.title, "A page"); + assert.ok(!JSON.stringify(r02).includes("the checker's own comment")); + assert.deepEqual(dropped.filter((d) => d.key.endsWith("/r02")).map((d) => [d.citation, d.reason]), [["s1", "not a video, audio, post or page citation"]]); + assert.equal(items.find((i) => i.claim === "r03")!.evidence!.length, EVIDENCE_MAX); + assert.deepEqual(dropped.filter((d) => d.key.endsWith("/r03")).map((d) => d.citation), ["p1"]); + // The prompt quotes the evidence, with who and when. + const u = benchPrompt(r02).user; + assert.match(u, /^Cited posts and pages:$/m); + assert.match(u, /^- \[post, post, 2026-01-06\] "the oven ran hot all week" \(by: synth-kitchen; dated: 2026-01-06\)$/m); + assert.match(u, /^- \[page, A page\] "y+…"$/m); + // A heading that names a verdict is the answer: withheld. The other stays. + assert.equal(items.find((i) => i.claim === "r06")!.section, undefined); + assert.ok(!benchPrompt(items.find((i) => i.claim === "r06")!).user.includes("Section:")); + assert.equal(r02.section, "The bakery"); + // The hash covers the evidence; an item without any hashes as before v3. + const bare = items.map(({ evidence: _e, ...rest }) => rest); + assert.notEqual(benchItemsHash(items), benchItemsHash(bare)); + assert.equal(benchItemsHash(bare), benchItemsHash(bare.map((i) => ({ ...i, evidence: [] })))); + } finally { + await s.done(); + } + + // A report re-cut from another: its claims repeat the first's — asked once + // with dedupe, every claim asked without it (the default; ruling 2026-10-17). + const t = await store(); + try { + const report = JSON.parse(await readFile(RULED, "utf8")); + report.id = "synth-ruled-recut"; + report.sections[0].claims[0].text = "A claim this re-cut words differently."; + await mkdir(path.join(t.paths.articlesDir, report.id), { recursive: true }); + await writeFile(path.join(t.paths.articlesDir, report.id, "report.json"), JSON.stringify(report)); + const reports = await benchReportsOf(t.paths); + const all = await benchItemsOf(reports, { cuesOf }); + assert.equal(all.items.length, 14); + assert.equal(all.skipped.filter((x) => x.reason.startsWith("the same claim as")).length, 0); + const { items, skipped } = await benchItemsOf(reports, { cuesOf, dedupe: true }); + assert.equal(items.length, 8); + assert.deepEqual(items.filter((i) => i.report === "synth-ruled-recut").map((i) => i.claim), ["r01"]); + const same = skipped.filter((x) => x.reason.startsWith("the same claim as")); + assert.equal(same.length, 6); + assert.deepEqual(same[0], { key: "synth-ruled-recut/r02", report: "synth-ruled-recut", claim: "r02", reason: "the same claim as synth-ruled/r02" }); + assert.equal((await benchItemsOf(reports, { cuesOf, dedupe: false })).items.length, 14); + // The bench's option: a plan with dedupe asks 8, without it 14; dedupe + // never goes with items-from (that run's items are taken as they are). + assert.equal((await planVerdictBench({ models: ["qwen3:8b"] }, { paths: t.paths, cuesOf })).items.length, 14); + assert.equal((await planVerdictBench({ models: ["qwen3:8b"], dedupe: true }, { paths: t.paths, cuesOf })).items.length, 8); + assert.throws(() => validateBenchOptions({ models: ["qwen3:8b"], itemsFrom: "vb-x", dedupe: true }), /drop the dedupe/); + } finally { + await t.done(); + } +}); diff --git a/common/lib/report/draft/bench/items.ts b/common/lib/report/draft/bench/items.ts @@ -1,14 +1,27 @@ -// THE VERDICT BENCH'S ITEMS (release 28 M7; release 29 V1): one per ruled -// fact-check claim. +// THE VERDICT BENCH'S ITEMS (release 28 M7; release 29 V1; bench v3): one per +// ruled fact-check claim. // // An item is a claim of a `kind: "factcheck"` article that carries the // operator's `verdict` and at least one span citation (video or audio) whose // recording has cues around the cited seconds: the claim's text, its context // (the report's title, the claim's section heading; each quote's speaker and -// date), the cited quotes, and the transcript WINDOW around each cited span — -// overlapping windows of one recording merged. Every other claim is SKIPPED, -// and every citation of a kept claim that gives no window is DROPPED, each -// with its reason, and counted: nothing is left out silently. +// date), the cited quotes, the transcript WINDOW around each cited span — +// overlapping windows of one recording merged — and (v3) the claim's cited +// POSTS and PAGES as EVIDENCE: their quoted words, label, speaker and date +// (never a page's `note`, which is the checker's own comment). Every other +// claim is SKIPPED, and every citation of a kept claim that gives no window +// and is not evidence is DROPPED, each with its reason, and counted: nothing +// is left out silently. +// +// v3 also, from the diagnosis of bench v2's disagreements: +// - a section heading that NAMES A VERDICT ("Only partially so", "Corroborated, +// with clips") is withheld from the item: it is the answer, not context +// (`sectionNamesVerdict`); +// - a claim that repeats an earlier item — the same text over the same cited +// spans, as a report re-cut from another carries — is SKIPPED as the same +// claim (`benchItemsOf`'s `dedupe`) — counted once, asked once. OFF by +// default (operator ruling 2026-10-17): a fresh bench asks every claim, and +// dedupe is an explicit option (`--dedupe`, the body's `dedupe: true`). // // THE WINDOW MODES (V1): // seconds the cues within ±`windowS` of the cited span (M7's, the default) @@ -37,7 +50,7 @@ import type { CuesOf } from "../../convertShared"; import { articleFile, listArticleDirs } from "../../registry"; import type { Claim, Report } from "../../schema"; import { parseReport } from "../../validate"; -import { isVerdict, VERDICTS, type Verdict } from "../../verdicts"; +import { isVerdict, VERDICT_DEFAULTS, VERDICTS, type Verdict } from "../../verdicts"; export const DEFAULT_WINDOW_S = 60; @@ -81,6 +94,24 @@ export type BenchWindow = { bound?: WindowBound; }; +// A cited post or page (v3): what the operator read beside the transcript. +export type BenchEvidence = { + citation: string; + kind: "post" | "page"; + quote: string; + // A post's channel, a page's title. + channel?: string; + title?: string; + label?: string; + speaker?: string; + date?: string; +}; + +// The most evidence an item carries, and the longest quote of one (code, not +// the prompt, holds both). +export const EVIDENCE_MAX = 8; +export const EVIDENCE_QUOTE_MAX = 600; + export type BenchItem = { // `<report>/<claim>`: unique across a run. key: string; @@ -91,6 +122,8 @@ export type BenchItem = { verdict: Verdict; quotes: BenchQuote[]; windows: BenchWindow[]; + // v3: the claim's cited posts and pages (absent: none, or an item made before v3). + evidence?: BenchEvidence[]; // Context for the model (V1): the report's title and the claim's section heading. title?: string; section?: string; @@ -187,6 +220,29 @@ function mergeWindows(windows: BenchWindow[]): BenchWindow[] { return out; } +const VERDICT_WORDS_RE = new RegExp( + [ + ...VERDICTS.map((v) => v.replace(/_/g, "[ _]")), + ...VERDICTS.map((v) => VERDICT_DEFAULTS[v].label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")), + "corroborat", + "contradict", + "partially", + "partly", + "untestable", + ].join("|"), + "i", +); + +/** + * Whether a section heading names a verdict (its code, its default label, or + * a word of one: "Corroborated, with clips", "Only partially so") — the + * operator's grouping of claims BY their ruling, which an item must not carry. + * Pure. + */ +export function sectionNamesVerdict(title: string | undefined): boolean { + return !!title && VERDICT_WORDS_RE.test(title); +} + const overlaps = (a: { start: number; end: number }, from: number, to: number) => a.end >= from && a.start <= to; const changesSpeaker = (text: string) => /^\s*>>/.test(text); @@ -238,6 +294,19 @@ export function turnOf( return clip(sorted[a]!.start, sorted[b]!.end, "pause"); } +function evidenceOf(id: string, c: Extract<Citation, { kind: "post" | "page" }>): BenchEvidence { + const quote = c.quote.length > EVIDENCE_QUOTE_MAX ? `${c.quote.slice(0, EVIDENCE_QUOTE_MAX - 1)}…` : c.quote; + return { + citation: id, + kind: c.kind, + quote, + ...(c.kind === "post" ? { channel: c.channel } : c.title ? { title: c.title } : {}), + ...(c.label ? { label: c.label } : {}), + ...(c.speaker ? { speaker: c.speaker } : {}), + ...(c.date ? { date: c.date } : {}), + }; +} + type ReadClaim = { ok: true; item: ClaimItem; dropped: BenchDropped[] } | { ok: false; reason: string }; // One claim's quotes and windows (its verdict is the caller's business). @@ -250,10 +319,14 @@ async function readClaim(r: BenchReport, sectionTitle: string, claim: Claim, o: const ids = claim.citations ?? []; if (!ids.length) return { ok: false, reason: "no citation" }; const spans: (readonly [string, Citation])[] = []; + const evidence: BenchEvidence[] = []; for (const id of ids) { const c = citations[id]; if (!c) dropped.push({ key, citation: id, reason: "not in the report's citations" }); - else if (!isSpanCitation(c)) dropped.push({ key, citation: id, reason: "not a video or audio citation" }); + else if (c.kind === "post" || c.kind === "page") { + if (evidence.length >= EVIDENCE_MAX) dropped.push({ key, citation: id, reason: `past the ${EVIDENCE_MAX} posts and pages an item carries` }); + else evidence.push(evidenceOf(id, c)); + } else if (!isSpanCitation(c)) dropped.push({ key, citation: id, reason: "not a video, audio, post or page citation" }); else spans.push([id, c]); } if (!spans.length) return { ok: false, reason: "no video or audio citation" }; @@ -304,8 +377,9 @@ async function readClaim(r: BenchReport, sectionTitle: string, claim: Claim, o: text: claim.text, quotes, windows: mergeWindows(windows), + ...(evidence.length ? { evidence } : {}), ...(r.report.title ? { title: r.report.title } : {}), - ...(sectionTitle ? { section: sectionTitle } : {}), + ...(sectionTitle && !sectionNamesVerdict(sectionTitle) ? { section: sectionTitle } : {}), }, dropped, }; @@ -417,17 +491,33 @@ export function stratifiedLimit<T extends { verdict: Verdict }>(items: readonly return { kept: items.filter((it) => keep.has(it)), left: items.filter((it) => !keep.has(it)) }; } -// Every item of every report, in report then claim order; `limit` keeps a -// stratified sample (the rest are skipped, LIMIT_REASON). -export async function benchItemsOf(reports: readonly BenchReport[], o: ItemOptions & { limit?: number }): Promise<BenchItems> { +export const SAME_CLAIM_REASON = "the same claim as"; + +// What makes two items the same claim: the text and the cited spans. +const sameness = (i: Pick<BenchItem, "text" | "quotes">) => + JSON.stringify([i.text.trim(), i.quotes.map((q) => [q.channel, q.id, q.start, q.end]).sort()]); + +// Every item of every report, in report then claim order; `dedupe: true` +// (default off) skips a claim that repeats an earlier item (SAME_CLAIM_REASON +// and its key); `limit` keeps a stratified sample (the rest are skipped, LIMIT_REASON). +export async function benchItemsOf(reports: readonly BenchReport[], o: ItemOptions & { limit?: number; dedupe?: boolean }): Promise<BenchItems> { const items: BenchItem[] = []; const skipped: BenchSkipped[] = []; const dropped: BenchDropped[] = []; + const seen = new Map<string, string>(); for (const r of reports) { const got = await benchItemsOfReport(r, o); - items.push(...got.items); skipped.push(...got.skipped); - dropped.push(...got.dropped); + for (const it of got.items) { + const same = o.dedupe === true ? seen.get(sameness(it)) : undefined; + if (same) { + skipped.push({ key: it.key, report: it.report, claim: it.claim, reason: `${SAME_CLAIM_REASON} ${same}` }); + continue; + } + seen.set(sameness(it), it.key); + items.push(it); + dropped.push(...got.dropped.filter((d) => d.key === it.key)); + } } if (o.limit === undefined || o.limit < 0 || o.limit >= items.length) return { items, skipped, dropped }; const { kept, left } = stratifiedLimit(items, o.limit); @@ -442,11 +532,12 @@ export async function benchItemsOf(reports: readonly BenchReport[], o: ItemOptio /** * The identity of a run's items, so two runs can be said to be over the SAME * items: each item's key, the claim's text, the operator's verdict, its quotes' - * spans and its windows (recording, from, to, how many cues) — not the context + * spans, its windows (recording, from, to, how many cues) and (v3) its posts' + * and pages' quotes — not the context * lines, which a run made from an earlier run's items may add. 16 hex * characters of a sha256. */ -export function benchItemsHash(items: readonly Pick<BenchItem, "key" | "text" | "verdict" | "quotes" | "windows">[]): string { +export function benchItemsHash(items: readonly Pick<BenchItem, "key" | "text" | "verdict" | "quotes" | "windows" | "evidence">[]): string { const canon = items .map((i) => ({ k: i.key, @@ -454,6 +545,8 @@ export function benchItemsHash(items: readonly Pick<BenchItem, "key" | "text" | v: i.verdict, q: i.quotes.map((q) => [q.citation, q.channel, q.id, q.start, q.end, q.quote]), w: i.windows.map((w) => [w.channel, w.id, w.from, w.to, w.cues.length]), + // v3's evidence, only when an item has some: an item before v3 hashes as it did. + ...(i.evidence?.length ? { e: i.evidence.map((e) => [e.citation, e.kind, e.quote]) } : {}), })) .sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : 0)); return createHash("sha256").update(JSON.stringify(canon)).digest("hex").slice(0, 16); diff --git a/common/lib/report/draft/bench/prompt.ts b/common/lib/report/draft/bench/prompt.ts @@ -1,66 +1,151 @@ -// THE VERDICT BENCH'S PROMPT (release 28 M7; release 29 V1): one claim per call. +// THE VERDICT BENCH'S PROMPT (release 28 M7; release 29 V1; bench v3): one +// claim per call. // // Q0: the system prompt is rules only — what each verdict means (the // operator's standard, read from ../../verdicts.mjs VERDICT_MEANINGS and its -// tie rule: the one copy), and that the model judges only what the window -// shows — with no worked example. The reason's length is enforced in code -// (./run.ts cuts it at REASON_MAX), not trusted to the prompt. The answer -// schema puts `reason` BEFORE `verdict`: the model writes what the transcript -// shows, then rules on it. A local model's prompt is held under its cap (8k -// tokens) by trimming the WINDOW, the cues farthest from a cited span first; -// the claim, its context and the cited quotes are never trimmed. +// parts rule: the one copy), and that the model judges only what the evidence +// shows — with no worked example. Lengths and counts are enforced in code +// (./run.ts and `readVerdictAnswer` cut the reason at REASON_MAX, a part at +// PART_MAX, the parts at PARTS_MAX), not trusted to the prompt. A local +// model's prompt is held under its cap (8k tokens) by trimming the WINDOW, the +// cues farthest from a cited span first; the claim, its context, the cited +// quotes and the cited posts and pages are never trimmed. +// +// BENCH V3 — THE PARTS. The model no longer names a verdict. It splits the +// claim into its parts (the separate things it says were said or done) and +// gives each a finding — shown, shown wrong, not shown — plus whether the +// claim is checkable at all; the VERDICT follows in code (`verdictOfParts`), +// the same rule VERDICT_MEANINGS states. The diagnosis of bench v2's +// disagreements (release 30 lane V) found the models' holistic verdict +// treating a part the evidence does not show as no demotion (the operator +// rules PARTLY) and an absent post as no evidence (the operator read it). // // The user prompt carries the claim's context (V1): the report's title, the -// claim's section heading, each cited line's speaker (the citation's, else the -// channel) and the recording's date. +// claim's section heading (withheld when it names a verdict: ./items.ts), +// each cited line's speaker (the citation's, else the channel) and the +// recording's date; and (v3) the claim's cited posts and pages, quoted. // // PROMPT_VERSION names the prompt: a string, bumped BY HAND with any change to // the system prompt, the meanings, the schema or the user prompt's shape. A run // records it (summary.promptVersion; a run without one is M7's, "1"), and a // run is never resumed under another version (./run.ts). // -// The prompt reads an item's claim text, context, quotes and windows — never -// its `verdict` (the operator's ruling, the answer). +// The prompt reads an item's claim text, context, quotes, windows and +// evidence — never its `verdict` (the operator's ruling, the answer). -import { VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS } from "../../verdicts"; +import { isVerdict, VERDICT_MEANINGS, VERDICT_PARTS_RULE, VERDICTS, type Verdict } from "../../verdicts"; import { PROMPT_CAP_TOKENS, promptEstimate } from "../../../llm/ollama"; import type { BenchItem, BenchWindow } from "./items"; -export const PROMPT_VERSION = "2"; +export const PROMPT_VERSION = "3"; // The version a run with no `promptVersion` was made with (release 28 M7). export const M7_PROMPT_VERSION = "1"; export const REASON_MAX = 300; +// The most parts a claim is split into, and the longest a part is written. +export const PARTS_MAX = 6; +export const PART_MAX = 160; + +export const PART_FINDINGS = ["shown", "shown wrong", "not shown"] as const; +export type PartFinding = (typeof PART_FINDINGS)[number]; +export type ClaimPart = { part: string; finding: PartFinding }; +const isPartFinding = (v: unknown): v is PartFinding => typeof v === "string" && (PART_FINDINGS as readonly string[]).includes(v); export const VERDICT_ANSWER_SCHEMA = { type: "object", properties: { + parts: { + type: "array", + description: `First: the claim's parts, at most ${PARTS_MAX}, each with what the evidence shows of it.`, + items: { + type: "object", + properties: { + part: { type: "string", description: `One thing the claim says was said or done, in a few words (at most ${PART_MAX} characters).` }, + finding: { type: "string", enum: [...PART_FINDINGS], description: "What the evidence shows of this part." }, + }, + required: ["part", "finding"], + }, + }, + checkable: { + type: "boolean", + description: "false only when the claim as a whole is an opinion, a judgement or a prediction that no record could show true or false.", + }, reason: { type: "string", - description: `First: what the transcript shows about the claim, in one or two plain sentences of at most ${REASON_MAX} characters.`, + description: `Then: what the evidence shows about the claim, in one or two plain sentences of at most ${REASON_MAX} characters.`, }, - verdict: { type: "string", enum: [...VERDICTS], description: "Then: the ruling that reason supports." }, }, - required: ["reason", "verdict"], + required: ["parts", "checkable", "reason"], } as const; +/** + * The verdict a claim's parts make — the rule VERDICT_MEANINGS states, applied + * in code: not checkable → UNTESTABLE; every part shown → CORROBORATED; no + * part shown and one shown wrong → CONTRADICTED; no part shown or shown wrong + * → NOT_FOUND; anything else (some shown, some not or wrong) → PARTLY. No + * parts on a checkable claim is no verdict (null). Pure. + */ +export function verdictOfParts(parts: readonly Pick<ClaimPart, "finding">[], checkable: boolean): Verdict | null { + if (!checkable) return "UNTESTABLE"; + if (!parts.length) return null; + const shown = parts.filter((p) => p.finding === "shown").length; + const wrong = parts.filter((p) => p.finding === "shown wrong").length; + if (shown === parts.length) return "CORROBORATED"; + if (!shown) return wrong ? "CONTRADICTED" : "NOT_FOUND"; + return "PARTLY"; +} + +export type VerdictAnswer = + | { ok: true; verdict: Verdict; reason: string; parts: ClaimPart[]; checkable: boolean } + | { ok: false; error: string; reason?: string }; + +/** + * A model's answer to VERDICT_ANSWER_SCHEMA read and held to the counts: the + * parts cut to PARTS_MAX (each part's words to PART_MAX), the reason to + * REASON_MAX, and the verdict derived (`verdictOfParts`). Shared by the bench + * (./run.ts) and the verdict proposals (../tasks/verdicts.ts). + */ +export function readVerdictAnswer(ans: unknown): VerdictAnswer { + const a = (ans && typeof ans === "object" ? ans : {}) as { parts?: unknown; checkable?: unknown; reason?: unknown }; + const reason = typeof a.reason === "string" ? a.reason.trim().slice(0, REASON_MAX) : null; + const rawParts = Array.isArray(a.parts) ? a.parts : null; + if (!rawParts) return { ok: false, error: `no parts: ${JSON.stringify(ans ?? null).slice(0, 80)}`, ...(reason ? { reason } : {}) }; + const parts: ClaimPart[] = []; + for (const p of rawParts) { + const o = (p && typeof p === "object" ? p : {}) as { part?: unknown; finding?: unknown }; + if (typeof o.part !== "string" || !o.part.trim() || !isPartFinding(o.finding)) continue; + parts.push({ part: o.part.trim().slice(0, PART_MAX), finding: o.finding }); + if (parts.length >= PARTS_MAX) break; + } + const checkable = a.checkable !== false; + const verdict = verdictOfParts(parts, checkable); + if (!verdict) return { ok: false, error: "no part with a finding", ...(reason ? { reason } : {}) }; + if (!reason) return { ok: false, error: "no reason" }; + if (!isVerdict(verdict)) return { ok: false, error: "no verdict" }; + return { ok: true, verdict, reason, parts, checkable }; +} + export const VERDICT_BENCH_SYSTEM = [ - "You rule on one claim about what a person said in recordings, using only the transcript you are given.", + "You check one claim about what a person said or did on record, using only the evidence you are given.", "", - "You are shown the report the claim is from, the section it is in, the claim, the lines it cites (who says each and when the recording was made), and the transcript around each cited line (each line stamped with its time in the recording).", + "You are shown the report the claim is from, the section it is in, the claim, the lines it cites (who says each and when the recording was made), the transcript around each cited line (each line stamped with its time in the recording), and any posts or pages the claim cites.", "", "Rules:", - "- Judge only from the transcript shown. Do not use outside knowledge, and do not assume what may have been said elsewhere or off the record.", - "- Rule on the substance of the claim: what it says was said or done.", - "- The cited lines are where the claim's evidence was found; read the transcript around them before ruling, since context can change their meaning.", + "- Judge only from the evidence shown. Do not use outside knowledge, and do not assume what may have been said elsewhere or off the record.", + "- The cited lines, posts and pages are where the claim's evidence was found; read the transcript around each cited line before judging, since context can change its meaning.", "- The transcript is automatic speech recognition: forgive misspellings and missing punctuation, never a change of meaning.", - "- Write the reason first, naming what the transcript says; then give the verdict that reason supports.", + `- First split the claim into its parts, at most ${PARTS_MAX}. ${VERDICT_PARTS_RULE}`, + "- Give each part one finding:", + " - shown: the evidence shows it in substance: other words, a softer phrasing or a hedge still count.", + " - shown wrong: the evidence shows it is wrong: the opposite, a different number, date or person, or words put in quotation marks that are not the speaker's where the speaker's own words are shown.", + " - not shown: the evidence does not show it; the topic may come up without it.", + "- Set checkable to false only when the claim as a whole is an opinion, a judgement or a prediction that no record could show true or false.", + "- Then write the reason: what the evidence shows about the claim.", "", - "The verdicts:", + "What the verdict will be, from your findings:", ...VERDICTS.map((v) => `- ${v}: ${VERDICT_MEANINGS[v]}`), - `- ${VERDICT_TIE_RULE}`, "", - `The reason is at most ${REASON_MAX} characters.`, + `A part is at most ${PART_MAX} characters; the reason is at most ${REASON_MAX} characters.`, ].join("\n"); const stamp = (s: number) => { @@ -71,7 +156,7 @@ const stamp = (s: number) => { return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; }; -type Prompted = Pick<BenchItem, "text" | "quotes" | "windows" | "title" | "section">; +type Prompted = Pick<BenchItem, "text" | "quotes" | "windows" | "title" | "section" | "evidence">; function render(item: Prompted, windows: BenchWindow[]): string { const lines: string[] = []; @@ -83,6 +168,14 @@ function render(item: Prompted, windows: BenchWindow[]): string { const where = [q.label, stamp(q.start)].filter(Boolean).join(", "); lines.push(`- [${where}] "${q.quote}" (${said(q)})`); } + if (item.evidence?.length) { + lines.push("", "Cited posts and pages:"); + for (const e of item.evidence) { + const where = [e.kind, e.label ?? e.title ?? e.channel].filter(Boolean).join(", "); + const by = [e.speaker ? `by: ${e.speaker}` : "", e.date ? `dated: ${e.date}` : ""].filter(Boolean).join("; "); + lines.push(`- [${where}] "${e.quote}"${by ? ` (${by})` : ""}`); + } + } lines.push("", "Transcript:"); windows.forEach((w, i) => { const q = item.quotes.find((x) => x.channel === w.channel && x.id === w.id); diff --git a/common/lib/report/draft/bench/run.ts b/common/lib/report/draft/bench/run.ts @@ -37,7 +37,6 @@ import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, ty import { ApiKeyError } from "../../../llm/anthropic"; import { CHARS_PER_TOKEN } from "../../../llm/ollama"; import type { CuesOf } from "../../convertShared"; -import { isVerdict } from "../../verdicts"; import { benchItemsHash, benchItemsOf, @@ -52,7 +51,7 @@ import { type TurnsOf, type WindowMode, } from "./items"; -import { benchPrompt, LOCAL_PROMPT_CAP, M7_PROMPT_VERSION, PROMPT_VERSION, REASON_MAX, VERDICT_ANSWER_SCHEMA, VERDICT_BENCH_SYSTEM } from "./prompt"; +import { benchPrompt, LOCAL_PROMPT_CAP, M7_PROMPT_VERSION, PROMPT_VERSION, readVerdictAnswer, VERDICT_ANSWER_SCHEMA, VERDICT_BENCH_SYSTEM } from "./prompt"; import { scoreBench, type BenchResult } from "./score"; import { appendBenchTrace, @@ -94,6 +93,9 @@ export type BenchOptions = { limit?: number; // The exact items of this earlier run (no reports, window or limit with it). itemsFrom?: string; + // Ask a claim that repeats an earlier one (same text, same cited spans) once + // (items.ts SAME_CLAIM_REASON). Off by default: every claim is asked. + dedupe?: boolean; }; // The model, injected (R6's shape; tests): a structured answer to the prompt. @@ -135,7 +137,7 @@ export type BenchPlan = { estimateUsd: number; }; -export type ValidBenchOptions = { models: string[]; windowS: number; windowMode: WindowMode; maxUsd: number; limit?: number; itemsFrom?: string }; +export type ValidBenchOptions = { models: string[]; windowS: number; windowMode: WindowMode; maxUsd: number; limit?: number; itemsFrom?: string; dedupe?: true }; export function validateBenchOptions(o: BenchOptions): ValidBenchOptions { const models = [...new Set((o.models ?? []).map((m) => m.trim()).filter(Boolean))]; @@ -150,9 +152,10 @@ export function validateBenchOptions(o: BenchOptions): ValidBenchOptions { if (!Number.isFinite(maxUsd) || maxUsd <= 0) throw new BenchInputError("maxUsd must be a positive number of dollars"); if (maxUsd > BENCH_MAX_USD_LIMIT) throw new BenchInputError(`maxUsd $${maxUsd} is over the bench's limit of $${BENCH_MAX_USD_LIMIT}`); if (o.limit !== undefined && (!Number.isInteger(o.limit) || o.limit < 1)) throw new BenchInputError("limit is a whole number of items, at least 1"); + if (o.dedupe !== undefined && typeof o.dedupe !== "boolean") throw new BenchInputError("dedupe is true or false"); if (o.itemsFrom !== undefined) { if (!isBenchRunId(o.itemsFrom)) throw new BenchInputError("items-from is a run id: lowercase letters, digits and dashes"); - const also = [o.reports?.length ? "reports" : "", o.windowS !== undefined ? "window" : "", o.windowMode !== undefined ? "window mode" : "", o.limit !== undefined ? "limit" : ""].filter(Boolean); + const also = [o.reports?.length ? "reports" : "", o.windowS !== undefined ? "window" : "", o.windowMode !== undefined ? "window mode" : "", o.limit !== undefined ? "limit" : "", o.dedupe ? "dedupe" : ""].filter(Boolean); if (also.length) throw new BenchInputError(`items-from takes ${o.itemsFrom}'s items as they are: drop the ${also.join(", ")}`); } return { @@ -162,6 +165,7 @@ export function validateBenchOptions(o: BenchOptions): ValidBenchOptions { maxUsd, ...(o.limit !== undefined ? { limit: o.limit } : {}), ...(o.itemsFrom !== undefined ? { itemsFrom: o.itemsFrom } : {}), + ...(o.dedupe === true ? { dedupe: true as const } : {}), }; } @@ -199,6 +203,7 @@ type ItemSet = { windowMode: WindowMode; limit?: number; itemsFrom?: string; + dedupe?: true; }; // The context lines an item made before V1 lacks (the report's title, the @@ -245,6 +250,7 @@ async function itemSetOf(v: ValidBenchOptions, o: BenchOptions, deps: Pick<Bench windowS: src.summary.windowS, windowMode: src.summary.windowMode ?? "seconds", ...(src.summary.limit !== undefined ? { limit: src.summary.limit } : {}), + ...(src.summary.dedupe ? { dedupe: true as const } : {}), itemsFrom: v.itemsFrom, }; } @@ -256,6 +262,7 @@ async function itemSetOf(v: ValidBenchOptions, o: BenchOptions, deps: Pick<Bench ...(deps.turnsOf ? { turnsOf: deps.turnsOf } : {}), ...(deps.dateOf ? { dateOf: deps.dateOf } : {}), ...(v.limit ? { limit: v.limit } : {}), + ...(v.dedupe ? { dedupe: true } : {}), }); return { ...got, @@ -263,6 +270,7 @@ async function itemSetOf(v: ValidBenchOptions, o: BenchOptions, deps: Pick<Bench windowS: v.windowS, windowMode: v.windowMode, ...(v.limit !== undefined ? { limit: v.limit } : {}), + ...(v.dedupe ? { dedupe: true as const } : {}), // (planVerdictBench names the reports it read; a run records what was asked.) }; } @@ -327,6 +335,9 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise if (o.limit !== undefined && o.limit !== s.limit) { throw new BenchInputError(`run ${id} was made ${s.limit === undefined ? "with no limit" : `with a limit of ${s.limit}`}: drop the limit, or start a new run`); } + if (o.dedupe !== undefined && o.dedupe !== (s.dedupe === true)) { + throw new BenchInputError(`run ${id} was made ${s.dedupe ? "with" : "without"} dedupe: drop it, or start a new run`); + } if (o.reports?.length && [...o.reports].sort().join(",") !== [...s.reports].sort().join(",")) { throw new BenchInputError(`run ${id} was made over other reports: drop them, or start a new run`); } @@ -346,6 +357,7 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise windowMode: s.windowMode ?? "seconds", ...(s.limit !== undefined ? { limit: s.limit } : {}), ...(s.itemsFrom ? { itemsFrom: s.itemsFrom } : {}), + ...(s.dedupe ? { dedupe: true as const } : {}), }; results = prior.results; models = [...s.models, ...v.models.filter((m) => !s.models.includes(m))]; @@ -386,6 +398,7 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise maxUsd: v.maxUsd, reports: set.reports, ...(set.limit !== undefined ? { limit: set.limit } : {}), + ...(set.dedupe ? { dedupe: true as const } : {}), spentUsd: round6(priorSpend + meter.usd), items: items.length, skipped: set.skipped, @@ -448,16 +461,16 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise let r: BenchResult; let raw: unknown = undefined; try { - const ans = await ask<{ verdict?: unknown; reason?: unknown }>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model); + const ans = await ask<unknown>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model); raw = ans; - const verdict = isVerdict(ans?.verdict) ? ans.verdict : null; - const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : null; + // v3: the parts and their findings; the verdict follows in code. + const read = readVerdictAnswer(ans); r = { key: item.key, model, - verdict: verdict && reason !== null ? verdict : null, - ...(reason !== null ? { reason } : {}), - ...(verdict && reason !== null ? {} : { failure: "parse" as const, error: verdict ? "no reason" : `not a verdict: ${JSON.stringify(ans?.verdict ?? null).slice(0, 60)}` }), + verdict: read.ok ? read.verdict : null, + ...(read.reason ? { reason: read.reason } : {}), + ...(read.ok ? { parts: read.parts, ...(read.checkable ? {} : { checkable: false }) } : { failure: "parse" as const, error: read.error }), ms: Date.now() - t0, usd: 0, inputTokens: 0, diff --git a/common/lib/report/draft/bench/score.ts b/common/lib/report/draft/bench/score.ts @@ -34,6 +34,11 @@ export type BenchResult = { // The model's verdict, or null when it gave none. verdict: Verdict | null; reason?: string; + // v3: the claim's parts as the model found them (the verdict follows from + // them, ./prompt.ts verdictOfParts), and `checkable: false` when it judged + // the claim untestable. + parts?: { part: string; finding: "shown" | "shown wrong" | "not shown" }[]; + checkable?: false; // `parse`: no structured answer, or one outside the schema; `error`: the // call failed (the API, the network, a prompt over the local cap). failure?: "parse" | "error"; diff --git a/common/lib/report/draft/bench/store.ts b/common/lib/report/draft/bench/store.ts @@ -61,6 +61,8 @@ export type BenchSummary = { // The reports asked for (empty: every fact-check in the registry). reports: string[]; limit?: number; + // A run made with dedupe (a repeated claim asked once); absent: every claim asked. + dedupe?: true; spentUsd: number; items: number; skipped: BenchSkipped[]; diff --git a/common/lib/report/draft/tasks/verdicts.test.ts b/common/lib/report/draft/tasks/verdicts.test.ts @@ -60,6 +60,13 @@ function stub(answer: (claimText: string) => unknown) { return { ask, asked }; } + +// A bench v3 answer (the parts; the verdict follows in code) that makes `verdict`. +function v3(verdict: string, reason: string) { + const f: Record<string, string[]> = { CORROBORATED: ["shown"], PARTLY: ["shown", "not shown"], CONTRADICTED: ["shown wrong"], NOT_FOUND: ["not shown"], UNTESTABLE: [] }; + return { parts: f[verdict]!.map((finding, i) => ({ part: `part ${i}`, finding })), checkable: verdict !== "UNTESTABLE", reason }; +} + test("the model: only one in verdicts.models — the asked one, else the first on the route; none, or code, refused", () => { const gen = (models: string[], route: "api" | "local" | "code") => { const g = sanitizeGeneration({ verdicts: { bar: { agreement: 0.6, contradictedRecall: 0.5, notFoundRecall: 0.5 }, models } }); @@ -81,7 +88,7 @@ test("the model: only one in verdicts.models — the asked one, else the first o test("proposals: the unruled claims only, the bench's prompt, written to the sidecar — never a verdict on a claim; an unlisted model refused", async () => { const s = await store(); const before = readFileSync(s.file, "utf8"); - const { ask, asked } = stub((text) => ({ reason: `the window shows it: ${text.slice(0, 20)}`, verdict: text.includes("oven") ? "PARTLY" : "NOT_FOUND" })); + const { ask, asked } = stub((text) => v3(text.includes("oven") ? "PARTLY" : "NOT_FOUND", `the window shows it: ${text.slice(0, 20)}`)); await assert.rejects(proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [], ask }), /models is empty/); await assert.rejects(proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: ["claude-opus-5-5"], ask }), /has not cleared the verdict bench's bar/); assert.equal(asked.length, 0); @@ -111,7 +118,7 @@ async function shown(paths: Parameters<typeof readVerdictProposals>[1], id: stri test("the sidecar survives makeCurrent; approve sets the verdict through patchArticle, reject leaves the claim; a reviewed proposal is never asked again", async () => { const s = await store(); - const { ask, asked } = stub(() => ({ reason: "shown", verdict: "CONTRADICTED" })); + const { ask, asked } = stub(() => v3("CONTRADICTED", "shown")); await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW }); // A new iteration made current replaces report.json whole: the proposals stay. const report = JSON.parse(readFileSync(s.file, "utf8")); @@ -156,7 +163,7 @@ test("the sidecar survives makeCurrent; approve sets the verdict through patchAr test("review fix 1: a revision that drops a claim shifts the ids — the shifted proposal is stale (409, not waiting), and the new claim under the id is asked again", async () => { const s = await store(); - const { ask, asked } = stub((text) => ({ reason: `on ${text.slice(0, 30)}`, verdict: "CONTRADICTED" })); + const { ask, asked } = stub((text) => v3("CONTRADICTED", `on ${text.slice(0, 30)}`)); await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW }); // r02 rejected by the operator. await reviewVerdictProposal({ article: s.id, claim: "r02", decision: "reject", ...(await shown(s.paths, s.id, "r02")) }, s.paths, NOW); @@ -186,7 +193,7 @@ test("review fix 1: a revision that drops a claim shifts the ids — the shifted test("review fix 2: the review is a compare-and-set — a proposal rewritten between view and click is refused; concurrent approve and reject: one wins", async () => { const s = await store(); - const { ask } = stub(() => ({ reason: "shown", verdict: "CORROBORATED" })); + const { ask } = stub(() => v3("CORROBORATED", "shown")); await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW }); const seen = await shown(s.paths, s.id, "r02"); // Another run rewrites r02 to PARTLY after the operator saw CORROBORATED. @@ -239,7 +246,7 @@ test("an API model: held to maxUsd before each call; the spend is the Meter's", const s = await store(); const api = await startFakeAnthropic(); try { - for (let i = 0; i < 3; i++) api.push(toolTurn("answer", { reason: "shown", verdict: "PARTLY" })); + for (let i = 0; i < 3; i++) api.push(toolTurn("answer", v3("PARTLY", "shown"))); const out = await proposeVerdicts( { article: s.id, model: "claude-opus-5-5", maxUsd: 0.015 }, { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, allowed: ["claude-opus-5-5"] }, diff --git a/common/lib/report/draft/tasks/verdicts.ts b/common/lib/report/draft/tasks/verdicts.ts @@ -23,7 +23,6 @@ import { Meter, providerOf, StructuredAnswerError, structuredAnswer, type LlmCon import type { GenerationSettings } from "../../../generationSettings"; import type { Paths } from "../../../paths"; import type { CuesOf } from "../../convertShared"; -import { isVerdict } from "../../verdicts"; import { claimFingerprint, markVerdictsJob, proposalIsCurrent, readVerdictProposals, recordVerdictProposals, VerdictProposalsError, type NewProposal } from "../../verdictProposals"; import { benchPrompt, @@ -32,7 +31,7 @@ import { estimateCall, LOCAL_PROMPT_CAP, PROMPT_VERSION, - REASON_MAX, + readVerdictAnswer, unruledItemsOfReport, VERDICT_ANSWER_SCHEMA, type BenchAsk, @@ -182,13 +181,15 @@ export async function proposeVerdicts(input: VerdictsInput, deps: VerdictsDeps): } const prompt = benchPrompt(item, local ? { capTokens: localCap } : {}); try { - const ans = await ask<{ verdict?: unknown; reason?: unknown }>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model); - const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : ""; - if (!isVerdict(ans?.verdict) || !reason) throw new StructuredAnswerError(`not a verdict and a reason: ${JSON.stringify(ans ?? null).slice(0, 120)}`); - const p: NewProposal = { verdict: ans.verdict, reason, model, promptVersion: PROMPT_VERSION, at: now().toISOString(), fingerprint: fingerprints.get(item.claim) ?? "" }; + const ans = await ask<unknown>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model); + // The bench's reading (bench v3: the verdict follows from the parts). + const read = readVerdictAnswer(ans); + if (!read.ok) throw new StructuredAnswerError(`not a verdict and a reason (${read.error}): ${JSON.stringify(ans ?? null).slice(0, 120)}`); + const { verdict, reason } = read; + const p: NewProposal = { verdict, reason, model, promptVersion: PROMPT_VERSION, at: now().toISOString(), fingerprint: fingerprints.get(item.claim) ?? "" }; const { written, stale } = await recordVerdictProposals(article, { [item.claim]: p }, deps.paths, now()); if (written.length) proposed.push(item.claim); - log(`${item.claim}: ${ans.verdict} — ${reason}${stale.length ? " (not kept: the claim was ruled or changed meanwhile)" : ""}`); + log(`${item.claim}: ${verdict} — ${reason}${stale.length ? " (not kept: the claim was ruled or changed meanwhile)" : ""}`); } catch (err) { // The article gone (deleted mid-run): nothing more is written for it. if (err instanceof VerdictProposalsError && err.status === 404) throw err; diff --git a/common/lib/report/verdicts.mjs b/common/lib/report/verdicts.mjs @@ -21,28 +21,36 @@ export const VERDICT_DEFAULTS = Object.freeze({ }); /** - * What each verdict MEANS — the operator's standard (release 29 V1), the one - * copy: the verdict bench's prompt (draft/bench/prompt.ts), the verdict - * proposals that reuse it, REPORT.md (lib/report/docs.ts) and umtool's bench - * page read these sentences; nowhere else spells them out. A change here - * changes the bench's prompt: bump its PROMPT_VERSION with it. + * What each verdict MEANS — the operator's standard, the one copy: the verdict + * bench's prompt (draft/bench/prompt.ts), the verdict proposals that reuse it, + * REPORT.md (lib/report/docs.ts) and umtool's bench page read these + * sentences; nowhere else spells them out. A change here changes the bench's + * prompt: bump its PROMPT_VERSION with it. + * + * Bench v3 (release 30) rewrote them from the operator's 147 rulings: a claim + * is ruled by its PARTS (the separate things it says were said or done), and + * the verdict follows from what the evidence shows of each part — the rule + * `verdictOfParts` (draft/bench/prompt.ts) applies in code. */ export const VERDICT_MEANINGS = Object.freeze({ CORROBORATED: - "the substance of the claim is shown by the cited words. Framing, emphasis, or a detail the transcript does not show does not demote it.", + "every part of the claim is shown by the cited evidence in substance: other words, a softer phrasing or a hedge still count.", PARTLY: - "a part of the claim is shown by the transcript to be overstated or wrong. A part that is only not shown does not make a claim PARTLY.", + "some parts of the claim are shown and at least one is not: it is not in the evidence, or the evidence shows it wrong (a different number, date or person, or words put in quotation marks that are not the speaker's).", CONTRADICTED: - "the substance of the claim is shown to be wrong: the transcript shows the opposite of it, or something that cannot be true at the same time.", + "no part of the claim is shown, and the evidence shows a part wrong: the opposite of it, or something that cannot be true at the same time.", NOT_FOUND: - "the claim could be checked against what was said, and its substance is not in the transcript shown: the topic may come up without what the claim says about it.", + "no part of the claim is shown or shown wrong by the evidence: the topic may come up without what the claim says about it.", UNTESTABLE: - "the claim is an opinion, a judgement, a prediction, or anything else a transcript cannot show to be true or false.", + "the claim is an opinion, a judgement, a prediction, or anything else a record cannot show to be true or false.", }); -/** The rule between the two verdicts a ruling most often falls between. */ -export const VERDICT_TIE_RULE = - "In doubt between CORROBORATED and PARTLY: CORROBORATED, unless a part of the claim is shown overstated or wrong."; +/** + * How a claim splits into PARTS (bench v3; it replaced release 29's + * CORROBORATED/PARTLY tie rule, which the rulings did not bear out). + */ +export const VERDICT_PARTS_RULE = + "A claim's parts are the separate things it says were said or done: a statement, an event, a number, a date, words it puts in quotation marks as someone's. A word that only describes what was said (its tone, motive or importance) is not a part, and neither is a fact about the world outside what was said (whether a thing said is true). A part about how often something was said, or that it was never said, is shown when the evidence is consistent with it and does not show otherwise."; /** The longest label an override may set, in characters (trimmed). */ export const VERDICT_LABEL_MAX = 24; diff --git a/common/lib/report/verdicts.ts b/common/lib/report/verdicts.ts @@ -7,7 +7,7 @@ import { VERDICT_DEFAULTS as VERDICT_DEFAULTS_JS, VERDICT_LABEL_MAX as VERDICT_LABEL_MAX_JS, VERDICT_MEANINGS as VERDICT_MEANINGS_JS, - VERDICT_TIE_RULE as VERDICT_TIE_RULE_JS, + VERDICT_PARTS_RULE as VERDICT_PARTS_RULE_JS, VERDICTS as VERDICTS_JS, resolveVerdicts as resolveVerdictsJs, verdictOverrideProblems as verdictOverrideProblemsJs, @@ -25,11 +25,11 @@ export const VERDICT_DEFAULTS = VERDICT_DEFAULTS_JS as Readonly<Record<Verdict, export const VERDICT_LABEL_MAX: number = VERDICT_LABEL_MAX_JS; -// What each verdict means (the operator's standard) and the CORROBORATED/PARTLY -// tie rule: the one copy the bench's prompt, REPORT.md and umtool read. +// What each verdict means (the operator's standard) and how a claim splits +// into parts: the one copy the bench's prompt, REPORT.md and umtool read. export const VERDICT_MEANINGS = VERDICT_MEANINGS_JS as Readonly<Record<Verdict, string>>; -export const VERDICT_TIE_RULE: string = VERDICT_TIE_RULE_JS; +export const VERDICT_PARTS_RULE: string = VERDICT_PARTS_RULE_JS; export const VERDICT_COLOR_RE: RegExp = VERDICT_COLOR_RE_JS; diff --git a/common/lib/waybackClient.test.ts b/common/lib/waybackClient.test.ts @@ -7,7 +7,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { startFakeWayback } from "../testing/web/fakeWayback.mjs"; -import { parseCdxJson, waybackCdxUrl, WaybackClient, waybackReplayUrl, waybackYoutubeUrl } from "./waybackClient"; +import { parseCdxJson, videoInfoFormatUrls, waybackCdxUrl, WaybackClient, waybackReplayUrl, waybackStreamUrl, waybackYoutubeUrl, WAYBACK_STREAM_PROBES_MAX } from "./waybackClient"; import { ArchiveOrgRequestError } from "./archiveOrgClient"; const BREAD = "https://video.example/watch?v=bread-day-01"; @@ -95,3 +95,60 @@ test("youtubeVideoArchived: yt-dlp's check — the video index's formats, not a await wb.close(); } }); + +test("youtubeVideoStream (R8): listed AND its stream answers a ranged GET — else page only, each probe's status kept", async () => { + const wb = await startFakeWayback({ videos: ["waybackVid1", "pageOnly001"], streams: ["waybackVid1"] }); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const fmt = "https://rr1---sn-fake.googlevideo.com/videoplayback?itag=18&id=waybackVid1"; + assert.deepEqual(await c.youtubeVideoStream("waybackVid1"), { + formats: 1, + stream: waybackStreamUrl(fmt), + probes: [{ url: `https://web.archive.org/web/2id_/${fmt}`, status: 206 }], + }); + const page = await c.youtubeVideoStream("pageOnly001"); + assert.equal(page.formats, 1); + assert.equal(page.stream, null); + assert.deepEqual(page.probes.map((p) => p.status), [404]); + const none = await c.youtubeVideoStream("neverArch01"); + assert.deepEqual(none, { formats: 0, stream: null, probes: [] }); + // Each probe asked for its first bytes only. + assert.equal(wb.requests.filter((r) => r.path.startsWith("/web/2id_/")).length, 2); + } finally { + await wb.close(); + } +}); + +test("videoInfoFormatUrls: audio first for a dmux answer, repeats once, non-URLs skipped; at most WAYBACK_STREAM_PROBES_MAX probed", async () => { + assert.deepEqual(videoInfoFormatUrls({ formats: [{ url: "https://a.example/1" }, { url: "https://a.example/1" }, { url: 5 }, { url: "ftp://x" }] }), ["https://a.example/1"]); + assert.deepEqual(videoInfoFormatUrls({ dmux: true, formats: { video: [{ url: "https://v.example/v" }], audio: [{ url: "https://v.example/a" }] } }), ["https://v.example/a", "https://v.example/v"]); + assert.deepEqual(videoInfoFormatUrls({}), []); + assert.deepEqual(videoInfoFormatUrls(null), []); + const statuses: string[] = []; + const many = { formats: Array.from({ length: 6 }, (_, i) => ({ url: `https://rr1---sn-fake.googlevideo.com/videoplayback?itag=${i}&id=x` })) }; + const c = new WaybackClient( + { + fetch: async (url) => { + if (url.includes("/__wb/videoinfo")) return new Response(JSON.stringify(many), { status: 200 }); + statuses.push(url); + return new Response("<p>nope</p>", { status: 404, headers: { "content-type": "text/html" } }); + }, + }, + { minGapMs: 0 }, + ); + const got = await c.youtubeVideoStream("x"); + assert.equal(got.formats, 6); + assert.equal(got.stream, null); + assert.equal(statuses.length, WAYBACK_STREAM_PROBES_MAX); + // A 200 that is an HTML page is not a stream. + const html = new WaybackClient( + { + fetch: async (url) => + url.includes("/__wb/videoinfo") + ? new Response(JSON.stringify({ formats: [{ url: "https://rr1---sn-fake.googlevideo.com/videoplayback?itag=18&id=x" }] }), { status: 200 }) + : new Response("<html>Wayback Machine</html>", { status: 200, headers: { "content-type": "text/html; charset=utf-8" } }), + }, + { minGapMs: 0 }, + ); + assert.equal((await html.youtubeVideoStream("x")).stream, null); +}); diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -102,6 +102,45 @@ export function waybackYoutubeUrl(youtubeId: string, timestamp?: string): string return `${WAYBACK_ORIGIN}/web/${timestamp ?? ""}${timestamp ? "/" : ""}https://www.youtube.com/watch?v=${youtubeId}`; } +// THE STREAM of an archived YouTube format, as yt-dlp's extractor fetches it +// (archiveorg.py `_parse_fmt`): `https://web.archive.org/web/2id_/<format url>` +// — the raw bytes Wayback holds for that googlevideo URL, if any. +export function waybackStreamUrl(formatUrl: string): string { + return `${WAYBACK_ORIGIN}/web/2id_/${formatUrl}`; +} + +// The format URLs of the video index's answer, audio first (fetch-copies asks +// yt-dlp for `ba/b`): a dmux answer's `formats.audio` then `formats.video`, +// else `formats` in its order. Repeats once; anything not an http(s) URL is +// skipped. +export function videoInfoFormatUrls(raw: unknown): string[] { + const formats = (raw as { formats?: unknown } | null)?.formats; + const urlsOf = (list: unknown): string[] => + Array.isArray(list) + ? list.map((f) => (f as { url?: unknown } | null)?.url).filter((u): u is string => typeof u === "string" && /^https?:\/\//.test(u)) + : []; + const all = Array.isArray(formats) + ? urlsOf(formats) + : formats && typeof formats === "object" + ? [...urlsOf((formats as Record<string, unknown>).audio), ...urlsOf((formats as Record<string, unknown>).video), ...Object.entries(formats as Record<string, unknown>).filter(([k]) => k !== "audio" && k !== "video").flatMap(([, v]) => urlsOf(v))] + : []; + return [...new Set(all)]; +} + +// At most this many of a video's formats are probed for a stream (one ranged +// request each, paced): a video whose first three formats all 404 is taken as +// its page alone. +export const WAYBACK_STREAM_PROBES_MAX = 3; + +// What the "found" check saw (release 32 R8): the formats the video index +// lists, the stream that answered (null: none did — the page was captured, +// the video was not), and each probe's status. +export type WaybackVideoStream = { + formats: number; + stream: string | null; + probes: { url: string; status: number }[]; +}; + export class WaybackClient { private readonly http: ArchiveOrgClient; @@ -117,6 +156,11 @@ export class WaybackClient { // Whether the Wayback Machine holds the YouTube VIDEO itself (formats in // its videoinfo index — what yt-dlp asks), not only captures of its page. async youtubeVideoArchived(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise<boolean> { + return (await this.youtubeVideoFormats(youtubeId, o)).length > 0; + } + + // The video index's format URLs for a YouTube id (videoInfoFormatUrls). + async youtubeVideoFormats(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise<string[]> { const body = await this.http.getText(waybackVideoInfoUrl(youtubeId), "application/json", o.signal); let raw: unknown; try { @@ -124,10 +168,29 @@ export class WaybackClient { } catch { throw new ArchiveOrgRequestError(`the Wayback video index did not answer JSON for ${youtubeId}`, null, false); } - const formats = (raw as { formats?: unknown } | null)?.formats; - if (Array.isArray(formats)) return formats.length > 0; - // A dmux answer keeps its formats by kind. - return !!formats && typeof formats === "object" && Object.values(formats as Record<string, unknown>).some((v) => Array.isArray(v) && v.length > 0); + return videoInfoFormatUrls(raw); + } + + // THE "FOUND" CHECK (release 32 R8): the video index lists formats AND one + // of their streams answers. The index can list a video whose bytes Wayback + // does not hold (the live case: formats listed, 404 at the format URL), so + // each of the first WAYBACK_STREAM_PROBES_MAX formats is probed with one + // ranged GET through the paced client; the first that serves (200/206, not + // an HTML page) is the stream. Throws ArchiveOrgRequestError when the index + // or a probe kept refusing. + async youtubeVideoStream(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise<WaybackVideoStream> { + const formats = await this.youtubeVideoFormats(youtubeId, o); + const out: WaybackVideoStream = { formats: formats.length, stream: null, probes: [] }; + for (const f of formats.slice(0, WAYBACK_STREAM_PROBES_MAX)) { + const url = waybackStreamUrl(f); + const p = await this.http.probe(url, o.signal); + out.probes.push({ url, status: p.status }); + if (p.ok && !/^text\/html\b/i.test(p.contentType ?? "")) { + out.stream = url; + break; + } + } + return out; } // The captures of `url`, oldest first: every capture, or (`okOnly`) only the diff --git a/common/publish/findCopy.test.ts b/common/publish/findCopy.test.ts @@ -15,7 +15,7 @@ import { startFakeWayback } from "../testing/web/fakeWayback.mjs"; import { startFakeArchiveOrg, type FakeArchiveOrgItem } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; import { ArchiveOrgClient } from "../lib/archiveOrgClient"; import { WaybackClient } from "../lib/waybackClient"; -import type { FailedCopy } from "../lib/copyAttempts-server"; +import type { CopyAttempt, FailedCopy } from "../lib/copyAttempts-server"; import type { MissingEvidenceWindows, UnfetchableEvidenceWindow } from "./reportMedia"; import type { ReportHost } from "./reportHost"; import type { Paths } from "../lib/paths"; @@ -26,6 +26,7 @@ import { mirrorNamesId, pickMirrorFile, runFindCopy, + WAYBACK_PAGE_ONLY, youtubeIdOf, youtubeIdQuery, type RecordFacts, @@ -89,17 +90,27 @@ const FACTS: Record<string, RecordFacts> = { v5abcde: { webpageUrl: "https://rumble.com/v5abcde-a-stream.html", duration: 100, videoDir: "/x/v5abcde" }, }; -async function fakes(o: { waybackBusy?: number; failed?: Record<string, FailedCopy[]>; need?: MissingEvidenceWindows } = {}) { - const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0, videos: [WB] }); - const ia = await startFakeArchiveOrg({ items: ITEMS }); +async function fakes( + o: { waybackBusy?: number; failed?: Record<string, FailedCopy[]>; need?: MissingEvidenceWindows; videos?: string[]; streams?: string[]; streamBusy?: number; items?: FakeArchiveOrgItem[] } = {}, +) { + const wb = await startFakeWayback({ + busyTimes: o.waybackBusy ?? 0, + videos: o.videos ?? [WB], + ...(o.streams ? { streams: o.streams } : {}), + streamBusyTimes: o.streamBusy ?? 0, + }); + const ia = await startFakeArchiveOrg({ items: o.items ?? ITEMS }); + const recorded: { dir: string; attempt: CopyAttempt }[] = []; const deps = { wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }), archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }), missing: async () => o.need ?? NEED, facts: async (_p: Paths, _slug: string, id: string) => FACTS[id]!, failedCopies: async (dir: string) => o.failed?.[dir] ?? [], + recordAttempt: async (dir: string, attempt: CopyAttempt) => void recorded.push({ dir, attempt }), + now: () => new Date("2026-10-17T00:00:00Z"), }; - return { wb, ia, deps, close: async () => Promise.all([wb.close(), ia.close()]) }; + return { wb, ia, deps, recorded, close: async () => Promise.all([wb.close(), ia.close()]) }; } const opts = (deps: unknown) => ({ paths: {} as Paths, host: { id: "articles" } as ReportHost, deps: deps as never }); @@ -157,7 +168,7 @@ test("archive-search by YouTube id: the mirror's direct file URL; a compilation }); test("find-copy: the Wayback video, else an archive.org mirror, else words only; a non-YouTube record is not looked for", async () => { - const { wb, ia, deps, close } = await fakes(); + const { wb, ia, deps, recorded, close } = await fakes(); try { const lines: string[] = []; const r = await findCopies({ ...opts(deps), onLog: (l) => lines.push(l) }); @@ -196,9 +207,63 @@ test("find-copy: the Wayback video, else an archive.org mirror, else words only; ], ); assert.ok(lines.some((l) => l.includes(COMP) && l.includes("its words only"))); + // The found check asked for WB's stream once (a ranged GET at yt-dlp's URL). + const probes = wb.requests.filter((q) => q.path.startsWith("/web/2id_/")); + assert.deepEqual(probes.map((q) => q.path), [`/web/2id_/https://rr1---sn-fake.googlevideo.com/videoplayback?itag=18&id=${WB}`]); + // (R8) The YouTube recordings neither source holds are recorded none-found; the Rumble one is not. + assert.deepEqual(recorded.map((x) => [x.dir, x.attempt.outcome]), [ + [`/x/${COMP}`, "none-found"], + [`/x/${NONE}`, "none-found"], + ]); + } finally { + await close(); + } +}); + +test("the Wayback found check: a video the index lists whose stream 404s is 'page captured, no video' — none found, recorded, never a copy", async () => { + // WB is in the video index, but Wayback holds no bytes for its format (the live case). + const { wb, deps, recorded, close } = await fakes({ streams: [], items: [], need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) } }); + try { + const lines: string[] = []; + const r = await findCopies({ ...opts(deps), onLog: (l) => lines.push(l) }); + assert.equal(r.recordings[0]!.outcome, "text-only"); + assert.deepEqual(r.items, [], "nothing goes to fetch-windows"); + const t = r.recordings[0]!.tried[0]!; + assert.deepEqual([t.from, t.found], ["wayback", false]); + assert.equal(t.error, undefined, "not a lookup error"); + assert.match(t.detail ?? "", new RegExp(`^${WAYBACK_PAGE_ONLY} \\(the video index lists 1 format\\(s\\); 1 probed, HTTP 404\\)$`)); + assert.equal(wb.requests.filter((q) => q.path.startsWith("/web/2id_/")).length, 1); + assert.equal(recorded.length, 1); + assert.equal(recorded[0]!.attempt.outcome, "none-found"); + assert.match(recorded[0]!.attempt.detail ?? "", /wayback none — page captured, no video/); + assert.ok(lines.some((l) => l.includes("page captured, no video") && l.includes("its words only"))); + // A dry run records nothing. + const dry = await runFindCopy({ ...opts(deps), dryRun: true, startFetch: async () => null }); + assert.equal(dry.recordings[0]!.outcome, "text-only"); + assert.equal(recorded.length, 1); } finally { await close(); } + // Page only on Wayback, a mirror on archive.org: the mirror is the copy. + const both = await fakes({ streams: [], need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) } }); + try { + const r = await findCopies(opts(both.deps)); + assert.equal(r.recordings[0]!.copy?.from, "archive.org"); + assert.match(r.recordings[0]!.tried[0]!.detail ?? "", /^page captured, no video/); + assert.equal(both.recorded.length, 0); + } finally { + await both.close(); + } + // A probe Wayback keeps refusing is a lookup error (tried again later), never none-found. + const busy = await fakes({ streamBusy: 50, need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) } }); + try { + const r = await findCopies(opts(busy.deps)); + assert.equal(r.recordings[0]!.outcome, "error"); + assert.match(r.stopped ?? "", /kept refusing/); + assert.equal(busy.recorded.length, 0); + } finally { + await busy.close(); + } }); test("a copy that failed before is not picked again: Wayback falls through to archive.org, a failed mirror to none", async () => { diff --git a/common/publish/findCopy.ts b/common/publish/findCopy.ts @@ -10,7 +10,12 @@ // page captures hold no video). The check is the one yt-dlp's // YoutubeWebArchive extractor makes before it fetches anything // (yt_dlp/extractor/archiveorg.py `_real_extract`: web.archive.org's -// `__wb/videoinfo?vtype=youtube&vid=<id>` has formats); the copy's URL is +// `__wb/videoinfo?vtype=youtube&vid=<id>` has formats) AND (release 32 +// R8) a format's stream answers a ranged GET (`/web/2id_/<format url>`, +// lib/waybackClient.ts youtubeVideoStream): the index lists videos whose +// bytes Wayback does not hold (the live case, 404 at the format URL), and +// such a video is "page captured, no video" — none found, never a copy +// that fails at its source; the copy's URL is // `https://web.archive.org/web/<ts>/https://www.youtube.com/watch?v=<id>`, // the form that extractor takes (the newest 200 capture's timestamp, when // the CDX names one); @@ -314,6 +319,10 @@ export async function waybackLookup( // ─── find-copy ─── +// The Wayback finding for a video the index lists but whose stream does not +// answer (release 32 R8): none found, recorded as such. +export const WAYBACK_PAGE_ONLY = "page captured, no video"; + export type FindCopyAttempt = { from: ClipCopy["from"]; found: boolean; @@ -352,11 +361,15 @@ export type FindCopyResult = { }; export type FindCopyDeps = { - wayback: Pick<typeof waybackClient, "captures" | "youtubeVideoArchived">; + wayback: Pick<typeof waybackClient, "captures" | "youtubeVideoStream">; archive: ArchiveOrgClient; missing: (paths: Paths, host: ReportHost) => Promise<MissingEvidenceWindows>; facts: (paths: Paths, slug: string, id: string) => Promise<RecordFacts>; failedCopies: (videoDir: string) => Promise<FailedCopy[]>; + // (release 32 R8) a YouTube recording neither source holds is recorded + // `none-found` in its copy-attempts.json, as the scope mode records one. + recordAttempt: (videoDir: string, attempt: CopyAttempt) => Promise<void>; + now: () => Date; }; const DEFAULT_DEPS: FindCopyDeps = { @@ -365,6 +378,8 @@ const DEFAULT_DEPS: FindCopyDeps = { missing: (paths, host) => missingEvidenceWindows(paths, host), facts: recordFacts, failedCopies: readFailedCopies, + recordAttempt: recordCopyAttempt, + now: () => new Date(), }; const describeAttempt = (t: FindCopyAttempt) => @@ -411,7 +426,8 @@ export async function lookForCopy(o: { out.tried.push({ from: "wayback", found: false, detail: "a fetch from its Wayback copy failed before" }); } else { try { - if (await deps.wayback.youtubeVideoArchived(youtubeId, sig)) { + const video = await deps.wayback.youtubeVideoStream(youtubeId, sig); + if (video.stream) { // The newest capture of the page that recorded a 200 dates the copy. const { captures } = await waybackLookup(`https://www.youtube.com/watch?v=${youtubeId}`, { client: deps.wayback, @@ -422,7 +438,14 @@ export async function lookForCopy(o: { const url = waybackYoutubeUrl(youtubeId, newest?.timestamp); out.copy = { from: "wayback", url }; if (newest) out.captureTs = newest.timestamp; - out.tried.push({ from: "wayback", found: true, url, detail: `the video is archived${newest ? `; its page captured ${newest.timestamp}` : ""}` }); + out.tried.push({ from: "wayback", found: true, url, detail: `the video is archived and its stream answers${newest ? `; its page captured ${newest.timestamp}` : ""}` }); + } else if (video.formats > 0) { + const statuses = [...new Set(video.probes.map((p) => p.status))].join(", "); + out.tried.push({ + from: "wayback", + found: false, + detail: `${WAYBACK_PAGE_ONLY} (the video index lists ${video.formats} format(s); ${video.probes.length} probed, HTTP ${statuses})`, + }); } else { out.tried.push({ from: "wayback", found: false, detail: "the video is not archived (its page may be)" }); } @@ -473,6 +496,8 @@ export async function findCopies(opts: { // Try copies recorded as failed again (they are still listed, as // `failedBefore`): for a failure later found to be ours, not the copy's. retryFailed?: boolean; + // Nothing recorded (runFindCopy's dry run). + dryRun?: boolean; signal?: AbortSignal; onLog?: (line: string) => void; deps?: Partial<FindCopyDeps>; @@ -521,6 +546,10 @@ export async function findCopies(opts: { } } else if (rec.tried.some((t) => t.error)) { rec.outcome = "error"; + } else if (youtubeId && !opts.dryRun) { + await deps + .recordAttempt(facts.videoDir, { at: deps.now().toISOString(), outcome: "none-found", detail: rec.tried.map(describeAttempt).join("; ") }) + .catch((e: unknown) => log(` ${r.slug}/${r.id}: copy-attempts.json not written (${(e as Error).message}).`)); } log( ` ${r.slug}/${r.id} (${r.gone}, ${r.windows.length} window(s)): ` + diff --git a/common/publish/findCopyScope.test.ts b/common/publish/findCopyScope.test.ts @@ -181,6 +181,32 @@ test("a run: none-found recorded (and then left out), ONE fetch of every copy fo } }); +test("(R8) a Wayback video whose stream does not answer is none-found, recorded 'page captured, no video' — not a copy, not failed at its source", async () => { + const c = await corpus(); + const wb = await startFakeWayback({ videos: [WB], streams: [] }); + const ia = await startFakeArchiveOrg({ items: [] }); + try { + const deps = { + wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }), + archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }), + now: () => NOW, + }; + let started = 0; + const r = await runFindWholeCopies({ paths: c.paths, scope: { slug: "alpha" }, gone: "no-transcript", deps, startFetch: async () => void started++ }); + const rec = r.looked.find((x) => x.id === WB); + assert.equal(rec?.outcome, "none-found"); + assert.equal(started, 0, "nothing found: no fetch-copies"); + const got = await loadCopyAttempts(path.join(c.alpha, "data", WB)); + assert.deepEqual(got?.failed, []); + assert.equal(got?.attempts?.[0]?.outcome, "none-found"); + assert.match(got?.attempts?.[0]?.detail ?? "", /wayback none — page captured, no video/); + } finally { + await wb.close(); + await ia.close(); + await c.close(); + } +}); + test("archive.org refusing stops the run there; a cancelled run starts no fetch", async () => { const c = await corpus(); const wb = await startFakeWayback({ videos: [] }); diff --git a/common/testing/README.md b/common/testing/README.md @@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever. | `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. | | `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. | | `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. | -| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. | +| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | | `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. | | `mirrors/mirrorCorpus.mjs` | Release 31 lane D: a synthetic creator (`synth-streamer`, "youtube": a public, a deleted and a private stream, removed shorts in and out of the window), its Rumble twin (`synth-streamer-rumble`: data dirs are URL slugs, ids embed ids) and a VOD mirror (`synth-vod-archive`, "odysee", titles `[VOD] SynthStreamer - MM/DD/YYYY - <topic>`, config `recordedDate` + `mirror.of`). `MIRROR_RECORDS` / `CREATOR_RECORDS` / `RUMBLE_RECORDS` are the matcher's input; `writeMirrorCorpus(channelsDir)` writes the three channels to disk (config, metadata, availability); `EXPECTED` is what a mirror scan finds (each status once or more, the removed uploads the mirror holds). | diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -10,4 +10,12 @@ export type FakeWayback = { close(): Promise<void>; }; -export function startFakeWayback(opts?: { captures?: FakeWaybackCapture[]; videos?: string[]; busyTimes?: number; downTimes?: number }): Promise<FakeWayback>; +export function startFakeWayback(opts?: { + captures?: FakeWaybackCapture[]; + videos?: string[]; + // (release 32 R8) ids whose format stream answers (default: videos). + streams?: string[]; + busyTimes?: number; + downTimes?: number; + streamBusyTimes?: number; +}): Promise<FakeWayback>; diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -18,7 +18,12 @@ // YoutubeWebArchive extractor asks: `{formats: [...]}` for an id in // opts.videos (default VIDEOS), `{}` for any other — the video itself // archived, not only its watch page +// GET /web/<ts>id_/<format url> (release 32 R8) a format's STREAM, as yt-dlp fetches it +// (`/web/2id_/<url>`): fake bytes (a Range is answered 206) when the format's `id` +// is in opts.streams (default: opts.videos), 404 otherwise — an id in `videos` but +// not in `streams` is the live case, the index listing a video Wayback does not hold // opts.busyTimes: the first N CDX requests answer 429 (Retry-After: 1); opts.downTimes: then 503s. +// opts.streamBusyTimes: the first N stream requests answer 429 (Retry-After: 1). import http from "node:http"; @@ -47,6 +52,8 @@ export const VIDEOS = ["gone-video-05"]; export async function startFakeWayback(opts = {}) { const captures = opts.captures ?? CAPTURES; const videos = opts.videos ?? VIDEOS; + const streams = opts.streams ?? videos; + let streamBusy = opts.streamBusyTimes ?? 0; const requests = []; let busy = opts.busyTimes ?? 0; let down = opts.downTimes ?? 0; @@ -86,6 +93,21 @@ export async function startFakeWayback(opts = {}) { : {}; return send(200, "application/json", JSON.stringify(body)); } + const st = /^\/web\/\d{1,14}id_\/(https?:\/\/[^/]*googlevideo\.com\/.+)$/.exec(u.pathname + u.search); + if (st) { + if (streamBusy > 0) { + streamBusy--; + return send(429, "text/plain", "Too Many Requests", { "retry-after": "1" }); + } + const id = new URL(st[1]).searchParams.get("id") ?? ""; + if (!streams.includes(id)) return send(404, "text/html", "<p>Wayback Machine has not archived that URL.</p>"); + const body = Buffer.alloc(4096, 7); + const range = /^bytes=(\d+)-(\d*)$/.exec(String(req.headers.range ?? "")); + if (!range) return send(200, "video/mp4", body); + const from = Number(range[1]); + const to = Math.min(body.length - 1, range[2] ? Number(range[2]) : body.length - 1); + return send(206, "video/mp4", body.subarray(from, to + 1), { "content-range": `bytes ${from}-${to}/${body.length}` }); + } const m = /^\/web\/(\d{14})(?:id_|if_)?\/(.+)$/.exec(u.pathname + u.search); if (m) { const c = captures.find((x) => x.timestamp === m[1] && x.original === m[2]); diff --git a/common/views/pipeline/channelFlow.test.ts b/common/views/pipeline/channelFlow.test.ts @@ -337,3 +337,21 @@ test("every optional snapshot field survives being absent", () => { for (const sd of g.sidings) assert.ok(Number.isFinite(sd.count)); } }); + +// Release 32 R8: the full-audio state in the flow — corrupt full sources still +// owed a stored-URL download, and the salvaged siding's attempts. +test("the flow says which corrupt full sources await full audio, and the salvaged siding's attempts", () => { + const buckets = { ...normalizeBuckets(undefined), corruptFullSource: ["a", "b", "c"], salvagedTranscript: ["c"] }; + const flow = flowOf( + snapshotOf({ buckets, fullAudio: { of: 2, attempts: { a: 0, b: 1, c: 2 }, awaiting: ["a", "b"] } }), + ); + const all = flow.gaps.flatMap((g) => g.sidings); + const awaiting = all.find((s) => s.label === "awaiting full audio"); + assert.equal(awaiting?.count, 2); + assert.match(awaiting?.hint ?? "", /tried 2 times before a salvage transcript is made; full audio attempts so far: 0–1 of 2/); + assert.equal(all.find((s) => s.label.startsWith("salvaged"))?.label, "salvaged — full audio attempts: 2"); + // Without the snapshot's fullAudio (another platform), the old label. + const plain = flowOf(snapshotOf({ buckets })).gaps.flatMap((g) => g.sidings); + assert.ok(plain.some((s) => s.label === "salvaged transcript")); + assert.ok(!plain.some((s) => s.label === "awaiting full audio")); +}); diff --git a/common/views/pipeline/channelFlow.ts b/common/views/pipeline/channelFlow.ts @@ -164,6 +164,29 @@ function ratio(through: number | null, denominator: number | null): number | nul return Math.min(1, through / denominator); } +// THE FULL-AUDIO STATE IN THE FLOW (release 32 R8). The salvaged siding reads +// "salvaged — full audio attempts: n" on a channel that tries the stored media +// URL first (the snapshot's `fullAudio`); n is a range when the videos differ. +type FullAudioSnapshot = ChannelSnapshot["fullAudio"]; + +function attemptsRange(fullAudio: FullAudioSnapshot, ids: readonly string[]): string | null { + const ns = ids.map((id) => fullAudio?.attempts[id]).filter((n): n is number => n !== undefined); + if (ns.length === 0) return null; + const lo = Math.min(...ns); + const hi = Math.max(...ns); + return lo === hi ? `${lo}` : `${lo}–${hi}`; +} + +export function salvagedLabel(fullAudio: FullAudioSnapshot, salvaged: readonly string[]): string { + const n = attemptsRange(fullAudio, salvaged); + return n === null ? "salvaged transcript" : `salvaged — full audio attempts: ${n}`; +} + +function attemptsSummary(fullAudio: FullAudioSnapshot, ids: readonly string[]): string { + const n = attemptsRange(fullAudio, ids); + return `full audio attempts so far: ${n ?? "0"} of ${fullAudio?.of ?? 0}`; +} + function siding( label: string, count: number, @@ -233,6 +256,7 @@ export function computeChannelFlow( const totals = snapshot.totals ?? { videos: 0, transcribed: 0, downloaded: 0 }; const undownloadedIds = snapshot.undownloadedIds ?? []; const excluded = snapshot.excludedFromDownload; + const fullAudio = snapshot.fullAudio; const excludedIds = excludedDownloadIdSet(snapshot); const actionableDownloadedNoTranscript = buckets.downloadedNoTranscript.filter( (id) => !excludedIds.has(id), @@ -450,6 +474,15 @@ export function computeChannelFlow( "download", "The audio audit found part of the held file will not decode; it is kept. A retry downloads again with the audio check.", ), + // Release 32 R8: corrupt full sources still owed a stored-URL download + // before any salvage transcript (lib/fullAudioFirst.ts). + ...siding( + "awaiting full audio", + fullAudio?.awaiting.length ?? 0, + "download", + `Corrupt full sources whose stored media URL is tried ${fullAudio?.of ?? 0} times before a salvage transcript is made; ` + + `${attemptsSummary(fullAudio, fullAudio?.awaiting ?? [])}. A retry or Transcribe downloads the next one.`, + ), ], transcribe: [ ...siding("failed", failedVideoIds.length, "transcribe"), @@ -466,10 +499,10 @@ export function computeChannelFlow( "The transcript covers a fraction of the runtime — the audio download truncated silently.", ), ...siding( - "salvaged transcript", + salvagedLabel(fullAudio, buckets.salvagedTranscript), buckets.salvagedTranscript.length, "transcribe", - "Transcribed from a damaged file: the parts that would not decode are gaps. A retry of the corrupt full source can bring a clean copy.", + "Transcribed from a damaged file: the parts that would not decode are gaps, and the transcript is marked partial wherever it shows. A retry of the corrupt full source can bring a clean copy.", ), ...siding( "short audio", diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -114,6 +114,7 @@ import { type StoredUrlWhy, } from "../lib/storedMediaUrl"; import { storedMediaUrl } from "../lib/storedMediaUrl-server"; +import { fullAudioLine, fullAudioState } from "../lib/fullAudioFirst"; import type { DownloadFailureClass } from "../lib/availability"; import { platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; import { noteStoredUrlRead } from "../jobs/storedUrlPace"; @@ -750,6 +751,28 @@ export async function downloadOneManaged( }, }; } + // FULL AUDIO FIRST (operator ruling 2026-10-17, release 32 R8): the refetch + // of a corrupt full source whose record stores a trusted media URL reads + // that URL (R7's ranged reader, its audio check and its gap) until + // FULL_AUDIO_ATTEMPTS such downloads are on record — unless the request or + // the channel names a stored-URL mode of its own (lib/fullAudioFirst.ts). + if ( + refetch?.trigger === "corrupt-full-source" && + canonicalId && + opts.storedUrl === undefined && + opts.channelConfig.storedUrlDownloads === undefined + ) { + const state = fullAudioState(refetch.previous, { + storedUrlTrusted: (await storedMediaUrl(path.join(channelDir, "data", canonicalId))) !== null, + ...(opts.channelConfig.handling ? { handling: opts.channelConfig.handling } : {}), + }); + if (state && !state.exhausted) { + opts.onLog( + `Full audio first (${fullAudioLine(state)}): this refetch reads the stored media URL before any salvage transcript.\n`, + ); + opts = { ...opts, storedUrl: "only" }; + } + } let outcome = await runManagedDownload(opts, channelDir, startedAt, canonicalId); if (refetch) outcome = await settleCorruptRefetch(refetch, outcome, refetchCtx); await recordWaybackProvenance(opts, channelDir, canonicalId); diff --git a/common/ytdlp/storedUrlManaged.test.ts b/common/ytdlp/storedUrlManaged.test.ts @@ -308,3 +308,80 @@ test("the managed download opens the player's page (the injected opener) and rec await done(f); } }); + +// Release 32 R8 — FULL AUDIO BEFORE A SALVAGE: a corrupt full source's refetch +// reads the stored URL by itself (no storedUrl asked, none on the channel) +// until FULL_AUDIO_ATTEMPTS stored-URL downloads are on record; then the page, +// as before. An explicit mode (request or channel) is left alone. +async function corruptPrevious(f: Fixture, storedAttempts: number): Promise<void> { + await writeFile(path.join(f.videoDir, "audio.mp4"), "OLD-MALFORMED"); + const previous: DownloadOutcomeRecord = { + videoId: CLAIM, + webpageUrl: PAGE, + status: "corrupt-full-source", + startedAt: "2026-10-15T00:00:00.000Z", + finishedAt: "2026-10-15T01:00:00.000Z", + attempts: [ + { n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, + ...Array.from({ length: storedAttempts }, () => ({ n: 1, kind: "stored-url-ranged" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 1 })), + ], + }; + await writeFile(path.join(f.videoDir, "download-outcome.json"), JSON.stringify(previous)); +} + +test("full audio first: a corrupt full source's refetch reads the stored URL by itself while attempts are owed", { skip: !FF }, async () => { + const f = await fixture(); + try { + await corruptPrevious(f, 0); + const log = { s: "" }; + const record = await run(f, { corruptRefetchDeps: { measure: async () => null } }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.deepEqual(await ytdlpCalls(f), [], "no page request"); + assert.match(log.s, /Full audio first \(full audio attempts: 0 of 2\): this refetch reads the stored media URL/); + assert.equal(storedUrlAttemptOf(record)?.why, "only"); + } finally { + await done(f); + } +}); + +test("full audio first: a refused attempt is counted on the corrupt record; once the attempts are made the refetch asks the page", { skip: !FF }, async () => { + const f = await fixture({ cdn: { refuseAfterBytes: 0 } }); + try { + await corruptPrevious(f, 1); + const record = await run(f, { corruptRefetchDeps: { measure: async () => null } }); + assert.equal(record.status, "failed"); + const disk = await readOutcome(f.videoDir); + assert.equal(disk.status, "corrupt-full-source", "the bucket stays"); + assert.equal(disk.attempts.filter((a) => a.kind === "stored-url-ranged").length, 2, "the attempt is on record"); + assert.deepEqual(await ytdlpCalls(f), []); + // Two on record: the next refetch is the page's, as before R8. + const cdnBefore = f.cdn.requests.length; + await run(f, { corruptRefetchDeps: { measure: async () => null } }); + assert.ok((await ytdlpCalls(f)).length > 0, "the page is asked"); + assert.equal(f.cdn.requests.length, cdnBefore, "the stored URL is not read again"); + } finally { + await done(f); + } +}); + +test("full audio first: an explicit mode (the request's never, the channel's) is left alone", { skip: !FF }, async () => { + const f = await fixture(); + try { + await corruptPrevious(f, 0); + await run(f, { storedUrl: "never", corruptRefetchDeps: { measure: async () => null } }); + assert.ok((await ytdlpCalls(f)).length > 0, "never: the page"); + assert.equal(f.cdn.requests.length, 0); + } finally { + await done(f); + } + const g = await fixture(); + try { + await corruptPrevious(g, 0); + const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "never" } as ChannelConfig; + await run(g, { channelConfig: cfg, corruptRefetchDeps: { measure: async () => null } }); + assert.ok((await ytdlpCalls(g)).length > 0, "the channel's never: the page"); + assert.equal(g.cdn.requests.length, 0); + } finally { + await done(g); + } +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **Partial transcripts wait for the full audio first.** A video whose download completed with malformed audio (a corrupt full source) used to get a salvage transcript, with gaps, as soon as anyone pressed Transcribe. When the video's record stores an Odysee media URL, Transcribe and the corrupt full sources' Retry now download from that URL first, up to two times and 20 minutes apart. The salvage transcript is made only if neither download comes back clean. A clean download is transcribed in full. **Salvage** (`transcribe-one {"salvage": true}`) still makes the partial transcript at once. The channel's line shows **awaiting full audio** for the videos still waiting, and the salvaged transcripts read **salvaged — full audio attempts: n**. The video page's salvaged notice gives the same count, the video list marks a salvaged transcript amber, and the MCP's `get_transcripts` marks it partial as `get_transcript` already did. +- **find-copy no longer reports a Wayback copy that has no video.** The Wayback Machine's video index can list a video whose file it does not hold, and such a copy then failed to fetch (404). A copy now counts as found only when one of its video files answers a request for its first bytes. Otherwise the lookup says **page captured, no video**, archive.org is tried next, and the video is recorded as none found, not as a copy that failed. Looking up copies for an article's cited windows now records none found too, as the channel and site lookup already did. +- **The verdict bench shows the model what you read, and rules each part of a claim.** A claim's cited posts and pages now go to the model beside the transcript, quoted with who posted them and when. A section heading that names a verdict is no longer shown to the model. A claim that repeats an earlier one (the same words over the same clips, as in a re-cut report) is still asked each time; `--dedupe` (the body's `"dedupe": true`) asks it once instead. The model no longer picks a verdict. It lists the claim's parts and says of each whether the evidence shows it, shows it wrong, or does not show it, and the verdict follows from those answers: every part shown is CORROBORATED, some shown and some not is PARTLY, nothing shown but a part shown wrong is CONTRADICTED, nothing shown is NOT_FOUND. What each verdict means (REPORT.md, the bench page) now says this. A part the evidence does not show makes a claim PARTLY again, as your rulings do. Proposed verdicts use the same rule. umtool's `/tools/bench` shows under each claim what the model saw (its transcript lines, its posts and pages), and under each answer its parts. This is prompt version 3. Needs a restart of the editor and umtool. - **An Odysee record can be read from its page in a browser when Odysee refuses yt-dlp.** The video page of an Odysee channel has **Read from the page**: it opens the video's Odysee page in a headless browser (which Odysee answers when it answers yt-dlp with 429), reads the record from what the page itself loads, and writes `metadata.info.json` — or, when there is one, adds only what it lacks and the media file the page's player asked for, so a stored-URL download can then read it. The record says `_source: "browser"`, and the change is in the metadata history. The channel's Playlist stage has **List from the page** (the uploads the channel page shows, scrolled as many times as you say, added to the top of the playlist — nothing removed, nothing downloaded) and **Read records from their pages** (a list of ids). A channel's Configure form has **Browser lookup**: with **Stored media URL downloads** set, a video whose record names no media file is looked up this way first and then downloaded. The channel's `--match-filter title~='…'` and download filters still decide what is listed and downloaded. One page a minute; Odysee only. `pnpm ops browser-lookup --json '{"slug":"<channel>","ids":["<claim id>"]}'` or `'{"slug":"<channel>","listing":true}'`. Needs a restart of the editor. - **The download lane takes an Odysee channel's held videos from their stored media URLs.** With **Stored media URL downloads** on (fallback or only), when Odysee is cooling down or held the lane still downloads that channel's videos whose record stores the media file — one new file per 20 minutes, without asking Odysee anything and without counting as Odysee answering. A refusal from the file's server defers the video; Odysee's own backoff is not touched. Needs a restart of the editor. - **Clip windows cut from Odysee's stored media URL open the video's page first, and wait their turn with full downloads.** Odysee's file server serves a video only once its player has opened the page, so **Fetch windows** with the stored media URL opens each video's page in a headless browser before its first window (again if the server refuses after a window came down), and a window of a new video waits out the same 20-minute rest a full download does — a second window of the same video does not. The window's provenance counts the page opens. Needs a restart of the editor. diff --git a/editor/app/api/ops/_benchVerdicts.test.ts b/editor/app/api/ops/_benchVerdicts.test.ts @@ -79,11 +79,15 @@ test("the body: models required, the run id and reports checked, numbers as numb assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28" }), { models: ["q"], itemsFrom: "vb-r28" }); assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "../x" }), /"itemsFrom" is a run id/); assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28", window: 30 }), /drop the window/); + // Release 32 R8: dedupe is a boolean, off unless asked, never with items-from. + assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], dedupe: true }), { models: ["q"], dedupe: true }); + assert.throws(() => parseBenchVerdictsBody({ models: ["q"], dedupe: "yes" }), /"dedupe" is true or false/); + assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28", dedupe: true }), /drop the dedupe/); }); test("an API and a local model: a bench-verdicts job on draft:local, every answer on disk, the API spend in the ledger, ollama unloaded", async () => { - for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "she says so" })); - for (let i = 0; i < 7; i++) ol.push(jsonReply({ verdict: "NOT_FOUND", reason: "not in the window" })); + for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { parts: [{ part: "she said it", finding: "shown" }], checkable: true, reason: "she says so" })); + for (let i = 0; i < 7; i++) ol.push(jsonReply({ parts: [{ part: "she said it", finding: "not shown" }], checkable: true, reason: "not in the window" })); const out = await enqueueVerdictBench({ models: ["claude-sonnet-5-5", "qwen3:8b"], run: "vb-editor" }, deps()); assert.ok(out.result.ok && "run" in out, (out.result as { error?: string }).error); assert.equal(out.run, "vb-editor"); @@ -110,7 +114,7 @@ test("an API and a local model: a bench-verdicts job on draft:local, every answe }); test("API models only run on draft:api; past the day's cap an API run is refused, a local one is not", async () => { - api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "ok" })); + api.push(toolTurn("answer", { parts: [{ part: "it", finding: "shown" }], checkable: true, reason: "ok" })); const one = await enqueueVerdictBench({ models: ["claude-haiku-4-5"], run: "vb-api", limit: 1 }, deps()); assert.ok(one.result.ok && "run" in one); assert.equal(getRegistry().get(one.result.jobId)!.queueKey, "draft:api"); @@ -122,7 +126,7 @@ test("API models only run on draft:api; past the day's cap an API run is refused const refused = await enqueueVerdictBench({ models: ["claude-sonnet-5-5"], run: "vb-late" }, deps()); assert.equal(refused.result.ok, false); assert.match((refused.result as { error: string }).error, /daily cap/); - ol.push(jsonReply({ verdict: "CORROBORATED", reason: "ok" })); + ol.push(jsonReply({ parts: [{ part: "it", finding: "shown" }], checkable: true, reason: "ok" })); const local = await enqueueVerdictBench({ models: ["qwen3:8b"], run: "vb-local", limit: 1 }, deps()); assert.ok(local.result.ok && "run" in local); void local.result.stream.cancel(); diff --git a/editor/app/api/ops/_verdicts.test.ts b/editor/app/api/ops/_verdicts.test.ts @@ -80,7 +80,7 @@ test("refused until a model clears the bar; then a report-draft job on draft:loc assert.match((unlisted.result as { error: string }).error, /has not cleared the verdict bench's bar/); const before = await readFile(articleFile(paths, id), "utf8"); - for (let i = 0; i < 3; i++) ol.push(jsonReply({ reason: "the window shows the opposite", verdict: "CONTRADICTED" })); + for (let i = 0; i < 3; i++) ol.push(jsonReply({ parts: [{ part: "what she said", finding: "shown wrong" }], checkable: true, reason: "the window shows the opposite" })); const out = await enqueueReportDraft({ task: "verdicts", article: id }, deps({ verdicts: { ...gen.verdicts, models: ["qwen3:8b"], window: { mode: "turn", seconds: 30 } } })); assert.ok(out.result.ok, (out.result as { error?: string }).error); assert.equal("iteration" in out ? out.iteration : null, 0); diff --git a/editor/app/api/ops/bench-verdicts/route.ts b/editor/app/api/ops/bench-verdicts/route.ts @@ -5,7 +5,7 @@ import { jobResponse, ops } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { models, run?, reports?, window?, windowMode?, maxUsd?, limit?, itemsFrom? } +// POST { models, run?, reports?, window?, windowMode?, maxUsd?, limit?, itemsFrom?, dedupe? } // -> { ok: true, jobId, run } // // The verdict bench (release 28 M7), as a `bench-verdicts` job: every ruled @@ -17,7 +17,8 @@ export const dynamic = "force-dynamic"; // names a run to continue (its answered pairs are skipped). The results are // local-only: `.generation/bench/verdicts/<run>/` (umtool's /bench reads // them). Release 29 V1: `windowMode` ("turn": the cited speaker's turn), -// a stratified `limit`, `itemsFrom` (an earlier run's exact items). +// a stratified `limit`, `itemsFrom` (an earlier run's exact items). Release 32 +// R8: `dedupe: true` asks a repeated claim once (off by default). // `job cancel` stops it; the log ends `@@bench-verdicts {json}`. // // AN ADAPTER: the refusals are the controller's (controller/benchVerdicts.ts). diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts @@ -21,7 +21,9 @@ export const dynamic = "force-dynamic"; // "salvage" (release 30, lane Q): true decodes the audio with error tolerance // and transcribes what decodes, its gaps recorded (transcribeOne's salvage); // false forbids it; absent, a corrupt-full-source video is salvaged and any -// other is not. +// other is not — release 32 R8: once its full audio was tried (a record that +// stores a trusted media URL is downloaded from it FULL_AUDIO_ATTEMPTS times +// first; controller/fullAudioFirst.ts). // "storedUrl" (release 32 R7): "never" | "fallback" | "only" — with no audio on // disk, the download reads the media URL the record stores, the way the // platform's player does (the managed path: the audio check, the outcome diff --git a/editor/app/channels/[slug]/components/VideoListPane.tsx b/editor/app/channels/[slug]/components/VideoListPane.tsx @@ -863,7 +863,7 @@ function StatusGlyphs({ row }: { row: VideoRow }) { : "bg-muted"; const trColor = row.untranscribable ? "bg-muted-foreground" - : row.incompleteTranscript + : row.incompleteTranscript || row.salvagedTranscript ? "bg-warning" : row.transcribed ? "bg-success" @@ -890,7 +890,9 @@ function StatusGlyphs({ row }: { row: VideoRow }) { title={ row.incompleteTranscript ? "transcript truncated (covers a fraction of the video — re-download)" - : "transcribed" + : row.salvagedTranscript + ? "salvaged transcript (partial — the parts of the audio that would not decode are gaps)" + : "transcribed" } className={`w-2 h-2 rounded-full ${trColor}`} /> diff --git a/editor/app/channels/[slug]/lib/videoRows.ts b/editor/app/channels/[slug]/lib/videoRows.ts @@ -33,6 +33,9 @@ export type VideoRow = { // (snapshot `corruptHeldAudio` minus its salvage transcripts — release 31, // lane A). Kept on disk; a retry refetches it. corruptHeldAudio?: boolean; + // The transcript is a SALVAGE (snapshot `salvagedTranscript`, release 30 + // lane Q): partial, marked as such (release 32 R8). + salvagedTranscript?: boolean; failedTranscription: boolean; // Has at least one finalized audio file not in the channel's target format — // the failed-extract orphans (audio.m4a with no audio.mp3) plus dirs with the diff --git a/editor/app/channels/[slug]/lib/videoRowsServer.ts b/editor/app/channels/[slug]/lib/videoRowsServer.ts @@ -112,6 +112,7 @@ export function computeVideoRows(input: ComputeRowsInput): VideoRow[] { corruptSource: isCorruptSource, corruptFullSource: isCorruptFullSource, ...(isCorruptHeldAudio ? { corruptHeldAudio: true } : {}), + ...(salvagedSet.has(id) ? { salvagedTranscript: true } : {}), failedTranscription: isFailedT, wrongFormatAudio: wrongFormatAudio.has(id) || multipleAudioFormats.has(id), diff --git a/editor/app/channels/[slug]/videos/[id]/components/SalvagedTranscriptNotice.tsx b/editor/app/channels/[slug]/videos/[id]/components/SalvagedTranscriptNotice.tsx @@ -7,7 +7,15 @@ import { formatDuration } from "yt-dlp-transcript-common/lib/format"; const clock = (s: number) => formatDuration(s) || "0:00"; const MAX_LISTED = 8; -export function SalvagedTranscriptNotice({ salvaged }: { salvaged: TranscriptSalvage }) { +// `fullAudio`: the stored-URL download attempts made before the salvage +// (release 32 R8, lib/fullAudioFirst.ts), when the record stores one. +export function SalvagedTranscriptNotice({ + salvaged, + fullAudio, +}: { + salvaged: TranscriptSalvage; + fullAudio?: { attempts: number; of: number } | null; +}) { const listed = salvaged.gaps.slice(0, MAX_LISTED); const more = salvaged.gaps.length - listed.length; return ( @@ -26,6 +34,7 @@ export function SalvagedTranscriptNotice({ salvaged }: { salvaged: TranscriptSal {more > 0 ? ` and ${more} more` : ""}. </> )} + {fullAudio && <> Full audio attempts: {fullAudio.attempts} of {fullAudio.of}.</>} </div> ); } diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -8,6 +8,7 @@ // The registry-driven operation panels (digest, diarization, attribution) render // after this component, in page.tsx. +import { FULL_AUDIO_ATTEMPTS, fullAudioAttemptsOf, fullAudioState } from "yt-dlp-transcript-common/lib/fullAudioFirst"; import type { AudioFormat, ChannelHandling, @@ -163,6 +164,17 @@ export function VideoPanel({ : "Audio not yet downloaded." : `${audioFiles.length} audio file${audioFiles.length === 1 ? "" : "s"} on disk.`; const salvageShown = hasTranscriptJson && salvaged !== null; + // Release 32 R8: a corrupt full source still owed its stored-URL downloads + // before a salvage (lib/fullAudioFirst.ts) — the Transcribe row says so and + // offers Salvage now. + const fullAudioGate = storedMediaHost + ? fullAudioState(downloadOutcome, { + storedUrlTrusted: true, + handling, + ...(channelStoredUrl ? { mode: channelStoredUrl } : {}), + }) + : null; + const fullAudioOwed = fullAudioGate && !fullAudioGate.exhausted ? fullAudioGate : null; const transcribeSummary = autoSubsOnly ? "YouTube auto-captions only — can be replaced with an AI transcript." : salvageShown @@ -207,7 +219,16 @@ export function VideoPanel({ downloadFailed={downloadFailed} /> {downloadOutcome && <DownloadOutcomeBadge outcome={downloadOutcome} />} - {salvageShown && salvaged && <SalvagedTranscriptNotice salvaged={salvaged} />} + {salvageShown && salvaged && ( + <SalvagedTranscriptNotice + salvaged={salvaged} + fullAudio={ + storedMediaHost && downloadOutcome + ? { attempts: fullAudioAttemptsOf(downloadOutcome), of: FULL_AUDIO_ATTEMPTS } + : null + } + /> + )} {/* BOTH BANNERS ARE RENDERED UNCONDITIONALLY, and each decides for itself whether to draw anything. THE RULE (plans/FACTS.md, fae99f1): a component carrying a StreamActionLog must not be UNMOUNTED when the @@ -335,6 +356,7 @@ export function VideoPanel({ existingQueues={existingQueues} hasTranscript={hasTranscript && !autoSubsOnly} replaceAutoSubs={autoSubsOnly} + fullAudio={fullAudioOwed} /> ))} </div> diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/PerFileTranscribeRow.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/PerFileTranscribeRow.tsx @@ -9,6 +9,7 @@ import { } from "../../videoActions"; import { Heading } from "./Heading"; import type { VideoFile } from "./videoFiles"; +import type { FullAudioState } from "yt-dlp-transcript-common/lib/fullAudioFirst"; export function PerFileTranscribeRow({ slug, @@ -17,6 +18,7 @@ export function PerFileTranscribeRow({ existingQueues, hasTranscript, replaceAutoSubs = false, + fullAudio = null, }: { slug: string; videoId: string; @@ -26,6 +28,10 @@ export function PerFileTranscribeRow({ // The existing transcript is YouTube ASR: transcribing is offered (and // labelled as a replacement) rather than blocked. replaceAutoSubs?: boolean; + // Release 32 R8: a corrupt full source still owed its stored-URL downloads + // (lib/fullAudioFirst.ts). Transcribe makes them first; Salvage now makes + // the partial transcript from this file at once. + fullAudio?: FullAudioState | null; }) { const [transcribeQueue, setTranscribeQueue] = useState(""); // `hasTranscript` is SERVER-derived (VideoPanel, the Transcribe card) and this row's own run @@ -59,6 +65,12 @@ export function PerFileTranscribeRow({ Transcribe disabled — transcript already present. </p> ) : null} + {fullAudio && !hasTranscript ? ( + <p role="status" aria-label="full audio first" className="text-sm text-warning"> + Full audio first: {fullAudio.attempts} of {fullAudio.of} downloads from the stored media URL made. Transcribe + downloads the rest first (20 minutes apart) and makes a partial transcript only if none comes back clean. + </p> + ) : null} {hasTranscript && !ranHere ? null : ( <StreamActionLog key="transcribe-run" @@ -91,6 +103,19 @@ export function PerFileTranscribeRow({ } /> )} + {fullAudio && !hasTranscript && ( + <StreamActionLog + key="salvage-run" + trigger={() => { + setRanHere(true); + return transcribeOneAction(slug, videoId, file.name, transcribeQueue, true); + }} + cancelAction={cancelJobAction} + buttonLabel={`Salvage now (${file.name})`} + runningLabel="Salvaging…" + label={`Salvage ${file.name}`} + /> + )} </div> ); } diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -64,6 +64,7 @@ import { transcriptionContainer, } from "yt-dlp-transcript-common/controller/transcribeOne"; import { findVideoSourceUrl } from "yt-dlp-transcript-common/controller/undownloadedVideos"; +import { fullAudioFirst } from "yt-dlp-transcript-common/controller/fullAudioFirst"; import { loadSavedVideo, unpersistSavedVideo, @@ -218,6 +219,9 @@ export async function transcribeOneAction( channelSlug: slug, videoId, fn: async (onLog, signal, _setProgress, ctx) => { + if (salvage === undefined) { + await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal }); + } await transcribeWithWorker({ paths, videoDir, @@ -306,6 +310,52 @@ export async function downloadVideoPipelineAction( }); } +// FULL AUDIO BEFORE A SALVAGE (operator ruling 2026-10-17, release 32 R8): +// a Transcribe that would salvage a corrupt full source whose record stores a +// trusted media URL first makes the stored-URL downloads still owed +// (controller/fullAudioFirst.ts) — the corrupt-source refetch, `storedUrl: +// "only"`. Nothing happens for any other video. `storedUrl` is the request's +// mode (an explicit "never" keeps the old behaviour), else the channel's. +async function fullAudioBeforeSalvage(o: { + slug: string; + videoId: string; + config: ChannelConfig; + paths: Paths; + onLog: (line: string) => void; + signal: AbortSignal; + storedUrl?: StoredUrlMode; +}): Promise<void> { + const videoDir = videoDirOf(o.slug, o.videoId); + const mode = o.storedUrl ?? o.config.storedUrlDownloads; + await fullAudioFirst({ + videoDir, + handling: o.config.handling, + ...(mode ? { mode } : {}), + onLog: o.onLog, + signal: o.signal, + download: async () => { + const url = await findVideoSourceUrl(o.paths, o.slug, o.videoId, o.config); + if (!url) throw new Error("Could not determine the video URL for the full-audio download."); + const settings = getSettings(); + const record = await downloadOneManaged({ + channelSlug: o.slug, + channelConfig: o.config, + paths: o.paths, + videoUrl: url, + onLog: o.onLog, + signal: o.signal, + cookiePolicy: resolveCookiePolicy(settings, o.config), + globalSkipLiveDownloads: settings.skipLiveDownloads, + audioFormatOverride: o.config.audioFormat ?? "mp3", + appendArchive: true, + storedUrl: "only", + }); + await recordStoredUrlBackoff(record, url, o.paths); + return record; + }, + }); +} + // A single-video download that read the stored media URL (release 32 R7) // backs the platform off on a refusal — its CDN's, or the page lookup's before // it — as a batch does. Best-effort. @@ -601,6 +651,9 @@ export async function whisperVideoAction( } } else { onLog(`Audio already on disk for ${videoId}; skipping download.`); + if (salvage === undefined) { + await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal, storedUrl }); + } } await transcribeWithWorker({ paths, diff --git a/editor/e2e/full-audio-first.spec.ts b/editor/e2e/full-audio-first.spec.ts @@ -0,0 +1,91 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { test, expect } from "@playwright/test"; +import { baseUrl } from "./baseUrl"; +import { generateReport, resetData, resolvePath, testPaths } from "./helpers"; + +// Release 32 R8, the operator's ruling of 2026-10-17: a partial transcript is +// marked, but the full audio comes first. A corrupt full source whose record +// stores a trusted media URL is downloaded from it FULL_AUDIO_ATTEMPTS times +// before a salvage transcript is made; the channel's line says which are still +// waiting ("awaiting full audio") and how many attempts the salvaged ones had +// ("salvaged — full audio attempts: n"), and the video page's salvaged +// transcript notice says the same. Nothing here starts a download: the stored +// URL's host is a real CDN and no test asks it anything (the downloads are +// covered by common's unit tests against a fake CDN). + +const CHANNEL = "test-transcribe"; +const FIXTURE = "one-transcribe-channel"; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; +const WAITING = "1111111111111111111111111111111111111111"; +const SALVAGED = "2222222222222222222222222222222222222222"; + +const stored = { n: 1, kind: "stored-url-ranged", handling: "transcribe", usedCookies: false, ytdlpExitCode: 1 }; + +async function video(id: string, storedAttempts: number, salvaged: boolean) { + const dir = resolvePath(`${ROOT}/data/${id}`); + await mkdir(dir, { recursive: true }); + const put = (name: string, body: unknown) => + writeFile(`${dir}/${name}`, typeof body === "string" ? body : JSON.stringify(body)); + await put("metadata.info.json", { + id, + extractor: "lbry", + title: `A synthetic stream ${id.slice(0, 4)}`, + webpage_url: `https://odysee.com/synthetic-stream:${id}`, + duration: 600, + formats: [{ url: `https://player.odycdn.com/v6/streams/${id}/a1b2c3.mp4`, protocol: "https", ext: "mp4" }], + }); + // The kept file in the channel's format (m4a), as the audio check keeps it. + await put("audio.m4a", "kept malformed bytes"); + await put("download-outcome.json", { + videoId: id, + status: "corrupt-full-source", + startedAt: "2026-10-16T00:00:00.000Z", + finishedAt: "2026-10-16T00:10:00.000Z", + attempts: [ + { n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, + ...Array.from({ length: storedAttempts }, () => stored), + ], + }); + if (salvaged) { + await put("transcript.json", { transcription: [{ offsets: { from: 0, to: 2000 }, text: " hello there" }] }); + await put("transcribe-outcome.json", { + videoId: id, + transcribedAt: "2026-10-16T01:00:00.000Z", + salvaged: { source: "audio.m4a", decodedSeconds: 300, totalSeconds: 600, gaps: [[300, 600]] }, + }); + } +} + +test("the line names the corrupt full sources awaiting full audio, and the salvaged ones' attempts; the video page says it too", async ({ page }) => { + await resetData(FIXTURE); + await video(WAITING, 0, false); + await video(SALVAGED, 1, true); + await writeFile( + resolvePath(`${ROOT}/playlist`), + [WAITING, SALVAGED].map((id) => `https://odysee.com/synthetic-stream:${id}`).join("\n") + "\n", + ); + await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); + await generateReport(page, CHANNEL); + await page.goto(`/channels/${CHANNEL}`); + + const line = page.getByLabel("channel line"); + await expect(line.getByLabel("awaiting full audio siding")).toContainText("1 awaiting full audio"); + await expect(line.getByLabel("salvaged — full audio attempts: 1 siding")).toContainText( + "1 salvaged — full audio attempts: 1", + ); + + await page.goto(`/channels/${CHANNEL}/videos/${SALVAGED}`); + const notice = page.getByRole("status", { name: "salvaged transcript" }); + await expect(notice).toContainText("Salvaged transcript — 5:00 of 10:00 of audio.m4a decoded."); + await expect(notice).toContainText("Full audio attempts: 1 of 2."); + + // The waiting one: Transcribe says the full audio comes first, and Salvage now + // is there for a person who wants the partial transcript at once (not pressed: + // nothing is transcribed here). + await page.goto(`/channels/${CHANNEL}/videos/${WAITING}`); + await expect(page.getByRole("status", { name: "full audio first" })).toContainText( + "Full audio first: 0 of 2 downloads from the stored media URL made.", + ); + await expect(page.getByRole("button", { name: "Salvage now (audio.m4a)" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Transcribe audio.m4a" })).toBeVisible(); +}); diff --git a/mcp/src/search.test.ts b/mcp/src/search.test.ts @@ -1790,5 +1790,13 @@ test("server: a salvage transcript is marked partial by get_transcript and get_v await client.callTool({ name: "get_transcript", arguments: { video_id: "b2" } }), ); assert.doesNotMatch(other, /PARTIAL TRANSCRIPT/); + // Release 32 R8: the batch reader marks it too — whole transcripts and windowed. + const batch = firstText(await client.callTool({ name: "get_transcripts", arguments: { video_ids: ["a1"] } })); + assert.match(batch, /Video ID: a1\n[\s\S]*PARTIAL TRANSCRIPT — made from a damaged recording: 39 of 100 min decoded/); + // Windowed (a query): the block's head carries it. + const windowed = firstText( + await client.callTool({ name: "get_transcripts", arguments: { video_ids: ["a1"], query: "coffee" } }), + ); + assert.match(windowed, /PARTIAL TRANSCRIPT — made from a damaged recording/); await client.close(); }); diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -2109,7 +2109,9 @@ async function handleGetTranscripts( (ch.siteTitle ? ` | site: ${ch.siteTitle}` : "") + ` | uploaded: ${formatDate(record.uploadDate)}` + (record.webpageUrl ? `\n- source: ${record.webpageUrl}` : "") + - (baseUrl ? `\n- moment_base: ${baseUrl}` : ""); + (baseUrl ? `\n- moment_base: ${baseUrl}` : "") + + // A salvage transcript (release 30, lane Q) is marked here too (release 32 R8). + (record.salvaged ? `\n- ${salvageCaveat(record.salvaged)}` : ""); if (matcher) { const { lines, matchCount } = getWindowedTranscript(record, matcher.match, { @@ -2164,6 +2166,9 @@ async function handleGetTranscripts( ].join("\n\n"); blocks.push(`${head}\n\n${body}`); } else { + // A salvage transcript (release 30, lane Q) is marked here too (release 32 R8). + const salvageMeta = record.salvaged ? [salvageCaveat(record.salvaged)] : []; + const extraMeta = [...(base && baseUrl ? [`moment_base: ${baseUrl}`] : []), ...salvageMeta]; const md = transcriptToMarkdown( record, base @@ -2171,12 +2176,13 @@ async function handleGetTranscripts( timestamps, includeTags: true, stampForCue: baseStamp, - extraMeta: baseUrl ? [`moment_base: ${baseUrl}`] : undefined, + extraMeta: extraMeta.length ? extraMeta : undefined, } : { timestamps, includeTags: true, linkForCue: (seconds) => momentLinkFor(source, link, seconds), + ...(extraMeta.length ? { extraMeta } : {}), }, ); blocks.push(md.trim()); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9496,6 +9496,37 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **The injected model** is `BenchDeps.ask(system, user, schema, model)` — no Meter, so an injected ask costs nothing in the run's spend. +## Release 30 lane V: the verdict bench, v3 (verified 2026-10-15, branch `r30/bench-v3`) + +- **The model names no verdict.** `VERDICT_ANSWER_SCHEMA` is `{parts: [{part, finding}], checkable, reason}` with + `finding` one of `PART_FINDINGS` (`shown`, `shown wrong`, `not shown`); `verdictOfParts` (`draft/bench/prompt.ts`) + derives the verdict in code: not checkable → UNTESTABLE; every part shown → CORROBORATED; no part shown and one + shown wrong → CONTRADICTED; none shown or wrong → NOT_FOUND; otherwise PARTLY. `readVerdictAnswer` is THE reader + of an answer (the bench's `run.ts` and M8's `tasks/verdicts.ts` both call it): parts cut at `PARTS_MAX` (6), a + part at `PART_MAX` (160), the reason at `REASON_MAX` (300); a checkable answer with no valid part is a parse + failure. A result stores `parts` (and `checkable: false` when untestable). `PROMPT_VERSION` is `"3"`. +- **The meanings are written in parts terms** and `VERDICT_TIE_RULE` is gone: `VERDICT_PARTS_RULE` + (`verdicts.mjs`) says what a part is (a separate thing said or done; a describing word and a fact about the world + outside what was said are not parts; a how-often / never part is shown when the evidence is consistent with it). + REPORT.md, the bench prompt and umtool read it. +- **An item's `evidence`** (`items.ts` `BenchEvidence`): the claim's `post` and `page` citations — quote (cut at + `EVIDENCE_QUOTE_MAX` 600), label, speaker, date, a post's channel, a page's title; never a page's `note`. At most + `EVIDENCE_MAX` (8); more are `dropped`. A `source` citation is still dropped ("not a video, audio, post or page + citation"). A claim still needs a span citation to be an item. The prompt quotes them under "Cited posts and + pages:". `benchItemsHash` adds the evidence only when an item has some (a pre-v3 item hashes as before). +- **A heading naming a verdict is withheld** (`sectionNamesVerdict`: a verdict code or default label, or + corroborat / contradict / partially / partly / untestable, case-insensitive) — `item.section` is absent. +- **`benchItemsOf` can dedupe** (`dedupe: true`; **default OFF — operator ruling 2026-10-17**, release 32 R8): a + claim with the same text over the same cited spans as an earlier item (report id order) is skipped `"the same claim + as <key>"` (`SAME_CLAIM_REASON`). Over the registry at 2026-10-15 that is 73 of 147 claims (the two fact-checks + repeat each other). A fresh bench asks every claim (147 there); dedupe is the explicit option `--dedupe` / the + `bench-verdicts` body's `dedupe: true`, recorded as the run summary's `dedupe: true`; a continuation must agree, and + it never goes with `itemsFrom`. **The meanings reversal is ruled (2026-10-17): kept** — a claim with a part the + evidence does not show is PARTLY. +- **umtool `/tools/bench`**: each item row carries `windows` (span, bound, cues) and `evidence`, shown as + `details[data-seen]` "what the model saw" (`[data-evidence]`, `[data-window]`); each answer its `parts` + (`[data-part-finding]`). + ## Release 29 lane A: Bluesky capture, the gone reading, `sourceGone`, find-copy (verified 2026-10-15, branch `r29/evidence`) - **Bluesky captures with no login** (`common/social/blueskyPostCapture.ts`, `blueskyFetcher.captureByIds`): liveness @@ -9529,7 +9560,8 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **The Wayback CDX client** (`lib/waybackClient.ts`) is an `ArchiveOrgClient` instance of its own (gap, UA, back-off); `parseCdxJson` reads the header row's columns, and `[]`, an empty body or a header alone are none. - **find-copy's copies** (`publish/findCopy.ts`, a `find-copy` job): YouTube pages only; Wayback when - `__wb/videoinfo?vtype=youtube&vid=<id>` has formats (yt-dlp's own check), URL + `__wb/videoinfo?vtype=youtube&vid=<id>` has formats (yt-dlp's own check) AND (release 32 R8) a format's stream + answers a ranged GET (`WaybackClient.youtubeVideoStream`; else "page captured, no video", none found), URL `https://web.archive.org/web/<ts>/https://www.youtube.com/watch?v=<id>`; else an archive.org item whose identifier, a file name or `originalurl`/`source` names the id, its file within 5 s / 2 % of the record's `duration`. A copy whose fetch failed is in `data/<id>/copy-attempts.json` (`lib/copyAttempts-server.ts`, written by @@ -9744,7 +9776,8 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **A YouTube record can now carry `archiveorg.json` without being archive.org's.** `refreshArchiveOrgRecords` skips a record whose metadata is not archive.org's (`isArchiveOrgRecordInfo`: extractor `ArchiveOrg` or an archive.org page). A `wayback.json` on the original makes compose cite it as "Original (may be gone)" + the Wayback copy - (`waybackCitationLinks`), and hides the video page's Refresh metadata (as for any copy). + (`waybackCitationLinks`), and hides the video page's Refresh metadata (as for any copy). **Ruled 2026-10-17: such a + Wayback-only citation is OK on public sites** (no code change). - **The transcription lane takes the audio as is**: a gone video with `audio.<ext>` is in `downloadedNoTranscript` (no availability filter there) and so in `backfill.transcription.ids`; it stays in `excludedFromDownload.deleted`. fetch-copies asks each changed channel's report (`requestChannelSnapshot`). @@ -10190,6 +10223,49 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri Transcription section); the video page's re-download **Stored media URL** select (`aria-label "stored media URL"`) shown only when the record stores a trusted URL and the channel is transcribe handling. +## Release 32 lane R8: the operator's rulings of 2026-10-17 (verified 2026-10-17, branch `r32/rulings`) + +- **The verdict bench** (`r30/bench-v3` merged in): the meanings reversal is kept; dedupe is off by default — see + "Release 30 lane V" above (`benchItemsOf`'s `dedupe`). +- **Wayback-only citations are OK on public sites** — see "Release 31 lane C" (`waybackCitationLinks`). +- **The Wayback "found" check** (`lib/waybackClient.ts`): `videoInfoFormatUrls(raw)` (a dmux answer's audio, then + video; repeats once; http(s) only), `waybackStreamUrl(fmt)` = `https://web.archive.org/web/2id_/<format url>` + (yt-dlp's `_parse_fmt`), `youtubeVideoStream(id)` → `{formats, stream: url | null, probes: [{url, status}]}`: the + first of at most `WAYBACK_STREAM_PROBES_MAX` (3) formats whose ranged GET answers 200/206 with a non-HTML body. + The probe is `ArchiveOrgClient.probe(url)` — ONE `Range: bytes=0-1023` GET (`PROBE_BYTES`) through the same chain, + gap and back-off, the body cancelled; a non-retried error answers its status, 429/503 kept up throws `rateLimited`. + `youtubeVideoArchived` stays (formats listed). `lookForCopy` uses the stream: listed but no stream → + `WAYBACK_PAGE_ONLY` "page captured, no video (the video index lists N format(s); M probed, HTTP <statuses>)", not a + copy, not a lookup error; archive.org is still tried. **The article mode now records `none-found`** in + copy-attempts.json as the scope mode does (a YouTube recording, no copy, no lookup error, not a dry run; + `FindCopyDeps.recordAttempt`/`now`). The live case (2026-10-16, one recording): formats listed, 404 at the format + URL, recorded `failed` by fetch-copies before this. +- **Full audio before a salvage** (`lib/fullAudioFirst.ts`, pure; `fullAudioFirst-server.ts` `fullAudioGate(videoDir, + {handling?, mode?})`; `controller/fullAudioFirst.ts`): `FULL_AUDIO_ATTEMPTS` = 2. An attempt is a + `stored-url-ranged` attempt in the video's download record (a refetch appends its attempts to the + corrupt-full-source record, refusals included). Applies to a corrupt-full-source record whose metadata stores a + trusted media URL (`storedMediaUrl`), on a transcribe-handling channel, with a stored-URL mode other than `never` + (the request's, else the channel's `storedUrlDownloads`). + - `downloadOneManaged`: a corrupt-full-source REFETCH with no `storedUrl` asked and no `storedUrlDownloads` on the + channel runs as `storedUrl: "only"` while attempts are owed (log `Full audio first (full audio attempts: n of 2): + …`); after 2, the page as before. So `retry-bucket corruptFullSource` reads the stored URL first too. + - `transcribeOneVideo`'s automatic salvage (no `salvage` given) of such a video with attempts owed throws + `TranscribeError("no-audio")` (`fullAudioFirstRefusal`); `salvage: true` still forces one; the channel's config.json + is read beside `data/<id>/` (`readChannelConfigFile`). + - The editor's `whisperVideoAction` (audio on disk) and `transcribeOneAction`, with `salvage` undefined, call + `fullAudioFirst` first: up to the owed attempts, each `downloadOneManaged({storedUrl: "only"})` (R7's 20-minute gap + between files applies) — clean → transcribe in full; exhausted → the salvage; a `rate_limit` with attempts still + owed → the job fails ("…transcribe again later"). So `pnpm ops transcribe-one {slug, id}` does the same. + - Snapshot **`fullAudio?: {of, attempts: {id: n}, awaiting: [id]}`** (top level, beside `totals`): on a + transcribe-handling channel whose `storedUrlDownloads` is not never — every corrupt full source whose record stores + a trusted media URL (one `storedMediaUrl` read per corrupt full source in the per-video fan-out, none for any other + video), its attempts, and the untranscribed unsalvaged ones still owed (`awaiting`). Omitted when none. The channel flow: a download siding **"awaiting full audio"**, and the salvaged siding reads **"salvaged — + full audio attempts: n"** (a range `a–b` when they differ) when `fullAudio` covers them, else "salvaged transcript". + - The partial mark: the video page's salvaged notice adds "Full audio attempts: n of 2." (a record with a trusted + stored URL); the video list's transcript dot is amber with "salvaged transcript (partial …)" (`VideoRow. + salvagedTranscript`); MCP `get_transcripts` adds the salvage caveat to that video's block (get_transcript and + get_video_metadata already did; the export's TranscriptModal already shows "Partial transcript: …"). + ## Release 32 lane R9: the Odysee loop — the cut's page open, one stored-URL rest, the lane, the browser lookup (verified 2026-10-17, branch `r32/odysee-loop`) - **The clip cut opens the player's page** (`ytdlp/fetchWindowManaged.ts`, the stored-URL ffmpeg branch). diff --git a/plans/release-30/V.md b/plans/release-30/V.md @@ -0,0 +1,94 @@ +# Release 30 lane V — the verdict bench, v3 + +### V, as shipped (2026-10-15, lane V, `r30/bench-v3` from `main` `59fdc486`) + +The diagnosis of bench v2's disagreements, and the fixes it called for. No real model call was made: the qwen +runs are the orchestrator's (the transcription lane and the memory floor held the GPU the whole session). The +commands are at the end of this section. + +**The diagnosis** (opus on prompt 2, `vb-r29-api`: 71 of 146 answered items disagree with the operator; read +locally, recorded as counts only): + +| Category | Disagreements | What it is | +| --- | --- | --- | +| compound claim, partly shown | 22 | the claim joins several things; some are shown, one is not found (or a quoted phrase, a count or a date is not the speaker's) — the operator rules PARTLY; v2's meaning ("a part only not shown does not make PARTLY") sent the model to CORROBORATED (18) or NOT_FOUND (4) | +| evidence the model never saw | 14 | the ruling rests on the claim's cited posts or pages; v2 items carried transcript windows only | +| framing | 14 | the operator rules the substance hers (paraphrase, softer wording); the model demotes for framing (PARTLY 10, CONTRADICTED 4) | +| corpus-wide claim | 11 | how often, "never", "constantly", "didn't come up in the episode": the operator ruled from a corpus search no window shows | +| ruling needs outside context | 6 | a fact about the world beside what was said ("she gets it wrong: X"), a claim phrased as a prediction, a feud the window only half shows | +| model error | 4 | a verdict against the model's own reason, or a misread | +| window miss | 0 | every cited quote is inside its ±60 s window (147 of 147, token overlap ≥ 0.6) | + +qwen on prompt 1 (`vb-r28`, 79 disagreements): the same categories where they overlap (evidence 14, framing 12, +corpus-wide 8, outside context 4, compound 4, model error 1) plus 36 of its own — 25 CORROBORATED claims demoted to +PARTLY for an unshown detail (prompt 1's meanings), 6 misreads, 5 others. + +Two item facts beside it: the 147 items are **74 distinct claims**, each twice (the second fact-check is a re-cut of +the first, its 73 repeats ruled identically), and the re-cut's **section headings name the verdict** — the answer, +shown to the model as context since V1. + +**What changed:** + +- **Evidence** (`items.ts`): a claim's post and page citations are its `evidence` — quoted, with label, speaker and + date (never a page's note), at most `EVIDENCE_MAX` 8, each quote cut at 600 characters — and the prompt quotes them + under "Cited posts and pages". 23 of the 74 claims carry some. +- **Withheld heading**: `sectionNamesVerdict` drops a section heading that names a verdict. +- **Dedupe**: `benchItemsOf` skips a claim that repeats an earlier item (same text, same cited spans), "the same claim + as <key>" (`dedupe`, default on). The registry now gives 74 items (39 CORROBORATED, 29 PARTLY, 3 NOT_FOUND, 2 + CONTRADICTED, 1 UNTESTABLE; the always-CORROBORATED baseline 52.7 %), hash `1aaf154834f0d807`, at half the cost of + a paid run. +- **Prompt v3** (`prompt.ts`, `PROMPT_VERSION` "3"): the model splits the claim into its parts (at most 6) and gives + each a finding — shown, shown wrong, not shown — plus `checkable`; the verdict follows in code (`verdictOfParts`), and + `readVerdictAnswer` holds the counts and lengths (Q0: rules, no examples, counts in code; the local prompt's largest + estimate over the 74 items is 7,214 tokens, none trimmed). +- **The meanings** (`verdicts.mjs`) are rewritten in parts terms to match the 147 rulings, and `VERDICT_PARTS_RULE` + replaces `VERDICT_TIE_RULE` (REPORT.md regenerated). **Ruling owed:** this reverses V1's "a part only not shown + does not make PARTLY"; the rulings bear the reversal out (22 disagreements), and the operator confirms it. +- **M8** (`tasks/verdicts.ts`) reads its answer through `readVerdictAnswer`, so proposals use the same rule. +- **umtool `/tools/bench`**: under each claim "what the model saw" (its windows' lines, its posts and pages), under + each answer the model's parts. +- **Not done:** a "look wider" second pass before a NOT_FOUND stands (the diagnosis found no window misses), the + `turn` window as the default (same reason), and post-only claims as items (9 ruled claims cite no span; left as + before). + +**The second attempt.** Q0's "keep the better of two attempts" is set up, not yet decided: attempt A is the shipped +v3 (parts, the verdict in code); attempt B ("3a", not committed) is the same items and meanings with a holistic +`{reason, verdict}` answer, kept as a snapshot in the scratch dir. Whichever qwen scores higher stays. + +| Commit | What | +| --- | --- | +| `6fe0d13b` | common, umtool: evidence, the withheld heading, dedupe, prompt v3 with the verdict in code, the meanings, M8's reader, the bench page; tests; REPORT.md | +| `ec5b8726` | this record, FACTS, CHANGELOG | +| (this commit) | umtool e2e: the V1 test reads v3's meanings; the record's e2e gate | + +Gates (branch start in brackets): + +| Gate | Result | +| --- | --- | +| tsc | common and umtool package tsc clean at `6fe0d13b`; repo-wide `tsc --noEmit` clean at this commit | +| common `pnpm --filter yt-dlp-transcript-common test` | **4255/4255** [4253] (+2 in `bench.test.ts`: the verdict from the parts and the counts; evidence, the withheld heading, dedupe and the hash) | +| `pnpm --filter umtool test` | 33/33 [33] | +| `archilyzer docs files --check` | clean after regenerating REPORT.md | +| umtool e2e `verdict-bench.spec.ts` (foreground, queued) | run 1: 3 passed, 1 failed (the V1 test still asserted V1's CORROBORATED meaning — the expectation updated to v3's meanings and the parts rule); run 2: **4 passed**, 0 failed, 17.4 s. The spec gains the what-the-model-saw and parts assertions | +| qwen runs | **not run**: the transcription lane and the memory floor; commands below | + +**The runs** (the orchestrator's; each behind the heavy lock, ≥ 7000 MB available, the transcription lane idle): + +- q2, prompt-2 baseline, through the live editor (from the primary): + `pnpm ops bench-verdicts --json '{"models":["qwen3:8b"],"itemsFrom":"vb-r28","run":"vb-r30-q2"}' --wait` +- q3, v3 (from `~/Projects/r30-bench-v3/common`): `pnpm exec tsx $T/r30v-run.mts vb-r30-q3` +- q4, v3 attempt B: `R30V_COMMON=$T/r30v-snap-q4/common pnpm exec tsx $T/r30v-run.mts vb-r30-q4` +- score on the shared claims, with the diagnosis categories: `pnpm exec tsx $T/r30v-score.mts vb-r28:qwen3:8b vb-r30-q2 vb-r30-q3 vb-r30-q4` + +**Proposed paid run** (after the better qwen attempt): sonnet + opus on v3's 74 items, `maxUsd` 3 (v2's 147-item +run spent $4.99; half the items, plus the evidence and the parts' output). Expected: the 14 evidence and 22 +compound-claim disagreements are where opus's 51.4 % was lost; recovering two thirds of them would put opus near +65–70 % against the 52.7 % baseline. + +## Ruling (operator, 2026-10-17) — release 32 R8 + +- **(a) only.** The meanings reversal is kept: a claim with a part the evidence does not show is PARTLY (REPORT.md's + definitions as regenerated here). +- **Dedupe is not the default.** A fresh bench asks every claim; dedupe is an explicit option (`--dedupe`, the + `bench-verdicts` body's `dedupe: true`). Merged into `r32/rulings` and changed there (`plans/release-32/rulings.md`). +- **No paid run.** diff --git a/plans/release-32/rulings.md b/plans/release-32/rulings.md @@ -0,0 +1,136 @@ +# Release 32 lane R8 — the operator's rulings of 2026-10-17 (as shipped) + +Branch `r32/rulings` from `main` `eb8d9523`. Brief: `r32r8-brief.md` (the plan of record for this lane). +FACTS: "Release 32 lane R8: the operator's rulings of 2026-10-17", plus the rulings recorded in place under "Release 30 +lane V" and "Release 31 lane C". + +## The rulings + +1. **Verdict bench v3 — (a) only.** The meanings reversal is kept (a claim with a part the evidence does not show is + PARTLY; REPORT.md's definitions as bench v3 regenerated them). Dedupe is NOT the default: a fresh bench asks every + claim, and dedupe stays available as an explicit option. No paid run. +2. **Wayback-only citations are OK on public sites** (a YouTube original with only a Wayback copy, cited as + "Original (may be gone)" + the Wayback link — release 31 C). No code. +3. **Build the Wayback "found" check.** +4. **Partial transcripts: marked, but full audio first.** + +## What + +- **1, the bench.** `r30/bench-v3` (`acc876a4`) merged in (`a410f413`; the CHANGELOG conflict kept both sides). + `benchItemsOf`'s `dedupe` is now off unless `true`; `BenchOptions.dedupe` → `--dedupe` (CLI), `"dedupe": true` + (`bench-verdicts` body, checked a boolean at the door); validated (never with `itemsFrom`); a run made with it records + `summary.dedupe: true`, and a continuation that names another setting is refused; a run made from `itemsFrom` carries + its source's setting. The editor's bench and M8 proposal tests answered in v2's shape and failed after the merge (bench + v3's lane did not run the editor suite); their stubs answer in v3's (parts, checkable, reason). V's record + (`plans/release-30/V.md`) carries the ruling; FACTS' V section says default off and the reversal kept. +- **2, Wayback-only citations.** Recorded in FACTS where find-copy and `waybackCitationLinks` are described. +- **3, the Wayback found check** (`lib/waybackClient.ts`, `lib/archiveOrgClient.ts`, `publish/findCopy.ts`): a video + the Wayback video index lists is a copy only when one of its formats' streams answers a ranged GET at yt-dlp's own + URL (`/web/2id_/<format url>`, archiveorg.py `_parse_fmt`) — one `bytes=0-1023` request per format, at most 3, through + the paced archive.org client (`ArchiveOrgClient.probe`: the chain, the 2 s gap, the back-off; the body cancelled). + Listed with no answering stream → `page captured, no video (the video index lists N format(s); M probed, HTTP …)`: + not a copy and not a lookup error, so archive.org is tried next and, with nothing there, the video is recorded + `none-found` in `copy-attempts.json` — never handed to fetch-windows / fetch-copies to fail at its source. A probe + Wayback keeps refusing is a lookup error (tried again later, nothing recorded). The article mode now records + `none-found` as the scope mode does (a YouTube recording, no copy, no lookup error, not a dry run). The fake Wayback + (`testing/web/fakeWayback.mjs`) serves streams (`streams`, default `videos`; `streamBusyTimes`). +- **4, full audio first** (`lib/fullAudioFirst.ts`, `lib/fullAudioFirst-server.ts`, `controller/fullAudioFirst.ts`): + `FULL_AUDIO_ATTEMPTS` = 2; an attempt is a `stored-url-ranged` attempt on the video's download record (a refetch + appends its attempts to the corrupt-full-source record; refusals count). It applies to a corrupt full source whose + record stores a trusted media URL (`storedMediaUrl`, STORED_URL_PLATFORMS), on a transcribe-handling channel, with a + stored-URL mode other than `never` (the request's, else the channel's `storedUrlDownloads`). + - **The refetch** (`downloadOneManaged`): a corrupt-full-source refetch with no mode asked (request or channel) runs + as `storedUrl: "only"` while attempts are owed — R7's ranged reader, its audio check, its page open and its + 20-minute gap — then from the page as before. `retry-bucket corruptFullSource` therefore reads the stored URL first. + - **The salvage gate** (`transcribeOneVideo`): an automatic salvage (no `salvage` given) of such a video with attempts + owed is refused as `TranscribeError("no-audio")` (a batch skips it, no failure recorded); `salvage: true` still + forces one. + - **Transcribe** (the video page's, and `pnpm ops transcribe-one` without `file`/with it, `salvage` unset): the owed + downloads first (`fullAudioFirst`, each `downloadOneManaged({storedUrl: "only"})`): clean → the full transcript; + exhausted → the salvage; a rate limit with attempts still owed → the job fails "transcribe again later" (no + hammering). + - **Marked partial wherever it shows:** the video page's salvaged notice adds "Full audio attempts: n of 2." (a record + with a trusted stored URL); the video list's transcript dot is amber with "salvaged transcript (partial …)" + (`VideoRow.salvagedTranscript`); MCP `get_transcripts` marks the video's block (whole and windowed) as + `get_transcript` and `get_video_metadata` did; the export's TranscriptModal already says "Partial transcript: …". + - **The pipeline view:** the snapshot's `fullAudio {of, attempts, awaiting}` (one `storedMediaUrl` read per corrupt + full source); the flow's download siding **awaiting full audio** and the transcribe siding **salvaged — full audio + attempts: n** (a range when they differ; "salvaged transcript" elsewhere). + - Ops help (`transcribe-one`, `retry-bucket`, `bench-verdicts`), COMMANDS.md regenerated. + +## Files + +`REPORT.md`, `common/lib/report/**` and `umtool/**` (the bench-v3 merge); `common/lib/report/draft/bench/{items,run,store}.ts`, +`common/controller/benchVerdicts.ts`, `common/bin/{archilyzer,reports-bench-verdicts}.ts`; `common/lib/archiveOrgClient.ts`, +`common/lib/waybackClient.ts`, `common/publish/findCopy.ts`, `common/testing/web/fakeWayback.{mjs,d.mts}`, +`common/testing/README.md`; `common/lib/fullAudioFirst.ts` (new), `common/lib/fullAudioFirst-server.ts` (new), +`common/controller/fullAudioFirst.ts` (new), `common/controller/transcribeOne.ts`, `common/ytdlp/downloadOneManaged.ts`, +`common/controller/channelSnapshot.ts`, `common/views/pipeline/channelFlow.ts`; `editor/app/channels/[slug]/videos/[id]/videoActions.ts`, +`…/components/{VideoPanel,SalvagedTranscriptNotice}.tsx`, `editor/app/channels/[slug]/lib/{videoRows,videoRowsServer}.ts`, +`…/components/VideoListPane.tsx`, `editor/app/api/ops/{bench-verdicts,transcribe-one}/route.ts`; `mcp/src/server.ts`; +`scripts/archilyzer-ops.mjs`, `COMMANDS.md`. +Tests: `common/lib/report/draft/bench/bench.test.ts` (dedupe off/on, the plan, the refusal), `common/lib/waybackClient.test.ts` +(+2), `common/publish/findCopy.test.ts` (+1, and the none-found records), `common/publish/findCopyScope.test.ts` (+1), +`common/controller/fullAudioFirst.test.ts` (4, new), `common/ytdlp/storedUrlManaged.test.ts` (+3), +`common/controller/channelSnapshot.test.ts` (+1), `common/views/pipeline/channelFlow.test.ts` (+1), +`editor/app/api/ops/{_benchVerdicts,_verdicts}.test.ts` (v3 stubs; the dedupe body), `mcp/src/search.test.ts` +(get_transcripts), `editor/e2e/full-audio-first.spec.ts` (1, new). + +| Commit | What | +| --- | --- | +| `a410f413` | merge `r30/bench-v3` | +| `d1c932e1` | common: the bench asks every claim by default; `--dedupe` / `dedupe: true` explicit | +| `104b09cf` | common: find-copy's Wayback found check; none-found recorded by the article mode; the fake serves streams | +| `3fca654d` | editor: the bench and M8 tests answer in v3's shape; the dedupe body | +| `e2b39f14` | common, editor, mcp: full audio before a salvage; the flow, the marks; ops help, COMMANDS.md; the e2e spec | +| `5a9c60af` | common: the snapshot reads each corrupt record's trusted URL | +| `8abfcd54` | editor: the Transcribe row's full-audio line and Salvage now; e2e | +| `cb9b2fdc` | this record, FACTS, CHANGELOG, V's ruling | +| `8be5eb1e` | merge `main` `72f777ae` (R7, R9, the cornbreadman import sweep); FACTS and CHANGELOG keep both sides | +| (this commit) | the gates | + +## Gates + +Everything ran through the shared heavy lock from the worktree root. Final run at `8be5eb1e` (`main` `72f777ae` merged in): +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean. +- common: `main` was 4537 per R7's record → **4594 (4593 pass, 0 fail, 1 skipped)** after the merge. On the branch before + the merge it was 4552 (4551 + 1 skipped). Only one earlier run had failures: `architecture.test.ts` flagged a lib test + importing controller (the test moved to `controller/`), and COMMANDS.md was stale (regenerated). +- editor unit: **346/346** after the merge, 342/342 before it. The bench-v3 merge left 2 failures (v2-shaped stubs), + which are fixed. +- mcp: **378/378**. test:scripts: **1053 (1049 pass + 4 skipped)**. umtool unit: **45/45**. +- `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: clean. +- e2e, one spec at a time: umtool `verdict-bench.spec.ts` passed 4/4 at `e2b39f14` and again at `8be5eb1e`. Editor + `full-audio-first.spec.ts`: + - run 1 at `e2b39f14`: 1/1. + - run 2: 0/1. The kept file was `audio.mp4`, which the video page lists for Transcode, not Transcribe, so the new row + never showed. The fixture now keeps `audio.m4a`, the channel's format. + - run 3 at `8be5eb1e`: 1/1 (1.8 s, start-mode build 64 s). + +## Decisions I made + +- **Dedupe as an explicit option** is a flag on every surface that starts a bench (CLI `--dedupe`, the ops body), not + only the library's parameter — otherwise "stays available" would be unreachable. A run records it; resuming with the + other setting is refused (as for `--limit`). +- **The found check probes at most 3 formats**, audio first (fetch-copies asks yt-dlp for `ba/b`), with a 1 KiB ranged + GET; a 200 that is an HTML page is not a stream. The copy's URL stays the watch-page replay URL yt-dlp takes. +- **The article mode records none-found too** — the brief says to record "page captured, no video" as none-found, and + only the scope mode wrote attempts. A recorded none-found makes the scope mode skip the video for 30 days (its rule). +- **An attempt is any `stored-url-ranged` attempt on record, a 429 included** — the ruling counts attempts. A refused + attempt with attempts still owed fails the Transcribe job instead of trying the next one at once. +- **Full audio first applies to corrupt full sources only**, not to damaged held audio (release 31 A's other automatic + salvage), per the brief's wording; damaged held audio is salvaged as before. +- **An explicit mode is respected**: the request's or the channel's `never` keeps release 30's behaviour (salvage at + once); an explicit `fallback`/`only` on the request or channel is used as given (the refetch is not switched). +- **The editor's Transcribe makes the attempts inline** (each paced by R7's 20-minute gap), so a person can do it from + the video page with no model and no CLI; `salvage: true` (ops) still salvages at once. +- **The snapshot reads `metadata.info.json` for corrupt full sources only**, in the per-video fan-out (not the + classification loop). + +## Not done + +- No live run (the orchestrator's, after merge — commands in the report). No paid bench run (ruled). +- **Salvage now** is on the Transcribe row of a file in the channel's audio formats. A corrupt full source whose only + kept file is a container (`audio.mp4` on an m4a channel) is listed under Transcode, so it gets no Salvage now; for + that case `pnpm ops transcribe-one {"salvage": true}` remains. +- Damaged held audio (release 31 A) is not gated (see Decisions). diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -462,7 +462,7 @@ const ACTIONS = [ "verdict-review", // THE VERDICT BENCH (release 28 M7): ruled fact-check claims asked of each // model, one per call ({models, run?, reports?, window?, windowMode?, - // maxUsd?, limit?, itemsFrom?}), + // maxUsd?, limit?, itemsFrom?, dedupe?}), // 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 @@ -959,7 +959,10 @@ export function usage() { ' managed path. A job; --wait follows it. "salvage": true decodes a damaged', ' file with error tolerance and transcribes what decodes, on the', ' recording\'s clock, its gaps recorded (the transcript is listed as', - ' salvaged); a corrupt-full-source video is salvaged unless "salvage": false.', + ' salvaged); a corrupt-full-source video is salvaged unless "salvage": false', + ' — once its full audio was tried: when its record stores an Odysee media', + ' URL, that URL is downloaded first, up to 2 times (20 min apart), and the', + ' salvage follows only if neither download is clean.', ' "storedUrl": "only" | "fallback" | "never" downloads missing audio from the', ' media URL the record stores (Odysee\'s CDN), read in ranges as its player', ' reads it — no page request with "only", the page first with "fallback" —', @@ -1147,6 +1150,8 @@ export function usage() { " with ids is not replayable, as a checkbox selection in the UI is not.", ' "corruptFullSource" downloads again: the kept file is set aside, and comes', " back if the download fails; malformed again, the longer decode stays.", + " A record that stores an Odysee media URL is read from that URL (as", + ' "only") until 2 such downloads are on record, then from the page.', ' "storedUrl": "fallback" | "only" reads each from the media URL its record', ' stores, as on download-missing (a held platform\'s retry runs as "only").', ' "corruptHeldAudio" (held audio the audio audit found damaged) is refetched', @@ -1490,7 +1495,9 @@ export function usage() { ' "windowMode"? ("seconds" | "turn": the cited speaker\'s turn, bounded by', ' the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the', ' operator\'s verdict), "itemsFrom"? (an earlier run\'s exact items; no', - ' reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim', + ' reports, window, windowMode, limit or dedupe with it), "dedupe"? (true: a', + ' claim repeating an earlier one, the same text over the same cited spans, is', + ' asked once; default: every claim is asked)} -> {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", diff --git a/umtool/app/tools/bench/page.tsx b/umtool/app/tools/bench/page.tsx @@ -7,12 +7,13 @@ import { BASELINE_MODEL, VERDICTS, VERDICT_MEANINGS, - VERDICT_TIE_RULE, + VERDICT_PARTS_RULE, filterBenchRows, passesBar, readBenchRuns, readBenchView, readVerdictsPolicy, + type BenchItemRow, } from "@/lib/bench"; import type { MarkedScore, ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; @@ -34,6 +35,9 @@ export const dynamic = "force-dynamic"; // whose answers changed); a Right / Wrong mark on each disagreement; the // not-CORROBORATED precision and recall beside the bar, marked and not; what // the verdicts mean (the one copy, verdicts.mjs). +// +// Bench v3: under each claim, what the model saw (its windows and its cited +// posts and pages); under each answer, the model's parts and their findings. type Search = { run?: string; model?: string; verdict?: string; compare?: string }; @@ -187,6 +191,7 @@ function RunView({ <td className="max-w-[28rem] py-1.5 pr-2"> <div className="font-mono text-[10px] text-[var(--color-dim)]">{r.key}</div> {r.text} + <Seen row={r} /> </td> <td className="py-1.5 pr-2 font-mono">{r.verdict}</td> {models.map((m) => { @@ -198,6 +203,8 @@ function RunView({ ) : a.verdict ? ( <> <span className={`font-mono ${a.verdict === r.verdict ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}`}>{a.verdict}</span> + {a.parts && <Parts parts={a.parts} />} + {a.checkable === false && <div className="micro">not checkable</div>} {a.reason && <div className="text-[var(--color-dim)]">{a.reason}</div>} {a.verdict !== r.verdict && <MarkButtons run={s.id} model={m} item={r.key} initial={a.mark} />} </> @@ -224,7 +231,7 @@ function RunView({ </div> ))} </dl> - <p className="mt-1 text-[var(--color-dim)]">{VERDICT_TIE_RULE}</p> + <p className="mt-1 text-[var(--color-dim)]">{VERDICT_PARTS_RULE}</p> </details> {s.dropped && s.dropped.length > 0 && ( <details> @@ -254,6 +261,64 @@ function RunView({ ); } +const stampOf = (sec: number) => { + const t = Math.max(0, Math.floor(sec)); + const h = Math.floor(t / 3600); + const m = Math.floor((t % 3600) / 60); + const ss = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +}; + +// What the model saw beside the claim (bench v3): the cited posts and pages, +// and each transcript window — its span, what ended it, its cues. +function Seen({ row }: { row: BenchItemRow }) { + return ( + <details data-seen={row.key} className="mt-1"> + <summary className="micro cursor-pointer"> + what the model saw · {row.windows.length} window{row.windows.length === 1 ? "" : "s"} + {row.evidence.length ? ` · ${row.evidence.length} post${row.evidence.length === 1 ? "" : "s"} or page${row.evidence.length === 1 ? "" : "s"}` : ""} + </summary> + {row.evidence.length > 0 && ( + <ul aria-label="posts and pages" className="mt-1 flex flex-col gap-0.5"> + {row.evidence.map((e) => ( + <li key={e.citation} data-evidence={e.kind}> + <span className="micro">{[e.kind, e.label ?? e.title ?? e.channel, e.date].filter(Boolean).join(" · ")}</span> “{e.quote}” + </li> + ))} + </ul> + )} + {row.windows.map((w) => ( + <div key={`${w.channel}/${w.id}/${w.from}`} data-window={`${w.channel}/${w.id}`} className="mt-1"> + <div className="micro"> + {w.label ?? `${w.channel}/${w.id}`} · {stampOf(w.from)}–{stampOf(w.to)} + {w.bound ? ` · ended by ${w.bound}` : ""} · {w.cues.length} lines + </div> + <div className="max-h-48 overflow-y-auto font-mono text-[10px] text-[var(--color-dim)]"> + {w.cues.map((c) => ( + <div key={c.start}> + [{stampOf(c.start)}] {c.text} + </div> + ))} + </div> + </div> + ))} + </details> + ); +} + +// The model's parts and what it found of each (bench v3: the verdict follows from them). +function Parts({ parts }: { parts: NonNullable<BenchItemRow["answers"][string]["parts"]> }) { + return ( + <ul aria-label="parts" className="mt-0.5 flex flex-col"> + {parts.map((p, i) => ( + <li key={i} data-part-finding={p.finding}> + <span className="font-mono text-[10px] text-[var(--color-dim)]">{p.finding}</span> {p.part} + </li> + ))} + </ul> + ); +} + // "Not CORROBORATED" as the positive class — the claims a proposal would put // in front of the operator — plain and with the operator's marks applied. function Precision({ scores, marked }: { scores: ModelScore[]; marked: MarkedScore[] }) { diff --git a/umtool/e2e/fixtures/bench-fixture.mjs b/umtool/e2e/fixtures/bench-fixture.mjs @@ -23,7 +23,7 @@ const said = { [QWEN]: ["CORROBORATED", "CORROBORATED", "CORROBORATED", null], }; -export function makeBenchRun(root, o = {}) { +export function makeBenchRun(root, o = { parts: true }) { const run = o.run ?? BENCH_RUN; const answers = o.said ?? said; const dir = path.join(root, run); @@ -37,7 +37,17 @@ export function makeBenchRun(root, o = {}) { verdict, quotes: [{ citation: `q${i}`, channel: "synth-kitchen", id: "bread-day-01", start: 10 + i * 15, end: 14 + i * 15, quote: "a line" }], windows: [{ channel: "synth-kitchen", id: "bread-day-01", from: 0, to: 80, cited: [{ start: 10 + i * 15, end: 14 + i * 15 }], cues: [{ start: 10 + i * 15, end: 14 + i * 15, text: "a line" }] }], + // Bench v3: a cited post beside the transcript (c2's). + ...(id === "c2" ? { evidence: [{ citation: "p1", kind: "post", channel: "synth-kitchen-posts", quote: "the oven was off for a week", date: "2026-01-06" }] } : {}), })); + // Bench v3: the parts a v3 answer carries, consistent with its verdict. + const partsOf = (v, claim) => + ({ + CORROBORATED: [{ part: `${claim}: what the article says`, finding: "shown" }], + PARTLY: [{ part: `${claim}: what the article says`, finding: "shown" }, { part: `${claim}: how long`, finding: "not shown" }], + CONTRADICTED: [{ part: `${claim}: what the article says`, finding: "shown wrong" }], + NOT_FOUND: [{ part: `${claim}: what the article says`, finding: "not shown" }], + })[v]; const results = []; for (const [model, verdicts] of Object.entries(answers)) { items.forEach((it, i) => { @@ -47,6 +57,7 @@ export function makeBenchRun(root, o = {}) { model, verdict: v, ...(v ? { reason: `${model} read the window for ${it.claim}` } : { failure: "parse", error: "the answer is not JSON" }), + ...(v && o.parts && model === SONNET ? { parts: partsOf(v, it.claim) } : {}), ms: 1200 + i * 100, usd: model === SONNET ? 0.004 : 0, inputTokens: 900, diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts @@ -60,6 +60,14 @@ test("the run: each model's tile against the baseline, the matrix, the items wit await expect(rows.nth(3)).toHaveAttribute("data-item", "synth-bench/c1"); await expect(rows.nth(0).locator(`[data-model="${SONNET}"]`)).toContainText("read the window for c2"); await expect(rows.nth(2).locator(`[data-model="${QWEN}"]`)).toContainText("parse: the answer is not JSON"); + // Bench v3: what the model saw (the cited post, the window's lines), and the model's parts. + const c2 = rows.nth(0); + await expect(c2.locator('[data-seen="synth-bench/c2"] summary')).toHaveText("what the model saw · 1 window · 1 post or page"); + await c2.locator('[data-seen="synth-bench/c2"] summary').click(); + await expect(c2.locator('[data-evidence="post"]')).toContainText("the oven was off for a week"); + await expect(c2.locator('[data-window="synth-kitchen/bread-day-01"]')).toContainText("[0:25] a line"); + await expect(c2.locator(`[data-model="${SONNET}"] [data-part-finding="shown"]`)).toContainText("c2: what the article says"); + await expect(c2.locator(`[data-model="${QWEN}"] [data-part-finding]`)).toHaveCount(0); // By model: that model's disagreements first, its column alone. await page.getByRole("region", { name: "items" }).getByRole("link", { name: SONNET, exact: true }).click(); await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c2"); @@ -126,7 +134,9 @@ test("V1: the run's prompt version and items hash; compare with a run over the s await expect(changed.nth(1)).toHaveText(`${SONNET} synth-bench/c3: CONTRADICTED → PARTLY (ruled CONTRADICTED)`); // What the verdicts mean: the one copy. await page.getByText("what the verdicts mean").click(); - await expect(page.locator('[data-meaning="CORROBORATED"]')).toContainText("the substance of the claim is shown by the cited words"); + await expect(page.locator('[data-meaning="CORROBORATED"]')).toContainText("every part of the claim is shown by the cited evidence in substance"); + await expect(page.locator('[data-meaning="PARTLY"]')).toContainText("some parts of the claim are shown and at least one is not"); + await expect(page.getByText("A claim's parts are the separate things it says were said or done")).toBeVisible(); }); test("V1: a Right mark on a disagreement moves the marked precision; again unmarks", async ({ page }) => { diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts @@ -20,7 +20,7 @@ import { type RunCompare, type VerdictBar, } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; -import { VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS, isVerdict, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts"; +import { VERDICT_MEANINGS, VERDICT_PARTS_RULE, VERDICTS, isVerdict, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts"; import { sanitizeGeneration, type GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; import { BenchMarksError, setBenchMark } from "./bench-marks.mjs"; import { askEditor, EditorError } from "@/lib/articles/generation"; @@ -33,6 +33,9 @@ import { askEditor, EditorError } from "@/lib/articles/generation"; // — read from and written through the editor's settings action, as the // generation policy is. // +// Bench v3 (release 30): each item row carries what the model saw (the +// windows and the cited posts and pages) and each answer the model's parts. +// // Release 29 V1: each run's prompt version and items hash (a run before V1: // version "1", its hash computed from its items), a comparison with another // run over the same items, the operator's Right/Wrong marks on disagreements @@ -51,7 +54,14 @@ export type BenchItemRow = { claim: string; text: string; verdict: Verdict; - answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string; mark?: "right" | "wrong" }>; + // What the model saw beside the claim (bench v3): each window's span and + // cues, and the cited posts and pages. + windows: Pick<BenchItem["windows"][number], "channel" | "id" | "label" | "from" | "to" | "bound" | "cues">[]; + evidence: NonNullable<BenchItem["evidence"]>; + answers: Record< + string, + { verdict: Verdict | null; reason?: string; failure?: string; error?: string; mark?: "right" | "wrong"; parts?: BenchResult["parts"]; checkable?: false } + >; // A model whose answer is not the operator's (failures included). disagree: string[]; }; @@ -114,10 +124,22 @@ function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], mo ...(r.failure ? { failure: r.failure } : {}), ...(r.error ? { error: r.error } : {}), ...(mark ? { mark } : {}), + ...(r.parts?.length ? { parts: r.parts } : {}), + ...(r.checkable === false ? { checkable: false as const } : {}), }; if (r.verdict !== it.verdict) disagree.push(m); } - return { key: it.key, report: it.report, claim: it.claim, text: it.text, verdict: it.verdict, answers, disagree }; + return { + key: it.key, + report: it.report, + claim: it.claim, + text: it.text, + verdict: it.verdict, + windows: it.windows.map((w) => ({ channel: w.channel, id: w.id, ...(w.label ? { label: w.label } : {}), from: w.from, to: w.to, ...(w.bound ? { bound: w.bound } : {}), cues: w.cues })), + evidence: it.evidence ?? [], + answers, + disagree, + }; }); } @@ -176,7 +198,7 @@ export async function markBenchItem(run: string, model: string, key: string, ver return { mark: verdict }; } -export { VERDICT_MEANINGS, VERDICT_TIE_RULE }; +export { VERDICT_MEANINGS, VERDICT_PARTS_RULE }; // The rows a filter keeps, disagreements first (then in item order). export function filterBenchRows(rows: readonly BenchItemRow[], f: { model?: string; verdict?: string }): BenchItemRow[] {