commit 5064aa74230833f1bfea81747b08edef24b3ae78
parent bb58d02f8d503a8726d89a2618a92bb309022000
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 08:02:02 -0400
Merge branch 'r29/integration' into r29/gen-debts
Diffstat:
83 files changed, 4965 insertions(+), 272 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -36,7 +36,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster <image>\] \[--caption <line>\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) |
| `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/<id>/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 bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--max-usd <n>] [--limit <n>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28): 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 claim, its quotes and the transcript within --window seconds (default 60) of each cited span, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, against an always-CORROBORATED baseline). --dry lists the items and the skipped claims 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. Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /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>] [--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) |
| `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 gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers |
| `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) |
@@ -113,7 +113,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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. | |
| `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): a screenshot of each through the connected X profile (a forum thread: its host's forum profile), and its attached media through gallery-dl (a forum thread: the same profile), into the channel's posts-media/<id>/: {"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. | |
+| `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/<id>/: {"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. | |
| `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "<branch>", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of <id> in <dir> — archilyzer publish build <id>". `get publish` is the status. | |
| `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` |
| `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | |
@@ -142,12 +142,14 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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` |
| `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -> {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` |
| `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` |
-| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
+| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload instead: items naming the id in their identifier, title, description or original URL, each read for its files -> {query, found, items: \[{identifier, title?, file, url, source, size?}\], skipped: \[{identifier, why}\]}: each mirror's direct video file URL, an original preferred. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'`<br>`pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
+| `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -> {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` |
+| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?. Per recording, one at a time: the Wayback Machine (the newest capture of its page that recorded a 200), then archive.org (a mirror naming its YouTube id, an original video file preferred). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". -> {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, tried: \[{from, found, url?, detail?, error?}\], copy?, outcome: fetch \| text-only \| error}\], items, stopped?, jobId?, refused?}. dryRun answers the lookups and starts nothing. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait` |
| `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", ...} -> {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}}. | `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` |
| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
-| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {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 claim, its quotes, the transcript within 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 (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /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"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
### Usage, flags and environment
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -218,6 +218,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts |
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts |
+| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
| `E2E_FAKE_YTDLP_CHUNK_DELAY_MS` | — | Fake yt-dlp: delay between written chunks. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/OPERATING.md b/OPERATING.md
@@ -134,6 +134,8 @@ pnpm ops tag-videos --file ids.json
pnpm archilyzer reports convert sweep <sweep.md> --out <report.json>
pnpm ops fetch-windows --json '{"siteId":"example-site","dryRun":true}'
pnpm ops fetch-windows --json '{"siteId":"example-site"}' --wait
+pnpm ops find-copy --json '{"siteId":"example-site","dryRun":true}'
+pnpm ops find-copy --json '{"siteId":"example-site"}' --wait
pnpm ops reports-prepare --json '{"siteId":"example-site"}' --wait
pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md"]}' --wait
```
@@ -143,8 +145,15 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md"
report-to-video manifest.
- `fetch-windows` with `siteId` fetches every clip window the site's published reports cite that the disk does not
hold, one paced job per platform; a re-run resumes.
-- `reports-prepare` cuts the cited clips and copies the cited post captures, then exports; it fails naming each
- citation that lacks media. Offline: `pnpm archilyzer reports prepare <siteId>`,
+- A cited recording deleted or made private on its platform cannot be fetched from its page. `find-copy` (a site's
+ `siteId`, an `article`, or `"articles": true`) looks for a copy of each — a Wayback Machine capture of its page,
+ then an archive.org mirror naming its YouTube id — and fetches the cited windows from it as one fetch-windows job;
+ each window's provenance names the copy. `wayback-lookup` and `archive-search` `{"youtubeId"}` are the lookups on
+ their own.
+- `reports-prepare` cuts the cited clips and copies the cited post captures (Bluesky posts too: `capture-posts`),
+ then exports; it fails naming each citation that lacks media — except a moment whose source is gone (a deleted or
+ private recording with no copy on disk, a deleted post never captured), which is a warning: the page shows its
+ words only, marked "Source deleted". Offline: `pnpm archilyzer reports prepare <siteId>`,
`pnpm archilyzer reports export <siteId>`.
- One cited moment's media, from an agent: the MCP's `fetch_clip`.
diff --git a/REPORT.md b/REPORT.md
@@ -59,7 +59,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `id` | yes | The claim's id (letters, digits, `_ . : -`; at most 64): its anchor on the report page. Unique among the report's section, claim and entry ids, and none of the page's own anchors (`report-head`, `in-brief`, `found`, `claims`, `references`, `downloads`, `report-end`). |
| `title` | no | A short headline for the claim (plain text, e.g. a phrase it turns on), shown above its text. Absent = the text alone. |
| `text` | yes | The claim, as stated by the document under review (plain text). |
-| `verdict` | no | The ruling on the claim: `CORROBORATED`, `PARTLY`, `CONTRADICTED`, `NOT_FOUND`, `UNTESTABLE`. A fact-check's claim may leave it out (not yet ruled); a sweep's carries none. |
+| `verdict` | no | The ruling on the claim: `CORROBORATED`, `PARTLY`, `CONTRADICTED`, `NOT_FOUND`, `UNTESTABLE` (what each means: "The verdicts", below). A fact-check's claim may leave it out (not yet ruled); a sweep's carries none. |
| `gist` | no | The claim's finding in one line (plain text, at most 240 characters), shown beside its title in the overview of what the check found. Absent = the title alone. |
| `flag` | no | A short mark on the claim (plain text, one line, at most 60 characters), shown as a pill on its card: e.g. that the document gives no source for it. Absent = none. |
| `sourceQuote` | no | The document's own sentence making the claim: `{ "citation": "<id>" }`, naming a `source` citation (its still is shown with the claim). |
@@ -108,13 +108,15 @@ A report is also read as slides — its page's **Slides** view (`?rv=slides`), t
The shared vocabulary (`common/lib/report/verdicts.mjs` — the one copy; report-to-video's fact-check stamps read it too), in the order a tally lists them. A report's `verdicts` overrides a label (one line, at most 24 characters) or a colour (`#rgb` or `#rrggbb`), each on its own.
-| Verdict | Default label | Default colour |
-|---|---|---|
-| `CORROBORATED` | Corroborated | `#3fbf7f` |
-| `PARTLY` | Partly true | `#e3b23c` |
-| `CONTRADICTED` | Contradicted | `#e5534b` |
-| `NOT_FOUND` | Not found | `#8b93a7` |
-| `UNTESTABLE` | Untestable | `#7d8fd6` |
+| 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` |
+
+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.
## Iterations
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -416,8 +416,8 @@ export const COMMANDS: Command[] = [
{
path: ["reports", "bench-verdicts"],
usage:
- "--models <a,b,…> [--report <id,…>] [--window <s>] [--max-usd <n>] [--limit <n>] [--run <id>] [--dry] [--here] [--wait] [--json] the verdict bench (release 28): 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 claim, its quotes and the transcript within --window seconds (default 60) of each cited span, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT_FOUND recall, against an always-CORROBORATED baseline). --dry lists the items and the skipped claims 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. Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench) (exit 1 when the run stopped early or was refused; 2 for usage)",
- flags: { report: "string", models: "string", window: "string", "max-usd": "string", limit: "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>] [--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" },
run: async (ctx) => (await import("./reports-bench-verdicts")).benchRow(ctx),
},
{
diff --git a/common/bin/reports-bench-verdicts.test.ts b/common/bin/reports-bench-verdicts.test.ts
@@ -60,7 +60,8 @@ test("--dry: the items over the local corpus's cues, the skipped claims and the
const code = await benchMain({ models: "claude-sonnet-5-5,claude-opus-5-5,qwen3:8b", dry: true }, { paths: c.paths, runOps: async () => ++asked, out: cap.out });
assert.equal(code, 0);
assert.equal(asked, 0);
- assert.match(cap.logs[0]!, /^7 items from 1 fact-check\(s\), a 60 s window; 1 claims skipped$/);
+ assert.match(cap.logs[0]!, /^7 items from 1 fact-check\(s\), a 60 s window; 1 claims skipped, 0 citations dropped$/);
+ assert.match(cap.logs[1]!, /^ {2}prompt version \d+, items [0-9a-f]{16}$/);
assert.ok(cap.logs.includes(" skipped 1: no citation"));
assert.ok(cap.logs.some((l) => /^ {2}synth-ruled\/r04 {2}CONTRADICTED {2}1 quote\(s\), \d+ cues$/.test(l)));
assert.ok(cap.logs.some((l) => /^ {2}qwen3:8b \(local\): 7 calls, .*~\$0\.0000$/.test(l)));
@@ -82,6 +83,17 @@ test("a run goes through the editor (pnpm ops bench-verdicts); --here refuses a
);
assert.equal(code, 0);
assert.deepEqual(seen, [["bench-verdicts", "--json", JSON.stringify({ models: ["claude-sonnet-5-5", "qwen3:8b"], run: "vb-real", maxUsd: 5 }), "--wait"]]);
+ // V1: the window mode, the stratified limit and items-from ride along.
+ seen.length = 0;
+ assert.equal(await benchMain({ models: "qwen3:8b", "window-mode": "turn", limit: "20" }, { paths: c.paths, runOps: async (argv) => (seen.push(argv), 0), out: capture().out }), 0);
+ assert.deepEqual(JSON.parse(seen[0]![2]!), { models: ["qwen3:8b"], limit: 20, windowMode: "turn" });
+ seen.length = 0;
+ assert.equal(await benchMain({ models: "qwen3:8b", "items-from": "vb-r28", run: "vb-r29-q1" }, { paths: c.paths, runOps: async (argv) => (seen.push(argv), 0), out: capture().out }), 0);
+ assert.deepEqual(JSON.parse(seen[0]![2]!), { models: ["qwen3:8b"], run: "vb-r29-q1", itemsFrom: "vb-r28" });
+ const bad = capture();
+ assert.equal(await benchMain({ models: "qwen3:8b", "items-from": "vb-r28", limit: "5" }, { paths: c.paths, runOps: async () => 0, out: bad.out }), 2);
+ assert.match(bad.errors.join("\n"), /items as they are: drop the limit/);
+ assert.equal(await benchMain({ models: "qwen3:8b", "window-mode": "sentence" }, { paths: c.paths, runOps: async () => 0, out: capture().out }), 2);
const cap = capture();
assert.equal(await benchMain({ models: "qwen3:8b", here: true }, { paths: c.paths, runOps: async () => 0, out: cap.out }), 2);
assert.match(cap.errors.join("\n"), /qwen3:8b runs on the GPU, which only the editor arbitrates/);
diff --git a/common/bin/reports-bench-verdicts.ts b/common/bin/reports-bench-verdicts.ts
@@ -1,8 +1,11 @@
// `archilyzer reports bench-verdicts --models a,b,c [--report <id>,…] [--window 60]
-// [--max-usd 5] [--limit n] [--run <id>] [--dry] [--here] [--wait] [--json]`
-// (release 28, M7) — 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/).
+// [--window-mode seconds|turn] [--max-usd 5] [--limit n] [--items-from <run>]
+// [--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).
//
// --dry lists the items (key, the operator's verdict, quotes, cues — no
// claim text unless --json) and the skipped claims with their
@@ -31,6 +34,7 @@ import { diskCuesOf } from "../lib/report/convert-server";
import {
BenchInputError,
isBenchRunId,
+ isWindowMode,
newBenchRunId,
validateBenchOptions,
planVerdictBench,
@@ -38,6 +42,7 @@ import {
type BenchPlan,
} from "../lib/report/draft/bench/index";
import { benchDailyCapRefusal, runBenchWithSettings } from "../controller/benchVerdicts";
+import { diskDateOf, diskTurnsOf } from "../lib/report/draft/bench/disk";
import { runOpsChild } from "./gen";
type Out = { log: (s: string) => void; error: (s: string) => void };
@@ -61,6 +66,11 @@ export function benchOptionsOf(flags: Record<string, FlagValue>): BenchOptions {
if (m !== undefined) o.maxUsd = m;
const l = num(flags.limit, "limit");
if (l !== undefined) o.limit = l;
+ if (typeof flags["window-mode"] === "string") {
+ if (!isWindowMode(flags["window-mode"])) throw new BenchInputError(`--window-mode is "seconds" or "turn"`);
+ o.windowMode = flags["window-mode"];
+ }
+ if (typeof flags["items-from"] === "string") o.itemsFrom = flags["items-from"];
if (typeof flags.run === "string") o.runId = flags.run;
validateBenchOptions(o);
if (o.runId !== undefined && !isBenchRunId(o.runId)) throw new BenchInputError("--run is a run id: lowercase letters, digits and dashes");
@@ -69,10 +79,17 @@ export function benchOptionsOf(flags: Record<string, FlagValue>): BenchOptions {
export function formatBenchPlan(plan: BenchPlan): string[] {
const lines: string[] = [];
- lines.push(`${plan.items.length} items from ${plan.reports.length} fact-check(s), a ${plan.windowS} s window; ${plan.skipped.length} claims skipped`);
+ const window = plan.windowMode === "turn" ? `the speaker's turn within ${plan.windowS} s` : `a ${plan.windowS} s window`;
+ lines.push(
+ `${plan.items.length} items from ${plan.reports.length} fact-check(s)${plan.itemsFrom ? ` (run ${plan.itemsFrom}'s items)` : ""}, ${window}; ${plan.skipped.length} claims skipped, ${plan.dropped.length} citations dropped`,
+ );
+ lines.push(` prompt version ${plan.promptVersion}, items ${plan.itemsHash}`);
const reasons = new Map<string, number>();
for (const s of plan.skipped) reasons.set(s.reason, (reasons.get(s.reason) ?? 0) + 1);
for (const [r, n] of reasons) lines.push(` skipped ${n}: ${r}`);
+ const drops = new Map<string, number>();
+ for (const d of plan.dropped) drops.set(d.reason, (drops.get(d.reason) ?? 0) + 1);
+ for (const [r, n] of drops) lines.push(` dropped ${n}: ${r}`);
const ruled = new Map<string, number>();
for (const it of plan.items) ruled.set(it.verdict, (ruled.get(it.verdict) ?? 0) + 1);
lines.push(` ruled: ${[...ruled].map(([v, n]) => `${v} ${n}`).join(", ") || "none"}`);
@@ -82,6 +99,7 @@ export function formatBenchPlan(plan: BenchPlan): string[] {
lines.push(` ${it.key} ${it.verdict} ${it.quotes.length} quote(s), ${cues} cues`);
}
for (const s of plan.skipped) lines.push(` skipped ${s.key}: ${s.reason}`);
+ for (const d of plan.dropped) lines.push(` dropped ${d.key} ${d.citation}: ${d.reason}`);
lines.push("estimate:");
for (const e of plan.estimate) {
lines.push(` ${e.model} (${e.provider}): ${e.calls} calls, ~${e.inputTokens} in / ~${e.outputTokens} out tokens, ~$${e.usd.toFixed(4)}`);
@@ -102,7 +120,12 @@ export async function benchMain(flags: Record<string, FlagValue>, deps: BenchDep
try {
opts = benchOptionsOf(flags);
if (flags.dry === true) {
- const plan = await planVerdictBench(opts, { paths: deps.paths, cuesOf: diskCuesOf(deps.paths.channelsDir) });
+ const plan = await planVerdictBench(opts, {
+ paths: deps.paths,
+ cuesOf: diskCuesOf(deps.paths.channelsDir),
+ turnsOf: diskTurnsOf(deps.paths.channelsDir),
+ dateOf: diskDateOf(deps.paths.channelsDir),
+ });
if (flags.json === true) out.log(JSON.stringify(plan, null, 2));
else for (const l of formatBenchPlan(plan)) out.log(l);
return plan.items.length ? 0 : 1;
@@ -145,6 +168,8 @@ export async function benchMain(flags: Record<string, FlagValue>, deps: BenchDep
if (opts.windowS !== undefined) body.window = opts.windowS;
if (opts.maxUsd !== undefined) body.maxUsd = opts.maxUsd;
if (opts.limit !== undefined) body.limit = opts.limit;
+ if (opts.windowMode !== undefined) body.windowMode = opts.windowMode;
+ if (opts.itemsFrom !== undefined) body.itemsFrom = opts.itemsFrom;
return deps.runOps(["bench-verdicts", "--json", JSON.stringify(body), ...(flags.wait === true ? ["--wait"] : [])]);
}
diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts
@@ -66,6 +66,7 @@ import {
resolveReports,
} from "../publish/composeReports";
import { articlesWorkHost, siteReportHost, type ReportHost } from "../publish/reportHost";
+import { SOURCE_GONE_LABELS } from "../lib/sourceGone";
type Out = { log: (s: string) => void; error: (s: string) => void };
@@ -116,6 +117,10 @@ export async function checkMain(
for (const line of formatComposeReportsProblems(resolved.allowed)) {
out.log(` allowed (--allow-missing-media): ${line}`);
}
+ // A gone source's moment with no media is a warning: its words only.
+ for (const g of resolved.sourceGone) {
+ out.log(` warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`);
+ }
for (const r of resolved.reports) {
const scores = Object.values(r.citations ?? {})
.map((c) => (c.kind === "video" || c.kind === "audio" || c.kind === "post" ? c.verification?.quoteScore : undefined))
diff --git a/common/bin/reports-prepare.ts b/common/bin/reports-prepare.ts
@@ -63,6 +63,12 @@ export async function main(
out.error(`reports prepare: ${(err as Error).message}`);
return opts.signal?.aborted ? 1 : 2;
}
+ // A gone source's moment with no media is a warning: compose shows its words
+ // only, marked "source deleted" (release 29 E2).
+ if (index.warnings?.length) {
+ out.log(`reports prepare ${who}: warning: ${index.warnings.length} moment(s) whose source is gone show their words only:`);
+ for (const line of formatReportMediaProblems(index.warnings)) out.log(` ${line}`);
+ }
if (opts.only && opts.article) return onlyArticle(opts.article, index, opts, out);
if (index.problems.length > 0) {
out.error(`reports prepare ${who}: ${index.problems.length} problem(s):`);
diff --git a/common/components/citations/CitationCard.tsx b/common/components/citations/CitationCard.tsx
@@ -13,6 +13,7 @@ import {
type SpanCitationView,
} from "../../lib/report/views";
import { cn } from "../../lib/utils";
+import { SOURCE_GONE_LABELS } from "../../lib/sourceGone";
import { VerificationBadge } from "./VerificationBadge";
// ONE CITATION, as a reader sees it — kind-aware, from a resolved view
@@ -135,10 +136,17 @@ function Picture({ c, variant }: { c: CitationView; variant: CitationCardVariant
function SpanLinks({ c }: { c: SpanCitationView }) {
return (
<>
- <a href={c.href} className={linkClass}>
- <Play className="size-3 shrink-0" aria-hidden />
- Play {spanLabel(c.start, c.end)}
- </a>
+ {c.sourceGone ? (
+ // Nothing to play: the moment's page has its words.
+ <a href={c.href} className={linkClass}>
+ Open {spanLabel(c.start, c.end)}
+ </a>
+ ) : (
+ <a href={c.href} className={linkClass}>
+ <Play className="size-3 shrink-0" aria-hidden />
+ Play {spanLabel(c.start, c.end)}
+ </a>
+ )}
<RecordLinks r={c.record} />
{c.record.corpusUrl && (
<a href={c.record.corpusUrl} className={linkClass}>
@@ -269,6 +277,11 @@ export function CitationCard({
</span>
)}
{c.label && <span className="truncate normal-case tracking-normal">· {c.label}</span>}
+ {(c.kind === "video" || c.kind === "audio" || c.kind === "post") && c.sourceGone && (
+ <span data-source-gone={c.sourceGone} className="normal-case tracking-normal">
+ · {SOURCE_GONE_LABELS[c.sourceGone]}
+ </span>
+ )}
</div>
<div className="font-medium leading-snug text-foreground break-words">{title}</div>
{meta.length > 0 && <div className="font-mono text-xs text-muted-foreground">{meta.join(" · ")}</div>}
diff --git a/common/components/report/MomentArticle.tsx b/common/components/report/MomentArticle.tsx
@@ -3,6 +3,7 @@ import { VerdictChip } from "./VerdictChip";
import { formatTimestamp } from "../../lib/vtt";
import { CITATION_KIND_LABELS, spanLabel, type MomentPageView, type RecordView } from "../../lib/report/views";
import { ExternalLinkText, Eyebrow, dateLabel, textLink } from "./parts";
+import { SOURCE_GONE_LABELS } from "../../lib/sourceGone";
// ONE CITED MOMENT, from its view (common/lib/report/views.ts): a span's
// self-hosted evidence clip (video, or audio with its poster) or a post's
@@ -47,6 +48,16 @@ export default function MomentArticle({
{meta && <p className="font-mono text-xs text-muted-foreground">{meta}</p>}
</header>
+ {view.sourceGone && (
+ // The source is gone and no copy of the moment is published: its words
+ // only (release 29 E2).
+ <p
+ data-source-gone={view.sourceGone}
+ className="rounded-lg border border-dashed border-border px-3 py-2 text-sm text-muted-foreground"
+ >
+ {SOURCE_GONE_LABELS[view.sourceGone]}
+ </p>
+ )}
{clip && view.kind === "video" && (
<video
data-evidence-clip=""
diff --git a/common/controller/benchVerdicts.ts b/common/controller/benchVerdicts.ts
@@ -6,8 +6,12 @@
// reports the fact-check articles to read (default: every one)
// models the models to ask (required)
// window seconds of transcript either side of each cited span (default 60)
+// windowMode "seconds" (the default) or "turn": the cited speaker's turn,
+// bounded by the window (release 29 V1)
// maxUsd the whole run's API cap (default 5, at most 50)
-// limit the first n items only
+// limit a stratified sample of n items, by the operator's verdict (V1)
+// itemsFrom the exact items of an earlier run (V1; no reports, window,
+// windowMode or limit with it)
//
// WHY A JOB IN THE EDITOR, NOT A `report-draft`: a bench writes no iteration
// and is no task of an article, so `report-draft`'s machinery (an iteration
@@ -36,18 +40,21 @@ import {
BenchInputError,
DEFAULT_BENCH_MAX_USD,
isBenchRunId,
+ isWindowMode,
newBenchRunId,
runVerdictBench,
validateBenchOptions,
type BenchOptions,
+ type WindowMode,
} from "../lib/report/draft/bench/index";
+import { diskDateOf, diskTurnsOf } from "../lib/report/draft/bench/disk";
import { isReportId } from "../lib/report/schema";
import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
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", "maxUsd", "limit"] as const;
+export const BENCH_VERDICTS_BODY_KEYS = ["run", "reports", "models", "window", "windowMode", "maxUsd", "limit", "itemsFrom"] as const;
const fail = (msg: string): never => {
throw new BenchInputError(msg);
@@ -79,6 +86,14 @@ export function parseBenchVerdictsBody(b: Record<string, unknown>): BenchOptions
if (typeof b.limit !== "number") fail(`"limit" is a number of items`);
out.limit = b.limit as number;
}
+ if (b.windowMode !== undefined) {
+ if (!isWindowMode(b.windowMode)) fail(`"windowMode" is "seconds" or "turn"`);
+ out.windowMode = b.windowMode as WindowMode;
+ }
+ if (b.itemsFrom !== undefined) {
+ if (!isBenchRunId(b.itemsFrom)) fail(`"itemsFrom" is a run id: lowercase letters, digits and dashes`);
+ out.itemsFrom = b.itemsFrom as string;
+ }
validateBenchOptions(out);
return out;
}
@@ -122,6 +137,8 @@ export async function runBenchWithSettings(
paths,
...(o.root ? { root: o.root } : {}),
cuesOf: diskCuesOf(paths.channelsDir),
+ turnsOf: diskTurnsOf(paths.channelsDir),
+ dateOf: diskDateOf(paths.channelsDir),
llm: llmConfigOf(g, paths, locals.length ? { onLog, ...(o.signal ? { signal: o.signal } : {}) } : undefined),
log: onLog,
...(o.signal ? { signal: o.signal } : {}),
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -17,6 +17,7 @@ import {
type FetchWindowsDeps,
type FetchWindowsItem,
} from "./fetchWindows";
+import { parseClipProvenance } from "../lib/clipWindow";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
@@ -421,3 +422,17 @@ test("a cached unpadded window does not cover a padded ask: it is fetched, its p
const again = await go(paths, [padded, item("v1", "/exact", 10, 20)], harness());
assert.deepEqual([again.cached.length, again.fetched.length], [2, 0]);
});
+
+test("a window of a gone recording fetched from a copy (find-copy) records which copy in its sidecar", async () => {
+ const paths = await corpus();
+ const copy = { from: "wayback" as const, url: "https://web.archive.org/web/20260125093000/https://www.youtube.com/watch?v=v1" };
+ const r = await go(paths, [{ slug: "c", id: "v1", from: 10, to: 20, webpageUrl: copy.url, copy }], harness());
+ assert.equal(r.fetched.length, 1);
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ const sidecar = JSON.parse(await readFile(path.join(clips, "10.00-20.00.json"), "utf8")) as { copy?: unknown; ytdlp?: { args: string[] } };
+ assert.deepEqual(sidecar.copy, copy);
+ // The copy's URL is what yt-dlp was given.
+ assert.equal(sidecar.ytdlp?.args.at(-1), copy.url);
+ assert.deepEqual(parseClipProvenance(sidecar)?.copy, copy);
+ assert.equal(parseClipProvenance({ requestedBy: "x", copy: { from: "elsewhere", url: copy.url } })?.copy, undefined);
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -4,6 +4,7 @@ import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
import { getSettings } from "../lib/settings";
import type { DownloadFailureClass } from "../lib/availability";
+import type { ClipCopy } from "../lib/clipWindow";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import { assertChannelTextReadable } from "../lib/channelMedia";
import { detectPlatform } from "../lib/platform";
@@ -127,6 +128,9 @@ export type FetchWindowsItem = {
pad?: number;
// The page URL when the caller has it; else resolved as the single fetch does.
webpageUrl?: string;
+ // The copy of a gone recording `webpageUrl` is (release 29 E2, find-copy):
+ // recorded in the window's provenance.
+ copy?: ClipCopy;
};
export type FetchWindowsFailureClass =
@@ -527,6 +531,7 @@ export async function fetchWindows({
reason: item.reason,
pad: item.pad,
requestedAt,
+ ...(item.copy ? { copy: item.copy } : {}),
},
cookiePolicy: resolveCookiePolicy(settings, config),
maxHeight,
diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts
@@ -194,6 +194,15 @@ export class ArchiveOrgClient {
);
}
+ // A body as text, through the same chain, gap and back-off (the Wayback
+ // CDX API answers an empty body as often as `[]`: lib/waybackClient.ts).
+ getText(url: string, accept: string, signal?: AbortSignal): Promise<string> {
+ return this.serial(async () => {
+ const res = await this.getOnce(url, accept, signal);
+ return res.text();
+ });
+ }
+
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/clipWindow.ts b/common/lib/clipWindow.ts
@@ -156,8 +156,24 @@ export type ClipProvenance = {
// a window cut from the video's saved container (release 21 D2,
// lib/savedVideoWindow-server.ts). Absent on every fetched window.
source?: ClipWindowSource;
+ // WHICH COPY a window of a gone recording was fetched from (release 29 E2,
+ // publish/findCopy.ts): a Wayback Machine capture of its page, or an
+ // archive.org mirror's file — and its URL. Absent when the window came from
+ // the recording's own page.
+ copy?: ClipCopy;
};
+export const CLIP_COPY_SOURCES = ["wayback", "archive.org"] as const;
+export type ClipCopy = { from: (typeof CLIP_COPY_SOURCES)[number]; url: string };
+
+export function coerceClipCopy(v: unknown): ClipCopy | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ if (!(CLIP_COPY_SOURCES as readonly unknown[]).includes(r.from)) return undefined;
+ if (typeof r.url !== "string" || !/^https?:\/\//.test(r.url)) return undefined;
+ return { from: r.from as ClipCopy["from"], url: r.url };
+}
+
export const CLIP_WINDOW_SOURCES = ["saved-video"] as const;
export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number];
@@ -198,6 +214,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
if ((CLIP_WINDOW_SOURCES as readonly unknown[]).includes(r.source)) {
out.source = r.source as ClipWindowSource;
}
+ const copy = coerceClipCopy(r.copy);
+ if (copy) out.copy = copy;
return out;
}
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -215,6 +215,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." },
{ name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." },
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts", doc: "The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
+ { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
{ name: "E2E_FAKE_YTDLP_CHUNK_DELAY_MS", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: delay between written chunks." },
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, VERDICTS } from "./verdicts";
+import { VERDICT_DEFAULTS, VERDICT_LABEL_MAX, VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS } from "./verdicts";
export function renderReportMarkdown(): string {
const out: string[] = [];
@@ -144,13 +144,15 @@ export function renderReportMarkdown(): string {
"characters) or a colour (`#rgb` or `#rrggbb`), each on its own.",
);
out.push("");
- out.push("| Verdict | Default label | Default colour |");
- out.push("|---|---|---|");
+ out.push("| Verdict | Means | Default label | Default colour |");
+ out.push("|---|---|---|---|");
for (const v of VERDICTS) {
const d = VERDICT_DEFAULTS[v];
- out.push(`| \`${v}\` | ${cell(d.label)} | \`${d.color}\` |`);
+ 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("");
out.push("## Iterations");
out.push("");
out.push(
diff --git a/common/lib/report/draft/bench/bench.test.ts b/common/lib/report/draft/bench/bench.test.ts
@@ -20,9 +20,20 @@ import {
runVerdictBench,
scoreBench,
VERDICT_BENCH_SYSTEM,
+ VERDICT_ANSWER_SCHEMA,
+ PROMPT_VERSION,
+ benchItemsHash,
+ compareBenchRuns,
+ markedScore,
+ stratifiedLimit,
+ turnOf,
+ type BenchAsk,
type BenchItem,
type BenchResult,
} from "./index";
+import { VERDICT_MEANINGS, VERDICT_TIE_RULE } from "../../verdicts";
+import { CLAIM_FIELD_DOCS } from "../../schema";
+import { renderReportMarkdown } from "../../docs";
import { promptEstimate } from "../../../llm/ollama";
const RULED = path.join(import.meta.dirname, "../../../../testing/draft/reports/ruled.report.json");
@@ -345,7 +356,12 @@ test("plan (the dry run): the items, the skipped, an estimate per model; nothing
try {
const plan = await planVerdictBench({ models: ["claude-sonnet-5-5", "claude-opus-5-5", "qwen3:8b"], limit: 5 }, { paths: s.paths, cuesOf });
assert.equal(plan.items.length, 5);
- assert.equal(plan.skipped.length, 1);
+ // The limit is stratified: every verdict ruled is kept; the rest are skipped, said so.
+ assert.deepEqual([...new Set(plan.items.map((i) => i.verdict))].sort(), ["CONTRADICTED", "CORROBORATED", "NOT_FOUND", "PARTLY"]);
+ assert.equal(plan.skipped.length, 3);
+ assert.equal(plan.skipped.filter((x) => x.reason === "left out by the limit").length, 2);
+ assert.equal(plan.promptVersion, PROMPT_VERSION);
+ assert.match(plan.itemsHash, /^[0-9a-f]{16}$/);
assert.deepEqual(plan.reports, ["synth-ruled"]);
const [sonnet, opus, qwen] = plan.estimate;
assert.ok(sonnet!.usd > 0 && opus!.usd > sonnet!.usd);
@@ -359,3 +375,238 @@ test("plan (the dry run): the items, the skipped, an estimate per model; nothing
await s.done();
}
});
+
+// ─── release 29 V1: bench v2 ───
+
+// A stubbed model (R6's injected ask): answers each claim from a table, and
+// records what it was asked.
+function stubAsk(answers: (model: string, id: string) => unknown, texts: Record<string, string>) {
+ const asked: { model: string; id: string; system: string; user: string; schema: any }[] = [];
+ const ask: BenchAsk = async <T,>(system: string, user: string, schema: object, model: string) => {
+ const id = texts[claimOf(user)]!;
+ asked.push({ model, id, system, user, schema });
+ const a = answers(model, id);
+ if (a instanceof Error) throw a;
+ return a as T;
+ };
+ 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 () => {
+ 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.match(VERDICT_MEANINGS.CORROBORATED, /substance/);
+ assert.match(VERDICT_MEANINGS.PARTLY, /shown .* overstated or wrong/);
+ 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.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.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();
+ try {
+ const { items } = await benchItemsOf(await benchReportsOf(s.paths), {
+ cuesOf,
+ dateOf: async (_c, id) => (id === "bread-day-01" ? "2026-01-05" : null),
+ });
+ const r02 = items.find((i) => i.claim === "r02")!;
+ assert.equal(r02.title, "Synth Kitchen — what an article says about the baker, checked");
+ assert.equal(r02.section, "The bakery");
+ const u = benchPrompt(r02).user;
+ assert.match(u, /^Report: Synth Kitchen/m);
+ assert.match(u, /^Section: The bakery$/m);
+ assert.match(u, /"the oven was fine it just ran hot" \(speaker: synth-kitchen; recorded: 2026-01-05\)/);
+ assert.match(u, /^## Bread day, 0:00 to 1:34 \(channel: synth-kitchen; recorded: 2026-01-05\)$/m);
+ assert.ok(!u.includes(r02.verdict));
+ // A local prompt stays under the 8k cap with the longer system prompt.
+ for (const it of items) assert.ok(benchPrompt(it, { capTokens: LOCAL_PROMPT_CAP }).estimate <= LOCAL_PROMPT_CAP);
+ } finally {
+ await s.done();
+ }
+});
+
+test("V1 items: the turn mode — the speaker's segments, else a pause or a >> change — bounded by the window; drops listed by reason", async () => {
+ const cues = [
+ { start: 0, end: 4, text: "hello" },
+ { start: 4.5, end: 8, text: "the oven" },
+ { start: 9, end: 12, text: "ran hot" },
+ { start: 16, end: 19, text: ">> no it did not" },
+ { start: 19.5, end: 22, text: "it was fine" },
+ ];
+ // No segments: back to the pause at 0 (none: the first cue), on until the >> change.
+ assert.deepEqual(turnOf(cues, null, { start: 5, end: 7 }, 0, 100), { from: 0, to: 12, bound: "pause" });
+ // A >> cue starts its own turn: it runs on, never back.
+ assert.deepEqual(turnOf(cues, null, { start: 17, end: 18 }, 0, 100), { from: 16, to: 22, bound: "pause" });
+ // The bound cuts a turn: `limit`.
+ assert.deepEqual(turnOf(cues, null, { start: 5, end: 7 }, 3, 10), { from: 3, to: 10, bound: "limit" });
+ // Speaker segments win: speaker 1's run around the span.
+ const segs = [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4, end: 9, speaker: 1 },
+ { start: 9, end: 13, speaker: 1 },
+ { start: 13, end: 22, speaker: 0 },
+ ];
+ 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.
+ 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.
+ r.citations.q99 = { ...r.citations.q02, id: "no-such-recording" };
+ r.sections[0].claims[1].citations = ["q02", "q99"];
+ });
+ try {
+ const reports = await benchReportsOf(s.paths);
+ const secs = await benchItemsOf(reports, { cuesOf, windowS: 60 });
+ 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.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" });
+ const r02 = turn.items.find((i) => i.claim === "r02")!;
+ assert.equal(r02.windows[0]!.bound, "limit");
+ assert.equal(r02.windows[0]!.from, 20);
+ assert.equal(r02.windows[0]!.to, 44.8);
+ // With the speaker's segments: exactly the turn.
+ const turns = await benchItemsOf(reports, {
+ cuesOf,
+ windowS: 60,
+ windowMode: "turn",
+ turnsOf: async (_c, id) => (id === "bread-day-01" ? [{ start: 0, end: 25, speaker: 0 }, { start: 25, end: 40, speaker: 1 }, { start: 40, end: 70, speaker: 0 }] : null),
+ });
+ const w = turns.items.find((i) => i.claim === "r02")!.windows[0]!;
+ assert.deepEqual([w.from, w.to, w.bound], [25, 40, "speaker"]);
+ assert.deepEqual(w.cues.map((c) => c.start), [25, 30, 35, 40]);
+ } finally {
+ await s.done();
+ }
+});
+
+test("V1 stratified limit: every verdict kept, in proportion, the rest by the largest remainder; order kept", () => {
+ const mk = (n: number, v: Verdict) => Array.from({ length: n }, (_, i) => ({ key: `${v}-${i}`, verdict: v }));
+ const items = [...mk(78, "CORROBORATED"), ...mk(58, "PARTLY"), ...mk(6, "NOT_FOUND"), ...mk(4, "CONTRADICTED"), ...mk(1, "UNTESTABLE")];
+ const { kept, left } = stratifiedLimit(items, 20);
+ assert.equal(kept.length, 20);
+ assert.equal(left.length, 127);
+ const count = (v: Verdict) => kept.filter((k) => k.verdict === v).length;
+ assert.deepEqual(VERDICTS.map(count), [10, 7, 1, 1, 1]);
+ assert.deepEqual(kept.slice(0, 2).map((k) => k.key), ["CORROBORATED-0", "CORROBORATED-1"]);
+ // Smaller than the verdicts: the rarest first.
+ assert.deepEqual(stratifiedLimit(items, 2).kept.map((k) => k.verdict), ["CONTRADICTED", "UNTESTABLE"]);
+ assert.equal(stratifiedLimit(items, 500).kept.length, 147);
+});
+
+test("V1 run: the injected ask, reason before verdict, a per-call trace; --items-from takes the exact items; a resume asks only its own models; another prompt version is refused", async () => {
+ 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 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 });
+ assert.equal(first.summary.status, "done");
+ assert.equal(asked.length, 14);
+ 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"]);
+ // 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");
+ assert.equal(trace[0].promptVersion, PROMPT_VERSION);
+ 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" });
+
+ // A run from vb-one's items: the same items, the same hash; only qwen asked.
+ asked.length = 0;
+ const two = await runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"], itemsFrom: "vb-one" }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(two.summary.itemsFrom, "vb-one");
+ assert.equal(two.summary.itemsHash, first.summary.itemsHash);
+ assert.equal(asked.length, 7);
+ assert.ok(asked.every((a) => a.model === "qwen3:8b"));
+ // Resume with Sonnet too: only Sonnet is asked; qwen's pairs are not re-asked.
+ asked.length = 0;
+ const again = await runVerdictBench({ runId: "vb-two", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(asked.length, 7);
+ assert.ok(asked.every((a) => a.model === "claude-sonnet-5-5"));
+ assert.deepEqual(again.summary.models, ["qwen3:8b", "claude-sonnet-5-5"]);
+ // A resume with qwen alone asks nothing.
+ asked.length = 0;
+ await runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(asked.length, 0);
+
+ // items-from refuses what would change the items, and a run that does not exist.
+ await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-one", limit: 3 }, { paths: s.paths, cuesOf, llm: {}, ask }), /drop the limit/);
+ await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-nope" }, { paths: s.paths, cuesOf, llm: {}, ask }), /no run "vb-nope"/);
+ // An M7 run (no prompt version) is not resumed under this one.
+ const sum = JSON.parse(await readFile(path.join(root, "vb-one", "summary.json"), "utf8"));
+ delete sum.promptVersion;
+ await writeFile(path.join(root, "vb-one", "summary.json"), JSON.stringify(sum));
+ await assert.rejects(runVerdictBench({ runId: "vb-one", models: ["qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask }), /prompt version 1, and this is version/);
+ // ... but its items are taken as they are, and fill the context M7's items lacked.
+ const m7 = (await readBenchRun(root, "vb-one"))!;
+ const bare = m7.items.map(({ title: _t, section: _s, ...rest }) => rest);
+ await writeFile(path.join(root, "vb-one", "items.jsonl"), bare.map((i) => `${JSON.stringify(i)}\n`).join(""));
+ asked.length = 0;
+ const three = await runVerdictBench({ runId: "vb-three", models: ["qwen3:8b"], itemsFrom: "vb-one" }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(three.summary.itemsHash, first.summary.itemsHash);
+ assert.match(asked[0]!.user, /^Section: /m);
+ } finally {
+ await s.done();
+ }
+});
+
+test("V1 score: not-CORROBORATED precision and recall; two runs compared; the operator's marks on disagreements", () => {
+ const items = Object.entries(TRUTH).map(([claim, verdict]) => ({ key: `r/${claim}`, verdict }));
+ const res = (model: string, said: Record<string, Verdict | null>): BenchResult[] =>
+ Object.entries(said).map(([claim, v]) => ({ key: `r/${claim}`, model, verdict: v, ...(v ? {} : { failure: "parse" as const }), ms: 1, usd: 0, inputTokens: 0, outputTokens: 0, at: "" }));
+ // Run A: PARTLY on both CORROBORATED (2 false flags), finds r02 r04 r07, misses r03 (CORROBORATED), r05 (failed).
+ const a = res("m", { r01: "PARTLY", r02: "PARTLY", r03: "CORROBORATED", r04: "CONTRADICTED", r05: null, r06: "PARTLY", r07: "NOT_FOUND" });
+ const sa = scoreBench(items, a, ["m"]).models[0]!;
+ // positives: r01 r02 r04 r06 r07 → tp r02 r04 r07 (3), fp r01 r06 (2); fn r03 r05 (2).
+ assert.deepEqual(sa.notCorroborated, { tp: 3, fp: 2, fn: 2, precision: 0.6, recall: 0.6 });
+ assert.equal(scoreBench(items, a, ["m"]).baseline.notCorroborated.recall, 0);
+ // Run B on the same items: r01 fixed, r04 broken.
+ const b = res("m", { r01: "CORROBORATED", r02: "PARTLY", r03: "CORROBORATED", r04: "PARTLY", r05: null, r06: "PARTLY", r07: "NOT_FOUND" });
+ const cmp = compareBenchRuns({ items, results: a, models: ["m"] }, { items, results: b, models: ["m", "n"] });
+ assert.equal(cmp.items, 7);
+ assert.equal(cmp.models.length, 1);
+ const m = cmp.models[0]!;
+ assert.deepEqual([m.a.agreed, m.b.agreed], [3, 3]);
+ assert.deepEqual(m.changed, [
+ { key: "r/r01", ruled: "CORROBORATED", a: "PARTLY", b: "CORROBORATED" },
+ { key: "r/r04", ruled: "CONTRADICTED", a: "CONTRADICTED", b: "PARTLY" },
+ ]);
+ assert.deepEqual([m.fixed, m.broke], [1, 1]);
+ // Marks: r06's PARTLY marked Right (the model saw what the ruling missed),
+ // r01's marked Wrong, and a stale mark (on an answer since changed) ignored.
+ const marks = {
+ m: {
+ "r/r06": { verdict: "right" as const, answer: "PARTLY" as const, at: "" },
+ "r/r01": { verdict: "wrong" as const, answer: "PARTLY" as const, at: "" },
+ "r/r02": { verdict: "right" as const, answer: "CORROBORATED" as const, at: "" },
+ },
+ };
+ const ms = markedScore(items, a, "m", marks);
+ assert.deepEqual(ms.marks, { marked: 2, right: 1, wrong: 1, precision: 0.5 });
+ assert.equal(ms.agreed, 4);
+ assert.deepEqual(ms.notCorroborated, { tp: 4, fp: 1, fn: 2, precision: 0.8, recall: 0.6667 });
+ // The hash is the items' identity: context lines do not change it.
+ assert.equal(
+ benchItemsHash([{ key: "a", verdict: "PARTLY", windows: [] }]),
+ benchItemsHash([{ key: "a", verdict: "PARTLY", windows: [], title: "t" } as any]),
+ );
+});
diff --git a/common/lib/report/draft/bench/disk.ts b/common/lib/report/draft/bench/disk.ts
@@ -0,0 +1,83 @@
+// The verdict bench's disk half (release 29 V1): what a channels tree tells
+// the items beside the cues (`diskCuesOf`, ../../convert-server.ts) — a
+// recording's speaker segments (its attribution sidecar, for the `turn` window
+// mode) and its own date (metadata.info.json's upload_date, for a quote whose
+// citation names none). Behind the text guard (lib/channelMedia.ts), as the
+// cues are: a channel whose text is not readable answers null. Reads only.
+//
+// SERVER-ONLY (node:fs).
+
+import { open } from "node:fs/promises";
+import path from "node:path";
+import { assertChannelTextReadable } from "../../../channelMedia";
+import { resolveVideoDir } from "../../../videoDir-server.mjs";
+import { isSafeChannelSegment, isSafeIdSegment } from "../../../citations/moments";
+import { loadAttribution } from "../../../attribution-server";
+import type { DateOf, SpeakerTurn, TurnsOf } from "./items";
+
+function guard(channelsDir: string) {
+ const readable = new Map<string, Promise<boolean>>();
+ return (slug: string) => {
+ let p = readable.get(slug);
+ if (!p) {
+ p = assertChannelTextReadable({ channelsDir }, slug).then(
+ () => true,
+ () => false,
+ );
+ readable.set(slug, p);
+ }
+ return p;
+ };
+}
+
+async function videoDirOf(channelsDir: string, ok: (slug: string) => Promise<boolean>, channel: string, id: string): Promise<string | null> {
+ if (!isSafeChannelSegment(channel) || !isSafeIdSegment(id)) return null;
+ if (!(await ok(channel))) return null;
+ return resolveVideoDir(channelsDir, channel, id).catch(() => null);
+}
+
+/** A recording's speaker segments from its attribution sidecar, or null. */
+export function diskTurnsOf(channelsDir: string): TurnsOf {
+ const ok = guard(channelsDir);
+ return async (channel, id) => {
+ const dir = await videoDirOf(channelsDir, ok, channel, id);
+ if (!dir) return null;
+ const rec = await loadAttribution(dir).catch(() => null);
+ if (!rec?.segments.length) return null;
+ return rec.segments.map((s): SpeakerTurn => ({ start: s.start, end: s.end, speaker: s.speaker }));
+ };
+}
+
+const UPLOAD_DATE_RE = /"upload_date":\s*"(\d{4})(\d{2})(\d{2})"/;
+const TAIL_BYTES = 8192;
+
+/**
+ * A recording's own date, `YYYY-MM-DD`, off its metadata.info.json — yt-dlp
+ * writes upload_date near the end, so the file's last 8 KB, then (a file
+ * whose date is not there) the whole file.
+ */
+export function diskDateOf(channelsDir: string): DateOf {
+ const ok = guard(channelsDir);
+ return async (channel, id) => {
+ const dir = await videoDirOf(channelsDir, ok, channel, id);
+ if (!dir) return null;
+ let fh;
+ try {
+ fh = await open(path.join(dir, "metadata.info.json"), "r");
+ const { size } = await fh.stat();
+ const tail = Buffer.alloc(Math.min(size, TAIL_BYTES));
+ await fh.read(tail, 0, tail.length, Math.max(0, size - tail.length));
+ let m = UPLOAD_DATE_RE.exec(tail.toString("utf8"));
+ if (!m && size > TAIL_BYTES) {
+ const all = Buffer.alloc(size);
+ await fh.read(all, 0, size, 0);
+ m = UPLOAD_DATE_RE.exec(all.toString("utf8"));
+ }
+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;
+ } catch {
+ return null;
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+ };
+}
diff --git a/common/lib/report/draft/bench/items.ts b/common/lib/report/draft/bench/items.ts
@@ -1,32 +1,54 @@
-// THE VERDICT BENCH'S ITEMS (release 28, M7): one per ruled fact-check claim.
+// THE VERDICT BENCH'S ITEMS (release 28 M7; release 29 V1): 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, the cited
-// quotes, and the transcript WINDOW (the cues within ±`windowS` of each cited
-// span, overlapping windows of one recording merged). Every other claim is
-// SKIPPED, with its reason, and counted.
+// 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.
+//
+// THE WINDOW MODES (V1):
+// seconds the cues within ±`windowS` of the cited span (M7's, the default)
+// turn the cited speaker's TURN: the recording's speaker segments
+// (`turnsOf`, the attribution sidecar) around the span, else the
+// cues run on until a pause of TURN_GAP_S or a `>>` speaker change —
+// bounded by ±`windowS` either way (a window's `bound` says which)
//
// The operator's `verdict` is the answer key: it is kept on the item for the
// scorer, and the prompt (./prompt.ts) never reads it. The claim's `findings`,
// `gist`, `flag` and `title` are never copied onto an item at all — they say
// what the check found.
//
+// The UNRULED mode (M8's proposals) is the same reading over the claims with
+// NO verdict: a ruled claim is skipped ("ruled by the operator").
+//
// The reports are read through the article registry (`listArticleDirs`,
// `articleFile`, `parseReport`), never by globbing the corpus; the cues through
// a `CuesOf` (the local corpus's `diskCuesOf`, or the synthetic corpus in tests).
+import { createHash } from "node:crypto";
import { readJsonFile } from "../../../jsonFile-server";
import type { Paths } from "../../../paths";
import { isSpanCitation, type Citation } from "../../../citations/schema";
import type { CuesOf } from "../../convertShared";
import { articleFile, listArticleDirs } from "../../registry";
-import type { Report } from "../../schema";
+import type { Claim, Report } from "../../schema";
import { parseReport } from "../../validate";
-import { isVerdict, type Verdict } from "../../verdicts";
+import { isVerdict, VERDICTS, type Verdict } from "../../verdicts";
export const DEFAULT_WINDOW_S = 60;
+export const WINDOW_MODES = ["seconds", "turn"] as const;
+export type WindowMode = (typeof WINDOW_MODES)[number];
+export const isWindowMode = (v: unknown): v is WindowMode => typeof v === "string" && (WINDOW_MODES as readonly string[]).includes(v);
+
+// The turn mode with no speaker segments: a pause this long between two cues
+// ends the turn.
+export const TURN_GAP_S = 2;
+
export type BenchCue = { start: number; end: number; text: string };
export type BenchQuote = {
@@ -41,6 +63,11 @@ export type BenchQuote = {
date?: string;
};
+// What ended a window: the seconds either side (`seconds`), the speaker's own
+// segments (`speaker`), a pause or a speaker change in the cues (`pause`), or
+// the ±windowS bound a turn ran into (`limit`).
+export type WindowBound = "seconds" | "speaker" | "pause" | "limit";
+
// One recording's cues around the cited spans in it.
export type BenchWindow = {
channel: string;
@@ -51,6 +78,7 @@ export type BenchWindow = {
// The cited spans in this window (for the trim: the cues nearest them stay).
cited: { start: number; end: number }[];
cues: BenchCue[];
+ bound?: WindowBound;
};
export type BenchItem = {
@@ -63,13 +91,36 @@ export type BenchItem = {
verdict: Verdict;
quotes: BenchQuote[];
windows: BenchWindow[];
+ // Context for the model (V1): the report's title and the claim's section heading.
+ title?: string;
+ section?: string;
};
+// An unruled claim, read the same way (M8's proposals): no answer key.
+export type ClaimItem = Omit<BenchItem, "verdict">;
+
export type BenchSkipped = { key: string; report: string; claim: string; reason: string };
+// A citation of a KEPT claim that gave no window, and why.
+export type BenchDropped = { key: string; citation: string; reason: string };
+
export type BenchReport = { id: string; report: Report };
-export type BenchItems = { items: BenchItem[]; skipped: BenchSkipped[] };
+export type BenchItems = { items: BenchItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[] };
+
+// A recording's speaker segments (the attribution sidecar's), or null.
+export type SpeakerTurn = { start: number; end: number; speaker: number | string };
+export type TurnsOf = (channel: string, id: string) => Promise<readonly SpeakerTurn[] | null>;
+// A recording's own date (`YYYY-MM-DD`), for a quote whose citation names none.
+export type DateOf = (channel: string, id: string) => Promise<string | null>;
+
+export type ItemOptions = {
+ cuesOf: CuesOf;
+ windowS?: number;
+ windowMode?: WindowMode;
+ turnsOf?: TurnsOf;
+ dateOf?: DateOf;
+};
export class BenchInputError extends Error {}
@@ -106,6 +157,8 @@ export async function benchReportsOf(
return out;
}
+const BOUND_RANK: Record<WindowBound, number> = { seconds: 0, speaker: 1, pause: 2, limit: 3 };
+
function mergeWindows(windows: BenchWindow[]): BenchWindow[] {
const byRecord = new Map<string, BenchWindow[]>();
for (const w of windows) {
@@ -123,6 +176,7 @@ function mergeWindows(windows: BenchWindow[]): BenchWindow[] {
const seen = new Set(cur.cues.map((c) => `${c.start}`));
for (const c of w.cues) if (!seen.has(`${c.start}`)) cur.cues.push(c);
cur.cues.sort((a, b) => a.start - b.start);
+ if (w.bound && (!cur.bound || BOUND_RANK[w.bound] > BOUND_RANK[cur.bound])) cur.bound = w.bound;
} else {
if (cur) out.push(cur);
cur = { ...w, cited: [...w.cited], cues: [...w.cues] };
@@ -133,77 +187,267 @@ function mergeWindows(windows: BenchWindow[]): BenchWindow[] {
return out;
}
-// The items of one report: its ruled claims with a span citation that has cues.
-export async function benchItemsOfReport(
- r: BenchReport,
- o: { cuesOf: CuesOf; windowS?: number },
-): Promise<BenchItems> {
+const overlaps = (a: { start: number; end: number }, from: number, to: number) => a.end >= from && a.start <= to;
+const changesSpeaker = (text: string) => /^\s*>>/.test(text);
+
+/**
+ * The cited speaker's turn around `span`, bounded by [lo, hi]: the speaker's
+ * run of segments when `turns` has one over the span, else the cues run on
+ * until a pause of TURN_GAP_S or a `>>` speaker change. The cited span is
+ * always inside; a turn cut by the bound says `limit`. Pure.
+ */
+export function turnOf(
+ cues: readonly BenchCue[],
+ turns: readonly SpeakerTurn[] | null,
+ span: { start: number; end: number },
+ lo: number,
+ hi: number,
+): { from: number; to: number; bound: WindowBound } {
+ const clip = (from: number, to: number, bound: WindowBound) => ({
+ from: Math.max(lo, Math.min(from, span.start)),
+ to: Math.min(hi, Math.max(to, span.end)),
+ bound: from < lo || to > hi ? ("limit" as const) : bound,
+ });
+ const segs = (turns ?? []).filter((s) => Number.isFinite(s.start) && Number.isFinite(s.end) && s.end > s.start).slice().sort((a, b) => a.start - b.start);
+ let best = -1;
+ let most = 0;
+ segs.forEach((s, i) => {
+ const o = Math.min(s.end, span.end) - Math.max(s.start, span.start);
+ if (o > most) {
+ most = o;
+ best = i;
+ }
+ });
+ if (best >= 0) {
+ const who = segs[best]!.speaker;
+ let a = best;
+ let b = best;
+ while (a > 0 && segs[a - 1]!.speaker === who) a--;
+ while (b < segs.length - 1 && segs[b + 1]!.speaker === who) b++;
+ return clip(segs[a]!.start, segs[b]!.end, "speaker");
+ }
+ const sorted = cues.slice().sort((x, y) => x.start - y.start);
+ const hit = sorted.flatMap((c, i) => (overlaps(c, span.start, span.end) ? [i] : []));
+ if (!hit.length) return clip(span.start, span.end, "pause");
+ let a = hit[0]!;
+ let b = hit[hit.length - 1]!;
+ // Back: the cue before joins while there is no pause and the turn did not start here.
+ while (a > 0 && !changesSpeaker(sorted[a]!.text) && sorted[a]!.start - sorted[a - 1]!.end < TURN_GAP_S) a--;
+ // On: the next cue joins while there is no pause and it does not change the speaker.
+ while (b < sorted.length - 1 && !changesSpeaker(sorted[b + 1]!.text) && sorted[b + 1]!.start - sorted[b]!.end < TURN_GAP_S) b++;
+ return clip(sorted[a]!.start, sorted[b]!.end, "pause");
+}
+
+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).
+async function readClaim(r: BenchReport, sectionTitle: string, claim: Claim, o: ItemOptions): Promise<ReadClaim> {
const windowS = o.windowS ?? DEFAULT_WINDOW_S;
+ const mode = o.windowMode ?? "seconds";
+ const key = `${r.id}/${claim.id}`;
+ const citations = (r.report.citations ?? {}) as Record<string, Citation>;
+ const dropped: BenchDropped[] = [];
+ const ids = claim.citations ?? [];
+ if (!ids.length) return { ok: false, reason: "no citation" };
+ const spans: (readonly [string, Citation])[] = [];
+ 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 spans.push([id, c]);
+ }
+ if (!spans.length) return { ok: false, reason: "no video or audio citation" };
+ const quotes: BenchQuote[] = [];
+ const windows: BenchWindow[] = [];
+ for (const [cid, c] of spans) {
+ if (!isSpanCitation(c)) continue;
+ const cues = await o.cuesOf(c.channel, c.id).catch(() => null);
+ if (!cues || !cues.length) {
+ dropped.push({ key, citation: cid, reason: "the recording has no cues" });
+ continue;
+ }
+ const lo = Math.max(0, c.start - windowS);
+ const hi = c.end + windowS;
+ let from = lo;
+ let to = hi;
+ let bound: WindowBound = "seconds";
+ if (mode === "turn") {
+ const turns = o.turnsOf ? await o.turnsOf(c.channel, c.id).catch(() => null) : null;
+ ({ from, to, bound } = turnOf(cues, turns, { start: c.start, end: c.end }, lo, hi));
+ }
+ const inWindow = cues.filter((q) => overlaps(q, from, to)).map((q) => ({ start: q.start, end: q.end, text: q.text }));
+ if (!inWindow.length) {
+ dropped.push({ key, citation: cid, reason: "no cues around the cited seconds" });
+ continue;
+ }
+ const date = c.date ?? (o.dateOf ? await o.dateOf(c.channel, c.id).catch(() => null) : null);
+ quotes.push({
+ citation: cid,
+ channel: c.channel,
+ id: c.id,
+ start: c.start,
+ end: c.end,
+ quote: c.quote,
+ ...(c.label ? { label: c.label } : {}),
+ ...(c.speaker ? { speaker: c.speaker } : {}),
+ ...(date ? { date } : {}),
+ });
+ windows.push({ channel: c.channel, id: c.id, ...(c.label ? { label: c.label } : {}), from, to, cited: [{ start: c.start, end: c.end }], cues: inWindow, bound });
+ }
+ if (!quotes.length) return { ok: false, reason: "no cited recording has cues around the cited seconds" };
+ return {
+ ok: true,
+ item: {
+ key,
+ report: r.id,
+ claim: claim.id,
+ text: claim.text,
+ quotes,
+ windows: mergeWindows(windows),
+ ...(r.report.title ? { title: r.report.title } : {}),
+ ...(sectionTitle ? { section: sectionTitle } : {}),
+ },
+ dropped,
+ };
+}
+
+// The items of one report: its ruled claims with a span citation that has cues.
+export async function benchItemsOfReport(r: BenchReport, o: ItemOptions): Promise<BenchItems> {
const items: BenchItem[] = [];
const skipped: BenchSkipped[] = [];
- const citations = (r.report.citations ?? {}) as Record<string, Citation>;
+ const dropped: BenchDropped[] = [];
for (const section of r.report.sections) {
for (const claim of section.claims ?? []) {
const key = `${r.id}/${claim.id}`;
- const skip = (reason: string) => skipped.push({ key, report: r.id, claim: claim.id, reason });
if (!isVerdict(claim.verdict)) {
- skip("no operator verdict");
+ skipped.push({ key, report: r.id, claim: claim.id, reason: "no operator verdict" });
continue;
}
- const ids = claim.citations ?? [];
- if (!ids.length) {
- skip("no citation");
+ const got = await readClaim(r, section.title, claim, o);
+ if (!got.ok) {
+ skipped.push({ key, report: r.id, claim: claim.id, reason: got.reason });
continue;
}
- const spans = ids.map((id) => [id, citations[id]] as const).filter((e): e is readonly [string, Citation] => !!e[1] && isSpanCitation(e[1]));
- if (!spans.length) {
- skip("no video or audio citation");
+ dropped.push(...got.dropped);
+ items.push({ ...got.item, verdict: claim.verdict });
+ }
+ }
+ return { items, skipped, dropped };
+}
+
+// The UNRULED claims of one report (M8's proposals): every claim with no
+// verdict, read as a bench item is; a ruled claim is skipped. `claims` keeps
+// only those ids.
+export async function unruledItemsOfReport(
+ r: BenchReport,
+ o: ItemOptions & { claims?: readonly string[] },
+): Promise<{ items: ClaimItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[] }> {
+ const items: ClaimItem[] = [];
+ const skipped: BenchSkipped[] = [];
+ const dropped: BenchDropped[] = [];
+ const only = o.claims?.length ? new Set(o.claims) : null;
+ for (const section of r.report.sections) {
+ for (const claim of section.claims ?? []) {
+ if (only && !only.has(claim.id)) continue;
+ const key = `${r.id}/${claim.id}`;
+ if (isVerdict(claim.verdict)) {
+ skipped.push({ key, report: r.id, claim: claim.id, reason: "ruled by the operator" });
continue;
}
- const quotes: BenchQuote[] = [];
- const windows: BenchWindow[] = [];
- for (const [cid, c] of spans) {
- if (!isSpanCitation(c)) continue;
- const cues = await o.cuesOf(c.channel, c.id).catch(() => null);
- if (!cues || !cues.length) continue;
- const from = Math.max(0, c.start - windowS);
- const to = c.end + windowS;
- const inWindow = cues.filter((q) => q.end >= from && q.start <= to).map((q) => ({ start: q.start, end: q.end, text: q.text }));
- if (!inWindow.length) continue;
- quotes.push({
- citation: cid,
- channel: c.channel,
- id: c.id,
- start: c.start,
- end: c.end,
- quote: c.quote,
- ...(c.label ? { label: c.label } : {}),
- ...(c.speaker ? { speaker: c.speaker } : {}),
- ...(c.date ? { date: c.date } : {}),
- });
- windows.push({ channel: c.channel, id: c.id, ...(c.label ? { label: c.label } : {}), from, to, cited: [{ start: c.start, end: c.end }], cues: inWindow });
- }
- if (!quotes.length) {
- skip("no cited recording has cues around the cited seconds");
+ const got = await readClaim(r, section.title, claim, o);
+ if (!got.ok) {
+ skipped.push({ key, report: r.id, claim: claim.id, reason: got.reason });
continue;
}
- items.push({ key, report: r.id, claim: claim.id, text: claim.text, verdict: claim.verdict, quotes, windows: mergeWindows(windows) });
+ dropped.push(...got.dropped);
+ items.push(got.item);
+ }
+ }
+ return { items, skipped, dropped };
+}
+
+export const LIMIT_REASON = "left out by the limit";
+
+/**
+ * A stratified `limit`: the items kept by the operator's verdict in proportion
+ * to how many were ruled each way, at least one of each verdict there is (the
+ * rarest first, when the limit is smaller than the verdicts), the rest by the
+ * largest remainder. Within a verdict the first items are kept; the kept ones
+ * stay in their order. Pure.
+ */
+export function stratifiedLimit<T extends { verdict: Verdict }>(items: readonly T[], limit: number): { kept: T[]; left: T[] } {
+ if (limit >= items.length) return { kept: [...items], left: [] };
+ const by = new Map<Verdict, T[]>();
+ for (const it of items) by.set(it.verdict, [...(by.get(it.verdict) ?? []), it]);
+ const size = (v: Verdict) => by.get(v)!.length;
+ const classes = [...by.keys()].sort((a, b) => size(a) - size(b) || VERDICTS.indexOf(a) - VERDICTS.indexOf(b));
+ const take = new Map<Verdict, number>(classes.map((v) => [v, 0]));
+ let left = limit;
+ for (const v of classes) {
+ if (left <= 0) break;
+ take.set(v, 1);
+ left--;
+ }
+ if (left > 0) {
+ const share = classes.map((v) => {
+ const want = (limit * size(v)) / items.length;
+ return { v, want, rem: want - Math.floor(want) };
+ });
+ for (const s of share) {
+ const e = Math.min(left, Math.max(0, Math.min(size(s.v), Math.floor(s.want)) - take.get(s.v)!));
+ take.set(s.v, take.get(s.v)! + e);
+ left -= e;
+ }
+ const order = share.slice().sort((a, b) => b.rem - a.rem || size(b.v) - size(a.v));
+ while (left > 0) {
+ let moved = false;
+ for (const s of order) {
+ if (left <= 0) break;
+ if (take.get(s.v)! < size(s.v)) {
+ take.set(s.v, take.get(s.v)! + 1);
+ left--;
+ moved = true;
+ }
+ }
+ if (!moved) break;
}
}
- return { items, skipped };
+ const keep = new Set<T>();
+ for (const v of classes) for (const it of by.get(v)!.slice(0, take.get(v)!)) keep.add(it);
+ 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 the first n.
-export async function benchItemsOf(
- reports: readonly BenchReport[],
- o: { cuesOf: CuesOf; windowS?: number; limit?: number },
-): Promise<BenchItems> {
+// 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> {
const items: BenchItem[] = [];
const skipped: BenchSkipped[] = [];
+ const dropped: BenchDropped[] = [];
for (const r of reports) {
const got = await benchItemsOfReport(r, o);
items.push(...got.items);
skipped.push(...got.skipped);
+ dropped.push(...got.dropped);
}
- return { items: o.limit !== undefined && o.limit >= 0 ? items.slice(0, o.limit) : items, skipped };
+ if (o.limit === undefined || o.limit < 0 || o.limit >= items.length) return { items, skipped, dropped };
+ const { kept, left } = stratifiedLimit(items, o.limit);
+ const keptKeys = new Set(kept.map((i) => i.key));
+ return {
+ items: kept,
+ skipped: [...skipped, ...left.map((i) => ({ key: i.key, report: i.report, claim: i.claim, reason: LIMIT_REASON }))],
+ dropped: dropped.filter((d) => keptKeys.has(d.key)),
+ };
+}
+
+/**
+ * The identity of a run's items, so two runs can be said to be over the SAME
+ * items: each item's key, the operator's verdict and its windows (recording,
+ * from, to, how many cues) — 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" | "verdict" | "windows">[]): string {
+ const canon = items
+ .map((i) => ({ k: i.key, v: i.verdict, w: i.windows.map((w) => [w.channel, w.id, w.from, w.to, w.cues.length]) }))
+ .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,51 +1,66 @@
-// THE VERDICT BENCH'S PROMPT (release 28, M7): one claim per call.
+// THE VERDICT BENCH'S PROMPT (release 28 M7; release 29 V1): one claim per call.
//
-// Q0: the system prompt is rules only — what each verdict means, 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. 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
-// and the cited quotes are never trimmed.
+// 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.
//
-// The prompt reads an item's claim text, its quotes and its windows — never
+// 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.
+//
+// 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).
-import { VERDICTS } from "../../verdicts";
+import { VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS } from "../../verdicts";
import { PROMPT_CAP_TOKENS, promptEstimate } from "../../../llm/ollama";
import type { BenchItem, BenchWindow } from "./items";
+export const PROMPT_VERSION = "2";
+// The version a run with no `promptVersion` was made with (release 28 M7).
+export const M7_PROMPT_VERSION = "1";
+
export const REASON_MAX = 300;
export const VERDICT_ANSWER_SCHEMA = {
type: "object",
properties: {
- verdict: { type: "string", enum: [...VERDICTS], description: "The ruling on the claim." },
reason: {
type: "string",
- description: `Why, in one or two plain sentences of at most ${REASON_MAX} characters, naming what the transcript shows.`,
+ description: `First: what the transcript 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: ["verdict", "reason"],
+ required: ["reason", "verdict"],
} as const;
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 are shown the claim, the lines it cites, 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), and the transcript around each cited line (each line stamped with its time in the recording).",
"",
"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.",
"- 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.",
"",
"The verdicts:",
- "- CORROBORATED: the transcript shows the claim is true as stated.",
- "- PARTLY: the transcript supports part of the claim, and another part is unsupported, overstated or wrong.",
- "- CONTRADICTED: the transcript shows the opposite of the claim, or something that cannot be true at the same time as it.",
- "- NOT_FOUND: the claim could be checked against what was said, and the transcript shown does not contain it — 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.",
+ ...VERDICTS.map((v) => `- ${v}: ${VERDICT_MEANINGS[v]}`),
+ `- ${VERDICT_TIE_RULE}`,
"",
- `Give the verdict and a reason of at most ${REASON_MAX} characters that names what the transcript says.`,
+ `The reason is at most ${REASON_MAX} characters.`,
].join("\n");
const stamp = (s: number) => {
@@ -56,18 +71,23 @@ const stamp = (s: number) => {
return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
};
-type Prompted = Pick<BenchItem, "text" | "quotes" | "windows">;
+type Prompted = Pick<BenchItem, "text" | "quotes" | "windows" | "title" | "section">;
function render(item: Prompted, windows: BenchWindow[]): string {
- const lines: string[] = [`Claim: ${item.text}`, "", "Cited lines:"];
+ const lines: string[] = [];
+ if (item.title) lines.push(`Report: ${item.title}`);
+ if (item.section) lines.push(`Section: ${item.section}`);
+ lines.push(`Claim: ${item.text}`, "", "Cited lines:");
+ const said = (q: Prompted["quotes"][number]) => [`speaker: ${q.speaker ?? q.channel}`, q.date ? `recorded: ${q.date}` : ""].filter(Boolean).join("; ");
for (const q of item.quotes) {
const where = [q.label, stamp(q.start)].filter(Boolean).join(", ");
- const who = [q.speaker ? `speaker: ${q.speaker}` : "", q.date ? `date: ${q.date}` : ""].filter(Boolean).join("; ");
- lines.push(`- [${where}] "${q.quote}"${who ? ` (${who})` : ""}`);
+ lines.push(`- [${where}] "${q.quote}" (${said(q)})`);
}
lines.push("", "Transcript:");
windows.forEach((w, i) => {
- lines.push("", `## ${w.label ?? `Recording ${i + 1}`}, ${stamp(w.from)} to ${stamp(w.to)}`);
+ const q = item.quotes.find((x) => x.channel === w.channel && x.id === w.id);
+ const of = [`channel: ${w.channel}`, q?.date ? `recorded: ${q.date}` : ""].filter(Boolean).join("; ");
+ lines.push("", `## ${w.label ?? `Recording ${i + 1}`}, ${stamp(w.from)} to ${stamp(w.to)} (${of})`);
if (!w.cues.length) lines.push("(trimmed to fit)");
for (const c of w.cues) lines.push(`[${stamp(c.start)}] ${c.text}`);
});
diff --git a/common/lib/report/draft/bench/run.ts b/common/lib/report/draft/bench/run.ts
@@ -1,14 +1,23 @@
-// THE VERDICT BENCH (release 28, M7): can a model propose a fact-check verdict
-// well enough to be worth an operator's review?
+// THE VERDICT BENCH (release 28 M7; release 29 V1): can a model propose a
+// fact-check verdict well enough to be worth an operator's review?
//
-// `planVerdictBench` reads only: the items, the skipped claims, and an
-// estimate of what each model would cost (the `--dry`). `runVerdictBench`
-// asks each model about each item, one claim per call — `structuredAnswer`
-// against {verdict, reason} — writes every answer as it lands, and scores the
+// `planVerdictBench` reads only: the items, the skipped claims, the dropped
+// citations, and an estimate of what each model would cost (the `--dry`).
+// `runVerdictBench` asks each model about each item, one claim per call —
+// `structuredAnswer` against {reason, verdict}, or the injected `ask` (tests,
+// R6's shape) — writes every answer as it lands, traces every call
+// (trace.jsonl: the prompt the model saw and its raw answer), and scores the
// run (./score.ts). The calls are SEQUENTIAL (API and local alike; a local
// model's GPU turn is the caller's `llm` config — the editor's job passes the
// GPU arbiter's gated fetch).
//
+// THE ITEMS: read from the registry's fact-checks (./items.ts: the window in
+// seconds or the speaker's turn, a stratified `limit`), or — `itemsFrom` — the
+// EXACT items of an earlier run (its keys, rulings, quotes and windows; the
+// context lines a run before V1 lacked are filled from the registry, which
+// does not change the items' hash). The run records the prompt's version and
+// its items' hash, so two runs can be compared on the same items.
+//
// THE CAP: `maxUsd` (default 5) for the whole run, resumed spend included,
// checked before each API call against the spend so far plus that call's
// estimate — past it the run stops `capped` with what it did. A model with
@@ -17,7 +26,10 @@
//
// RESUME: a run id whose directory exists continues it — its items are the
// stored ones, and each (item, model) pair already ANSWERED is skipped; a
-// failed one is asked again.
+// failed one is asked again. Only THIS invocation's models are asked (a
+// qwen-only re-run never re-asks an API model's pairs); the summary keeps
+// every model the run has asked. A resume under another PROMPT_VERSION, or
+// with `itemsFrom` naming other items, is REFUSED: start a new run.
import { mkdir } from "node:fs/promises";
import type { Paths } from "../../../paths";
@@ -26,14 +38,29 @@ import { ApiKeyError } from "../../../llm/anthropic";
import { CHARS_PER_TOKEN } from "../../../llm/ollama";
import type { CuesOf } from "../../convertShared";
import { isVerdict } from "../../verdicts";
-import { benchItemsOf, benchReportsOf, BenchInputError, DEFAULT_WINDOW_S, type BenchItem, type BenchSkipped } from "./items";
-import { benchPrompt, LOCAL_PROMPT_CAP, REASON_MAX, VERDICT_ANSWER_SCHEMA } from "./prompt";
+import {
+ benchItemsHash,
+ benchItemsOf,
+ benchReportsOf,
+ BenchInputError,
+ DEFAULT_WINDOW_S,
+ isWindowMode,
+ type BenchDropped,
+ type BenchItem,
+ type BenchSkipped,
+ type DateOf,
+ 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 { scoreBench, type BenchResult } from "./score";
import {
+ appendBenchTrace,
BENCH_FORMAT,
BENCH_VERSION,
benchRootOf,
benchRunDir,
+ isBenchRunId,
newBenchRunId,
readBenchRun,
writeBenchItems,
@@ -61,17 +88,30 @@ export type BenchOptions = {
reports?: string[];
models: string[];
windowS?: number;
+ windowMode?: WindowMode;
maxUsd?: number;
+ // A stratified sample of this many items (by the operator's verdict).
limit?: number;
+ // The exact items of this earlier run (no reports, window or limit with it).
+ itemsFrom?: string;
};
+// The model, injected (R6's shape; tests): a structured answer to the prompt.
+export type BenchAsk = <T>(system: string, user: string, schema: object, model: string) => Promise<T>;
+
export type BenchDeps = {
paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "generationUsageFile">;
// Where runs live (default `.generation/bench/verdicts/`, ./store.ts).
root?: string;
cuesOf: CuesOf;
+ // The turn mode's speaker segments, and a recording's own date.
+ turnsOf?: TurnsOf;
+ dateOf?: DateOf;
// The providers' config (the editor's job gates a local model's calls on the GPU).
llm: LlmConfig;
+ // The model, stubbed (tests): replaces structuredAnswer (and its Meter: an
+ // injected ask costs nothing here).
+ ask?: BenchAsk;
log?: (line: string) => void;
signal?: AbortSignal;
now?: () => Date;
@@ -84,13 +124,20 @@ export type BenchModelEstimate = { model: string; provider: "api" | "local"; cal
export type BenchPlan = {
items: BenchItem[];
skipped: BenchSkipped[];
+ dropped: BenchDropped[];
reports: string[];
windowS: number;
+ windowMode: WindowMode;
+ promptVersion: string;
+ itemsHash: string;
+ itemsFrom?: string;
estimate: BenchModelEstimate[];
estimateUsd: number;
};
-export function validateBenchOptions(o: BenchOptions): { models: string[]; windowS: number; maxUsd: number; limit?: number } {
+export type ValidBenchOptions = { models: string[]; windowS: number; windowMode: WindowMode; maxUsd: number; limit?: number; itemsFrom?: string };
+
+export function validateBenchOptions(o: BenchOptions): ValidBenchOptions {
const models = [...new Set((o.models ?? []).map((m) => m.trim()).filter(Boolean))];
if (!models.length) throw new BenchInputError("name at least one model (--models a,b,c)");
for (const m of models) {
@@ -98,11 +145,24 @@ export function validateBenchOptions(o: BenchOptions): { models: string[]; windo
}
const windowS = o.windowS ?? DEFAULT_WINDOW_S;
if (!Number.isFinite(windowS) || windowS < 0 || windowS > 600) throw new BenchInputError("the window is 0 to 600 seconds");
+ if (o.windowMode !== undefined && !isWindowMode(o.windowMode)) throw new BenchInputError(`the window mode is "seconds" or "turn"`);
const maxUsd = o.maxUsd ?? DEFAULT_BENCH_MAX_USD;
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");
- return { models, windowS, maxUsd, ...(o.limit !== undefined ? { limit: o.limit } : {}) };
+ 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);
+ if (also.length) throw new BenchInputError(`items-from takes ${o.itemsFrom}'s items as they are: drop the ${also.join(", ")}`);
+ }
+ return {
+ models,
+ windowS,
+ windowMode: o.windowMode ?? "seconds",
+ maxUsd,
+ ...(o.limit !== undefined ? { limit: o.limit } : {}),
+ ...(o.itemsFrom !== undefined ? { itemsFrom: o.itemsFrom } : {}),
+ };
}
// What one call to `model` about `item` would cost, by the prompt's size.
@@ -130,17 +190,100 @@ function estimateOf(items: readonly BenchItem[], models: readonly string[], loca
});
}
-// The dry run: the items, the skipped claims and the estimate. Reads only.
-export async function planVerdictBench(o: BenchOptions, deps: Pick<BenchDeps, "paths" | "cuesOf" | "localCapTokens">): Promise<BenchPlan> {
- const v = validateBenchOptions(o);
+type ItemSet = {
+ items: BenchItem[];
+ skipped: BenchSkipped[];
+ dropped: BenchDropped[];
+ reports: string[];
+ windowS: number;
+ windowMode: WindowMode;
+ limit?: number;
+ itemsFrom?: string;
+};
+
+// The context lines an item made before V1 lacks (the report's title, the
+// claim's section heading, a quote's recording date), filled from the registry
+// as it is now. The items' identity (benchItemsHash) does not change.
+async function withContext(items: BenchItem[], deps: Pick<BenchDeps, "paths" | "dateOf">): Promise<BenchItem[]> {
+ const reports = new Map<string, Awaited<ReturnType<typeof benchReportsOf>>[number] | null>();
+ const out: BenchItem[] = [];
+ for (const it of items) {
+ let next = it;
+ if (it.title === undefined || it.section === undefined) {
+ if (!reports.has(it.report)) reports.set(it.report, (await benchReportsOf(deps.paths, [it.report]).catch(() => []))[0] ?? null);
+ const r = reports.get(it.report);
+ const section = r?.report.sections.find((s) => (s.claims ?? []).some((c) => c.id === it.claim));
+ next = {
+ ...next,
+ ...(it.title === undefined && r?.report.title ? { title: r.report.title } : {}),
+ ...(it.section === undefined && section?.title ? { section: section.title } : {}),
+ };
+ }
+ if (deps.dateOf && next.quotes.some((q) => !q.date)) {
+ const quotes = [];
+ for (const q of next.quotes) {
+ const date = q.date ?? (await deps.dateOf(q.channel, q.id).catch(() => null));
+ quotes.push(date ? { ...q, date } : q);
+ }
+ next = { ...next, quotes };
+ }
+ out.push(next);
+ }
+ return out;
+}
+
+async function itemSetOf(v: ValidBenchOptions, o: BenchOptions, deps: Pick<BenchDeps, "paths" | "cuesOf" | "turnsOf" | "dateOf" | "root">): Promise<ItemSet> {
+ if (v.itemsFrom) {
+ const root = deps.root ?? benchRootOf(deps.paths);
+ const src = await readBenchRun(root, v.itemsFrom);
+ if (!src) throw new BenchInputError(`no run "${v.itemsFrom}" to take the items from`);
+ return {
+ items: await withContext(src.items, deps),
+ skipped: src.summary.skipped,
+ dropped: src.summary.dropped ?? [],
+ reports: src.summary.reports,
+ windowS: src.summary.windowS,
+ windowMode: src.summary.windowMode ?? "seconds",
+ ...(src.summary.limit !== undefined ? { limit: src.summary.limit } : {}),
+ itemsFrom: v.itemsFrom,
+ };
+ }
const reports = await benchReportsOf(deps.paths, o.reports);
- const { items, skipped } = await benchItemsOf(reports, { cuesOf: deps.cuesOf, windowS: v.windowS, ...(v.limit ? { limit: v.limit } : {}) });
- const estimate = estimateOf(items, v.models, deps.localCapTokens);
+ const got = await benchItemsOf(reports, {
+ cuesOf: deps.cuesOf,
+ windowS: v.windowS,
+ windowMode: v.windowMode,
+ ...(deps.turnsOf ? { turnsOf: deps.turnsOf } : {}),
+ ...(deps.dateOf ? { dateOf: deps.dateOf } : {}),
+ ...(v.limit ? { limit: v.limit } : {}),
+ });
return {
- items,
- skipped,
- reports: reports.map((r) => r.id),
+ ...got,
+ reports: o.reports?.length ? [...new Set(o.reports)] : [],
windowS: v.windowS,
+ windowMode: v.windowMode,
+ ...(v.limit !== undefined ? { limit: v.limit } : {}),
+ // (planVerdictBench names the reports it read; a run records what was asked.)
+ };
+}
+
+// The dry run: the items, the skipped claims, the dropped citations and the
+// estimate. Reads only.
+export async function planVerdictBench(o: BenchOptions, deps: Pick<BenchDeps, "paths" | "cuesOf" | "turnsOf" | "dateOf" | "localCapTokens" | "root">): Promise<BenchPlan> {
+ const v = validateBenchOptions(o);
+ const set = await itemSetOf(v, o, deps);
+ const estimate = estimateOf(set.items, v.models, deps.localCapTokens);
+ const reports = v.itemsFrom ? [...new Set(set.items.map((i) => i.report))] : (await benchReportsOf(deps.paths, o.reports)).map((r) => r.id);
+ return {
+ items: set.items,
+ skipped: set.skipped,
+ dropped: set.dropped,
+ reports,
+ windowS: set.windowS,
+ windowMode: set.windowMode,
+ promptVersion: PROMPT_VERSION,
+ itemsHash: benchItemsHash(set.items),
+ ...(set.itemsFrom ? { itemsFrom: set.itemsFrom } : {}),
estimate,
estimateUsd: Math.round(estimate.reduce((s, e) => s + e.usd, 0) * 10_000) / 10_000,
};
@@ -160,43 +303,64 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
const id = o.runId ?? newBenchRunId(now());
const dir = benchRunDir(root, id);
const localCap = deps.localCapTokens ?? LOCAL_PROMPT_CAP;
+ if (v.itemsFrom === id) throw new BenchInputError(`a run cannot take its items from itself: name the new run`);
// A new run, or the stored one continued.
const prior = await readBenchRun(root, id);
- let items: BenchItem[];
- let skipped: BenchSkipped[];
+ let set: ItemSet;
let results: BenchResult[];
let models: string[];
- let reportsAsked: string[];
let createdAt: string;
+ let itemsHash: string;
if (prior) {
const s = prior.summary;
+ const was = s.promptVersion ?? M7_PROMPT_VERSION;
+ if (was !== PROMPT_VERSION) {
+ throw new BenchInputError(`run ${id} was asked with prompt version ${was}, and this is version ${PROMPT_VERSION}: start a new run (--items-from ${id} keeps its items)`);
+ }
if (o.windowS !== undefined && o.windowS !== s.windowS) {
throw new BenchInputError(`run ${id} was made with a ${s.windowS} s window: drop the window, or start a new run`);
}
+ if (o.windowMode !== undefined && o.windowMode !== (s.windowMode ?? "seconds")) {
+ throw new BenchInputError(`run ${id} was made with the ${s.windowMode ?? "seconds"} window mode: drop the mode, 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`);
}
- items = prior.items;
- skipped = s.skipped;
+ itemsHash = s.itemsHash ?? benchItemsHash(prior.items);
+ if (v.itemsFrom) {
+ const src = await readBenchRun(root, v.itemsFrom);
+ if (!src) throw new BenchInputError(`no run "${v.itemsFrom}" to take the items from`);
+ const theirs = src.summary.itemsHash ?? benchItemsHash(src.items);
+ if (theirs !== itemsHash) throw new BenchInputError(`run ${id} is over other items than ${v.itemsFrom}'s: start a new run`);
+ }
+ set = {
+ items: prior.items,
+ skipped: s.skipped,
+ dropped: s.dropped ?? [],
+ reports: s.reports,
+ windowS: s.windowS,
+ windowMode: s.windowMode ?? "seconds",
+ ...(s.limit !== undefined ? { limit: s.limit } : {}),
+ ...(s.itemsFrom ? { itemsFrom: s.itemsFrom } : {}),
+ };
results = prior.results;
models = [...s.models, ...v.models.filter((m) => !s.models.includes(m))];
- reportsAsked = s.reports;
createdAt = s.createdAt;
- log(`continuing run ${id}: ${items.length} items, ${results.filter((r) => r.verdict !== null).length} answers on disk`);
+ log(`continuing run ${id}: ${set.items.length} items, ${results.filter((r) => r.verdict !== null).length} answers on disk; asking ${v.models.join(", ")}`);
} else {
- const reports = await benchReportsOf(deps.paths, o.reports);
- const got = await benchItemsOf(reports, { cuesOf: deps.cuesOf, windowS: v.windowS, ...(v.limit ? { limit: v.limit } : {}) });
- items = got.items;
- skipped = got.skipped;
+ set = await itemSetOf(v, o, { ...deps, root });
+ itemsHash = benchItemsHash(set.items);
results = [];
models = v.models;
- reportsAsked = o.reports?.length ? [...new Set(o.reports)] : [];
createdAt = now().toISOString();
await mkdir(dir, { recursive: true });
- await writeBenchItems(dir, items);
- log(`run ${id}: ${items.length} items from ${reports.length} fact-check(s), ${skipped.length} claims skipped`);
+ await writeBenchItems(dir, set.items);
+ log(
+ `run ${id}: ${set.items.length} items${set.itemsFrom ? ` from run ${set.itemsFrom}` : ""}, ${set.skipped.length} claims skipped, ${set.dropped.length} citations dropped; prompt version ${PROMPT_VERSION}, items ${itemsHash}`,
+ );
}
+ const items = set.items;
const priorSpend = round6(results.reduce((s, r) => s + r.usd, 0));
const meter = new Meter();
@@ -211,13 +375,18 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
status,
...(stopped.length ? { stopped: [...stopped] } : {}),
models,
- windowS: prior?.summary.windowS ?? v.windowS,
+ windowS: set.windowS,
+ windowMode: set.windowMode,
+ promptVersion: PROMPT_VERSION,
+ itemsHash,
+ ...(set.itemsFrom ? { itemsFrom: set.itemsFrom } : {}),
maxUsd: v.maxUsd,
- reports: reportsAsked,
- ...(prior?.summary.limit !== undefined ? { limit: prior.summary.limit } : v.limit !== undefined ? { limit: v.limit } : {}),
+ reports: set.reports,
+ ...(set.limit !== undefined ? { limit: set.limit } : {}),
spentUsd: round6(priorSpend + meter.usd),
items: items.length,
- skipped,
+ skipped: set.skipped,
+ dropped: set.dropped,
score: scoreBench(items, results, models),
});
const save = async () => {
@@ -229,11 +398,27 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
if (at >= 0) results[at] = r;
else results.push(r);
};
+ let traceBroken = false;
+ const trace = async (line: Record<string, unknown>) => {
+ try {
+ await appendBenchTrace(dir, { at: now().toISOString(), ...line });
+ } catch (e) {
+ if (!traceBroken) log(`trace not kept: ${(e as Error).message}`);
+ traceBroken = true;
+ }
+ };
await save();
+ await trace({ t: "start", run: id, promptVersion: PROMPT_VERSION, itemsHash, models: v.models, system: VERDICT_BENCH_SYSTEM, schema: VERDICT_ANSWER_SCHEMA });
+
+ const ask: BenchAsk =
+ deps.ask ??
+ (<T,>(system: string, user: string, schema: object, model: string) =>
+ structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens: MAX_ANSWER_TOKENS }));
const answered = new Set(results.filter((r) => r.verdict !== null).map((r) => `${r.model}\u0000${r.key}`));
try {
- models: for (const model of models) {
+ // THIS invocation's models only: a resumed run never re-asks another's pairs.
+ models: for (const model of v.models) {
const local = providerOf(model) === "local";
let streak = 0;
for (const item of items) {
@@ -258,17 +443,10 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
const usdBefore = meter.usd;
const t0 = Date.now();
let r: BenchResult;
+ let raw: unknown = undefined;
try {
- const ans = await structuredAnswer<{ verdict?: unknown; reason?: unknown }>({
- llm: deps.llm,
- model,
- system: prompt.system,
- user: prompt.user,
- schema: VERDICT_ANSWER_SCHEMA,
- meter,
- ...(deps.signal ? { signal: deps.signal } : {}),
- maxTokens: MAX_ANSWER_TOKENS,
- });
+ const ans = await ask<{ verdict?: unknown; reason?: 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;
r = {
@@ -314,6 +492,21 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
if (prompt.cuesTrimmed) r.cuesTrimmed = prompt.cuesTrimmed;
record(r);
await save();
+ await trace({
+ t: "call",
+ model,
+ key: item.key,
+ promptVersion: PROMPT_VERSION,
+ estimate: prompt.estimate,
+ cuesShown: prompt.cuesShown,
+ cuesTrimmed: prompt.cuesTrimmed,
+ user: prompt.user,
+ ...(raw !== undefined ? { answer: raw } : {}),
+ verdict: r.verdict,
+ ...(r.failure ? { failure: r.failure, error: r.error } : {}),
+ ms: r.ms,
+ usd: r.usd,
+ });
log(`${model} ${item.key}: ${r.verdict ?? `(${r.failure}: ${r.error})`} ${r.ms} ms${r.usd ? ` $${r.usd.toFixed(4)}` : ""}`);
if (streak >= BENCH_ERROR_STREAK) {
stopped.push(`${model}: stopped after ${BENCH_ERROR_STREAK} errors in a row (${r.error})`);
diff --git a/common/lib/report/draft/bench/score.ts b/common/lib/report/draft/bench/score.ts
@@ -11,10 +11,22 @@
// - recall for CONTRADICTED and NOT_FOUND (of the items the operator ruled
// so, the share the model ruled so), and for PARTLY strictly and adjacent;
// - cost (USD from the Meter), latency (ms per call), parse failures, errors.
+// - (V1) "not CORROBORATED" as the positive class — the claims a proposal
+// would put in front of the operator: precision (of the model's
+// not-CORROBORATED answers, the share the operator ruled so too) and
+// recall (of the operator's not-CORROBORATED rulings, the share the model
+// found); a failed answer is a miss, never a positive.
// The BASELINE is a model that always answers CORROBORATED, scored the same way
// over the same items. A pass against the operator's bar is `passesBar`.
+//
+// V1 adds, also pure: `compareBenchRuns` (two runs on the same items: each
+// model's agreement in each, and the claims whose answers changed) and
+// `markedScore` (the operator's Right/Wrong marks on disagreements — a
+// disagreement marked Right counts as the model agreeing — tallied by the
+// triage marks' `markTally`).
import { VERDICTS, type Verdict } from "../../verdicts";
+import { markTally, type MarkTally } from "../triage/types";
export type BenchResult = {
key: string;
@@ -37,6 +49,9 @@ export type BenchResult = {
export type Recall = { ruled: number; matched: number; recall: number | null };
+// "Not CORROBORATED" as the positive class.
+export type FlagScore = { tp: number; fp: number; fn: number; precision: number | null; recall: number | null };
+
export type ModelScore = {
model: string;
asked: number;
@@ -49,6 +64,7 @@ export type ModelScore = {
matrix: number[][];
unanswered: number[];
recall: { CONTRADICTED: Recall; NOT_FOUND: Recall; PARTLY: Recall; PARTLY_ADJACENT: Recall };
+ notCorroborated: FlagScore;
parseFailures: number;
errors: number;
usd: number;
@@ -97,10 +113,15 @@ export function scoreModel(model: string, truth: ReadonlyMap<string, Verdict>, r
let errors = 0;
let usd = 0;
const ms: number[] = [];
+ const flag = { tp: 0, fp: 0, fn: 0 };
for (const [key, r] of last) {
const op = truth.get(key)!;
usd += r.usd;
if (r.ms > 0) ms.push(r.ms);
+ const pos = r.verdict !== null && r.verdict !== "CORROBORATED";
+ if (pos && op !== "CORROBORATED") flag.tp++;
+ else if (pos) flag.fp++;
+ else if (op !== "CORROBORATED") flag.fn++;
if (r.verdict === null) {
unanswered[idx(op)]! += 1;
if (r.failure === "parse") parseFailures++;
@@ -129,6 +150,7 @@ export function scoreModel(model: string, truth: ReadonlyMap<string, Verdict>, r
PARTLY: recallOf(matrix, unanswered, "PARTLY"),
PARTLY_ADJACENT: recallOf(matrix, unanswered, "PARTLY", "CORROBORATED"),
},
+ notCorroborated: { ...flag, precision: ratio(flag.tp, flag.tp + flag.fp), recall: ratio(flag.tp, flag.tp + flag.fn) },
parseFailures,
errors,
usd: Math.round(usd * 1e6) / 1e6,
@@ -184,3 +206,114 @@ export function passesBar(s: ModelScore, bar: VerdictBar): BarCheck {
if (s.asked === 0) misses.push("no items asked");
return { pass: misses.length === 0, misses };
}
+
+// ─── V1: two runs compared, and the operator's marks ───
+
+type RunLike = { items: readonly { key: string; verdict: Verdict }[]; results: readonly BenchResult[]; models: readonly string[] };
+
+export type AnswerChange = { key: string; ruled: Verdict; a: Verdict | null; b: Verdict | null };
+
+export type ModelCompare = {
+ model: string;
+ a: { agreed: number; asked: number; agreement: number | null };
+ b: { agreed: number; asked: number; agreement: number | null };
+ // The claims whose answer changed, the ones b got right that a did not first.
+ changed: AnswerChange[];
+ // Of the changed: b agrees where a did not (fixed), and the other way (broke).
+ fixed: number;
+ broke: number;
+};
+
+export type RunCompare = {
+ // The item keys both runs have (a comparison reads only these).
+ items: number;
+ onlyA: number;
+ onlyB: number;
+ models: ModelCompare[];
+};
+
+const lastOf = (results: readonly BenchResult[], model: string) => {
+ const m = new Map<string, BenchResult>();
+ for (const r of results) if (r.model === model) m.set(r.key, r);
+ return m;
+};
+
+/**
+ * Two runs on the same items: for each model asked in both, its agreement in
+ * each (over the shared items) and every claim whose answer changed. The
+ * operator's verdict is A's (the same items carry the same rulings). Pure.
+ */
+export function compareBenchRuns(a: RunLike, b: RunLike): RunCompare {
+ const bKeys = new Map(b.items.map((i) => [i.key, i.verdict] as const));
+ const shared = a.items.filter((i) => bKeys.has(i.key));
+ const truth = new Map(shared.map((i) => [i.key, i.verdict] as const));
+ const models: ModelCompare[] = [];
+ for (const model of a.models.filter((m) => b.models.includes(m))) {
+ const ra = lastOf(a.results, model);
+ const rb = lastOf(b.results, model);
+ const changed: AnswerChange[] = [];
+ let fixed = 0;
+ let broke = 0;
+ const tally = (r: Map<string, BenchResult>) => {
+ let agreed = 0;
+ let asked = 0;
+ for (const [k, v] of truth) {
+ const x = r.get(k);
+ if (!x) continue;
+ asked++;
+ if (x.verdict === v) agreed++;
+ }
+ return { agreed, asked, agreement: ratio(agreed, asked) };
+ };
+ for (const [k, ruled] of truth) {
+ const x = ra.get(k);
+ const y = rb.get(k);
+ if (!x || !y || x.verdict === y.verdict) continue;
+ changed.push({ key: k, ruled, a: x.verdict, b: y.verdict });
+ if (y.verdict === ruled) fixed++;
+ else if (x.verdict === ruled) broke++;
+ }
+ const rank = (c: AnswerChange) => (c.b === c.ruled ? 0 : c.a === c.ruled ? 1 : 2);
+ changed.sort((p, q) => rank(p) - rank(q));
+ models.push({ model, a: tally(ra), b: tally(rb), changed, fixed, broke });
+ }
+ return { items: shared.length, onlyA: a.items.length - shared.length, onlyB: b.items.length - shared.length, models };
+}
+
+// An operator's mark on one disagreement: was the MODEL right? `answer` is the
+// answer it marked — a mark whose answer has since changed (a resumed run asked
+// again) no longer applies.
+export type BenchMark = { verdict: "right" | "wrong"; answer: Verdict | null; at: string };
+// model → item key → mark.
+export type BenchMarks = Record<string, Record<string, BenchMark>>;
+
+export type MarkedScore = {
+ model: string;
+ // The marks that apply (on a disagreement, on the answer it still has).
+ marks: MarkTally;
+ // Agreement and the not-CORROBORATED scores with each disagreement marked
+ // Right counted as the model agreeing.
+ agreed: number;
+ agreement: number | null;
+ notCorroborated: FlagScore;
+};
+
+/** One model's score with the operator's marks applied. Pure. */
+export function markedScore(items: readonly { key: string; verdict: Verdict }[], results: readonly BenchResult[], model: string, marks: BenchMarks): MarkedScore {
+ const mine = marks[model] ?? {};
+ const last = lastOf(results, model);
+ const applied: BenchMark[] = [];
+ const truth = new Map<string, Verdict>();
+ for (const it of items) {
+ const r = last.get(it.key);
+ const m = mine[it.key];
+ let v = it.verdict;
+ if (r && m && r.verdict !== it.verdict && m.answer === r.verdict) {
+ applied.push(m);
+ if (m.verdict === "right" && r.verdict !== null) v = r.verdict;
+ }
+ truth.set(it.key, v);
+ }
+ const s = scoreModel(model, truth, results);
+ return { model, marks: markTally(applied), agreed: s.agreed, agreement: s.agreement, notCorroborated: s.notCorroborated };
+}
diff --git a/common/lib/report/draft/bench/store.ts b/common/lib/report/draft/bench/store.ts
@@ -6,18 +6,24 @@
// included: the answer key, never shown to a model
// results.jsonl one answer per (item, model) (./score.ts BenchResult)
// summary.json the run's parameters, status, spend, skipped claims and
-// its score
+// its score; V1: the prompt version, the items hash, the
+// window mode, the dropped citations, `itemsFrom`
+// trace.jsonl (V1) every call as it was made — the prompt the model
+// saw, its raw answer, the verdict kept — appended, one
+// line each, plus a `start` line per invocation
+// marks.json (V1) the operator's Right/Wrong marks on disagreements,
+// umtool's own (one writer: umtool/lib/bench-marks.mjs)
//
// Never `transcripts/`, never a commit: the items quote ruled claims. Every
// write is atomic (tmp + rename, the whole file); a re-run with the same id
// resumes (./run.ts skips each pair already answered).
-import { readdir, readFile } from "node:fs/promises";
+import { appendFile, readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { writeFileAtomic, writeJsonAtomic } from "../../../jsonFile-server";
import type { Paths } from "../../../paths";
-import type { BenchItem, BenchSkipped } from "./items";
-import type { BenchResult, BenchScore } from "./score";
+import type { BenchDropped, BenchItem, BenchSkipped, WindowMode } from "./items";
+import type { BenchMarks, BenchResult, BenchScore } from "./score";
export const BENCH_FORMAT = "archilyzer-verdict-bench";
export const BENCH_VERSION = 1;
@@ -25,6 +31,9 @@ export const BENCH_VERSION = 1;
export const BENCH_ITEMS_FILE = "items.jsonl";
export const BENCH_RESULTS_FILE = "results.jsonl";
export const BENCH_SUMMARY_FILE = "summary.json";
+export const BENCH_TRACE_FILE = "trace.jsonl";
+export const BENCH_MARKS_FILE = "marks.json";
+export const BENCH_MARKS_FORMAT = "archilyzer-bench-marks";
export const BENCH_STATUSES = ["running", "done", "capped", "cancelled", "failed"] as const;
export type BenchStatus = (typeof BENCH_STATUSES)[number];
@@ -40,6 +49,14 @@ export type BenchSummary = {
stopped?: string[];
models: string[];
windowS: number;
+ // V1: how each window was cut (absent: M7's, "seconds").
+ windowMode?: WindowMode;
+ // V1: the prompt the run asked with (absent: M7's, "1"), and the identity of
+ // its items (./items.ts benchItemsHash; absent: compute it from the items).
+ promptVersion?: string;
+ itemsHash?: string;
+ // V1: the run whose items this one was made from (`--items-from`).
+ itemsFrom?: string;
maxUsd: number;
// The reports asked for (empty: every fact-check in the registry).
reports: string[];
@@ -47,6 +64,8 @@ export type BenchSummary = {
spentUsd: number;
items: number;
skipped: BenchSkipped[];
+ // V1: the citations of kept claims that gave no window, with their reasons.
+ dropped?: BenchDropped[];
score: BenchScore;
};
@@ -146,3 +165,23 @@ export async function listBenchRuns(root: string): Promise<BenchSummary[]> {
}
export { readJsonl as readBenchJsonl };
+
+// One line of a run's trace, appended (never rewritten). A trace write never
+// fails the run: the caller catches.
+export async function appendBenchTrace(dir: string, line: Record<string, unknown>): Promise<void> {
+ await appendFile(path.join(dir, BENCH_TRACE_FILE), `${JSON.stringify(line)}\n`);
+}
+
+export async function readBenchTrace(root: string, id: string): Promise<Record<string, unknown>[]> {
+ return readJsonl<Record<string, unknown>>(path.join(benchRunDir(root, id), BENCH_TRACE_FILE));
+}
+
+// A run's marks, as umtool wrote them (none, or a file that does not read: empty).
+export async function readBenchMarks(root: string, id: string): Promise<BenchMarks> {
+ try {
+ const v = JSON.parse(await readFile(path.join(benchRunDir(root, id), BENCH_MARKS_FILE), "utf8")) as { format?: string; marks?: BenchMarks };
+ return v?.format === BENCH_MARKS_FORMAT && v.marks && typeof v.marks === "object" ? v.marks : {};
+ } catch {
+ return {};
+ }
+}
diff --git a/common/lib/report/draft/refresh/delta.ts b/common/lib/report/draft/refresh/delta.ts
@@ -21,6 +21,7 @@ import { enumerateOf, type EnumeratedRow } from "../tasks/trace";
import type { CorpusToolsLike } from "../tasks/types";
import { queryKey } from "./basis";
import type { CitedQuote, MatchedRow, QuoteRecheck, RefreshBasis, RefreshDelta, RefreshQuery } from "./types";
+import { goneState } from "../../../sourceGone";
export type CandidateScope = { channels: string[]; from?: string; to?: string };
@@ -191,8 +192,6 @@ export type QuoteReaders = {
postTextOf?: (channel: string, id: string) => Promise<string | null>;
};
-// The states a recording is "gone" in, for the delta's `deleted`.
-const GONE_STATES = new Set(["deleted", "private"]);
const isEn = (name: string) => /(^|[./])en\.vtt$/.test(name) || /\.en\.vtt$/.test(name);
const isEnOrig = (name: string) => /en-orig/.test(name);
@@ -227,7 +226,8 @@ export async function recheckQuotes(cited: readonly CitedQuote[], readers: Quote
out.push({ ...base, status: "missing", message: rec ? `${key} has no transcript now` : `${key} is not in the archive now` });
continue;
}
- const state = rec.state && GONE_STATES.has(rec.state) ? rec.state : undefined;
+ // A recording "gone" from its platform: the one reading (lib/sourceGone.ts).
+ const state = goneState(rec.state) ?? undefined;
const t = c.start ?? 0;
const cite = { t, end: c.end ?? t };
// The primary first, then every other track: the words on any of them stand.
diff --git a/common/lib/report/draft/triage/types.ts b/common/lib/report/draft/triage/types.ts
@@ -310,6 +310,21 @@ export type Precision = {
byStrength: { strong: { right: number; wrong: number }; weak: { right: number; wrong: number } };
};
+// An operator's Right/Wrong marks, tallied: the one count triage's flags and
+// the verdict bench's disagreements (release 29 V1) share.
+export type MarkTally = { marked: number; right: number; wrong: number; precision: number | null };
+
+export function markTally(marks: readonly { verdict: "right" | "wrong" }[]): MarkTally {
+ let right = 0;
+ let wrong = 0;
+ for (const m of marks) {
+ if (m.verdict === "right") right++;
+ else wrong++;
+ }
+ const marked = right + wrong;
+ return { marked, right, wrong, precision: marked ? Math.round((right / marked) * 1000) / 1000 : null };
+}
+
export function precisionOf(marks: readonly FlagMark[]): Precision {
const by = { strong: { right: 0, wrong: 0 }, weak: { right: 0, wrong: 0 } };
for (const m of marks) {
@@ -317,10 +332,7 @@ export function precisionOf(marks: readonly FlagMark[]): Precision {
if (m.verdict === "right") s.right++;
else s.wrong++;
}
- const right = by.strong.right + by.weak.right;
- const wrong = by.strong.wrong + by.weak.wrong;
- const marked = right + wrong;
- return { marked, right, wrong, precision: marked ? Math.round((right / marked) * 1000) / 1000 : null, byStrength: by };
+ return { ...markTally(marks), byStrength: by };
}
// The fewest marks of a kind a suggestion is made on.
diff --git a/common/lib/report/schema.ts b/common/lib/report/schema.ts
@@ -205,7 +205,7 @@ export const CLAIM_FIELD_DOCS: FieldDocs<Claim> = {
id: `The claim's id (letters, digits, \`_ . : -\`; at most 64): its anchor on the report page. Unique among the report's section, claim and entry ids, and none of the page's own anchors (${RESERVED_ANCHOR_IDS.map((a) => `\`${a}\``).join(", ")}).`,
title: "A short headline for the claim (plain text, e.g. a phrase it turns on), shown above its text. Absent = the text alone.",
text: "The claim, as stated by the document under review (plain text).",
- verdict: `The ruling on the claim: ${VERDICTS.map((v) => `\`${v}\``).join(", ")}. A fact-check's claim may leave it out (not yet ruled); a sweep's carries none.`,
+ verdict: `The ruling on the claim: ${VERDICTS.map((v) => `\`${v}\``).join(", ")} (what each means: "The verdicts", below). A fact-check's claim may leave it out (not yet ruled); a sweep's carries none.`,
gist: `The claim's finding in one line (plain text, at most ${CLAIM_GIST_MAX} characters), shown beside its title in the overview of what the check found. Absent = the title alone.`,
flag: `A short mark on the claim (plain text, one line, at most ${CLAIM_FLAG_MAX} characters), shown as a pill on its card: e.g. that the document gives no source for it. Absent = none.`,
sourceQuote:
diff --git a/common/lib/report/verdicts.mjs b/common/lib/report/verdicts.mjs
@@ -20,6 +20,30 @@ export const VERDICT_DEFAULTS = Object.freeze({
UNTESTABLE: Object.freeze({ label: "Untestable", color: "#7d8fd6" }),
});
+/**
+ * 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.
+ */
+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.",
+ 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.",
+ 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.",
+ 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.",
+ UNTESTABLE:
+ "the claim is an opinion, a judgement, a prediction, or anything else a transcript 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.";
+
/** 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
@@ -6,6 +6,8 @@ import {
VERDICT_COLOR_RE as VERDICT_COLOR_RE_JS,
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,
VERDICTS as VERDICTS_JS,
resolveVerdicts as resolveVerdictsJs,
verdictOverrideProblems as verdictOverrideProblemsJs,
@@ -23,6 +25,12 @@ 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.
+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_COLOR_RE: RegExp = VERDICT_COLOR_RE_JS;
export function isVerdict(v: unknown): v is Verdict {
diff --git a/common/lib/report/views.ts b/common/lib/report/views.ts
@@ -64,6 +64,7 @@ import type { Claim, Report, ReportKind, ReportSlidesSpec, SlideSpec } from "./s
import { reportCitationNumbers } from "./uses";
import { SITE_REPORTS_BASE, type ReportBase } from "./routes";
import { resolveVerdicts, VERDICTS, type Verdict, type VerdictStyle } from "./verdicts";
+import type { GoneState } from "../sourceGone";
export const REPORT_VIEWS_VERSION = 1;
@@ -237,6 +238,10 @@ export type SpanCitationView = CitationViewCommon & {
record: RecordView;
// A still for the card: a site-root path or an http(s) URL.
poster?: string;
+ // The recording is gone from its platform and no copy of the moment is
+ // published: the moment is its words only, said in plain words
+ // (SOURCE_GONE_LABELS, lib/sourceGone.ts). Release 29 E2.
+ sourceGone?: GoneState;
};
export type PostCitationView = CitationViewCommon & {
@@ -249,6 +254,8 @@ export type PostCitationView = CitationViewCommon & {
// The captured screenshot of the post: a site-root path.
shot?: string;
thread?: boolean;
+ // The post is deleted and was never captured: its words only.
+ sourceGone?: GoneState;
};
// A sentence of a document. The document itself (its byline and its archive
@@ -460,6 +467,9 @@ export type MomentPageView = {
cues?: CueLineView[];
// A post.
post?: MomentPostView;
+ // The source is gone and no media of the moment is published (a span with
+ // no clip, a post with no shot): the page says so in plain words.
+ sourceGone?: GoneState;
citedIn: CitedInView[];
};
@@ -477,6 +487,8 @@ export type ReportViewResolver = {
record: (c: SpanCitation | PostCitation) => RecordView;
poster?: (c: SpanCitation) => string | undefined;
post?: (c: PostCitation) => { author?: string; text?: string; shot?: string } | undefined;
+ // A cited moment whose source is gone and whose media is not published.
+ sourceGone?: (c: SpanCitation | PostCitation) => GoneState | undefined;
downloads?: ReportDownloads;
history?: ReportHistoryRef;
// The report's feeds (absolute URLs), carried only by a report with entries.
@@ -539,6 +551,7 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver)
end: Number(formatMomentSeconds(c.end)),
record: resolve.record(c),
poster: resolve.poster?.(c),
+ sourceGone: resolve.sourceGone?.(c),
});
break;
}
@@ -556,6 +569,7 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver)
text: post?.text,
shot: post?.shot,
thread: c.thread,
+ sourceGone: resolve.sourceGone?.(c),
});
break;
}
diff --git a/common/lib/sourceGone-server.ts b/common/lib/sourceGone-server.ts
@@ -0,0 +1,33 @@
+// The disk half of the gone reading (./sourceGone.ts): a recording's video
+// directory, a post's availability sidecar.
+//
+// SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { stateFromAvailability } from "./availability";
+import { resolveEffectiveAvailability } from "./availability-server";
+import { readPostAvailability } from "./posts-server";
+import { resolveVideoDir } from "./videoDir-server.mjs";
+import { goneState, type GoneState } from "./sourceGone";
+
+// A recording's video directory → its gone state, or null (live, or never
+// resolved: a missing or unreadable availability is NOT gone).
+export async function sourceGoneState(videoDir: string): Promise<GoneState | null> {
+ const a = await resolveEffectiveAvailability(videoDir).catch(() => null);
+ return goneState(stateFromAvailability(a));
+}
+
+// The same by channel and record id (the record's directory resolved as every
+// reader resolves it).
+export async function recordGoneState(channelsDir: string, slug: string, id: string): Promise<GoneState | null> {
+ const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null);
+ return dir ? sourceGoneState(dir) : null;
+}
+
+// A post is gone when the channel's posts-availability.json says `deleted`
+// (a deleted-post sweep or a capture saw it so). Anything else — available,
+// an unreachable account, an error, never checked — is not.
+export async function postGoneState(channelsDir: string, slug: string, id: string): Promise<"deleted" | null> {
+ const map = await readPostAvailability(path.join(channelsDir, slug)).catch(() => ({}) as Record<string, { availability: string }>);
+ return map[id]?.availability === "deleted" ? "deleted" : null;
+}
diff --git a/common/lib/sourceGone.test.ts b/common/lib/sourceGone.test.ts
@@ -0,0 +1,62 @@
+// The one gone reading (release 29 E2): deleted or private is gone; members-
+// only, an error probe, an unlisted video and no availability at all are not.
+// A post is gone when posts-availability.json says deleted.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/sourceGone.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { goneState, GONE_STATES, SOURCE_GONE_LABELS } from "./sourceGone";
+import { postGoneState, recordGoneState, sourceGoneState } from "./sourceGone-server";
+
+test("goneState: deleted and private, nothing else", () => {
+ assert.deepEqual([...GONE_STATES], ["deleted", "private"]);
+ assert.equal(goneState("deleted"), "deleted");
+ assert.equal(goneState("private"), "private");
+ for (const s of ["available", "members_only", "unlisted", "maybe_missing", "error", "", null, undefined]) {
+ assert.equal(goneState(s), null, String(s));
+ }
+ assert.equal(SOURCE_GONE_LABELS.deleted, "Source deleted");
+});
+
+test("sourceGoneState reads the video's availability as refresh does; recordGoneState by channel and id; postGoneState", async () => {
+ const channels = await mkdtemp(path.join(os.tmpdir(), "source-gone-"));
+ try {
+ const dir = path.join(channels, "demo", "data", "v1");
+ await mkdir(dir, { recursive: true });
+ assert.equal(await sourceGoneState(dir), null, "never checked: not gone");
+ const write = (availability: string) =>
+ writeFile(path.join(dir, "availability.json"), JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability }));
+ for (const [a, want] of [
+ ["deleted", "deleted"],
+ ["private", "private"],
+ ["members_only", null],
+ ["needs_auth", null],
+ ["error", null],
+ ["unlisted", null],
+ ["public", null],
+ ] as const) {
+ await write(a);
+ assert.equal(await sourceGoneState(dir), want, a);
+ }
+ await write("deleted");
+ assert.equal(await recordGoneState(channels, "demo", "v1"), "deleted");
+ assert.equal(await recordGoneState(channels, "demo", "nope"), null);
+
+ assert.equal(await postGoneState(channels, "demo", "p1"), null, "no sidecar");
+ await writeFile(
+ path.join(channels, "demo", "posts-availability.json"),
+ JSON.stringify({
+ p1: { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" },
+ p2: { availability: "account_unavailable", checkedAt: "2026-10-01T00:00:00.000Z" },
+ }),
+ );
+ assert.equal(await postGoneState(channels, "demo", "p1"), "deleted");
+ assert.equal(await postGoneState(channels, "demo", "p2"), null, "an unreachable account is not a deleted post");
+ } finally {
+ await rm(channels, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/sourceGone.ts b/common/lib/sourceGone.ts
@@ -0,0 +1,31 @@
+// IS THIS SOURCE GONE? — the one reading (release 29 E2).
+//
+// A recording is gone from its platform when its effective availability
+// (availability-server.ts resolveEffectiveAvailability: the explicit check or
+// the last download's outcome, whichever is newer) reads, as a viewer state
+// (availability.ts stateFromAvailability), `deleted` or `private`. Members-only
+// is not gone: a member's cookies fetch it. An `error` probe is not gone: it
+// never saw the video.
+//
+// The reading R4's refresh made first (draft/refresh/delta.ts), shared by every
+// caller since: refresh's delta, compose (a cited moment of a gone source with
+// no media is a text-only moment, `sourceGone`), the evidence windows a site
+// still needs (reportMedia.ts missingEvidenceWindows, "unfetchable: gone"),
+// fetch-windows' door and find-copy. A post is gone when posts-availability.json
+// says `deleted` (sourceGone-server.ts postGoneState).
+//
+// Pure: client-safe, no node: imports.
+
+export const GONE_STATES = ["deleted", "private"] as const;
+export type GoneState = (typeof GONE_STATES)[number];
+
+// A viewer state (or anything) as a gone state, or null when it is not one.
+export function goneState(state: string | null | undefined): GoneState | null {
+ return state === "deleted" || state === "private" ? state : null;
+}
+
+// What a reader is told about a gone source: plain words.
+export const SOURCE_GONE_LABELS: Readonly<Record<GoneState, string>> = Object.freeze({
+ deleted: "Source deleted",
+ private: "Source made private",
+});
diff --git a/common/lib/waybackClient.test.ts b/common/lib/waybackClient.test.ts
@@ -0,0 +1,80 @@
+// The Wayback CDX client (release 29 E2), over the fake Wayback on loopback
+// (common/testing/web/fakeWayback.mjs) through archive.org's polite client:
+// the JSON answer and its empty forms, the 200 filter, a 429 waited out.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackClient.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import { parseCdxJson, waybackCdxUrl, WaybackClient, waybackReplayUrl } from "./waybackClient";
+import { ArchiveOrgRequestError } from "./archiveOrgClient";
+
+const BREAD = "https://video.example/watch?v=bread-day-01";
+const GONE = "https://video.example/watch?v=gone-video-05";
+
+test("parseCdxJson: the header names the columns; [] and an empty body are none; anything else is an error", () => {
+ const rows = parseCdxJson(
+ JSON.stringify([
+ ["urlkey", "timestamp", "original", "mimetype", "statuscode", "digest", "length"],
+ ["example,video)/watch?v=x", "20260106120000", "https://video.example/watch?v=x", "text/html", "200", "D", "1"],
+ ["example,video)/watch?v=x", "not-a-time", "https://video.example/watch?v=x", "text/html", "200", "D", "1"],
+ ]),
+ );
+ assert.deepEqual(rows, [
+ {
+ timestamp: "20260106120000",
+ original: "https://video.example/watch?v=x",
+ status: "200",
+ mimetype: "text/html",
+ replayUrl: "https://web.archive.org/web/20260106120000/https://video.example/watch?v=x",
+ },
+ ]);
+ assert.deepEqual(parseCdxJson("[]"), []);
+ assert.deepEqual(parseCdxJson(""), []);
+ assert.deepEqual(parseCdxJson('[["urlkey","timestamp","original"]]'), []);
+ assert.throws(() => parseCdxJson("<html>busy</html>"), /did not answer JSON/);
+ assert.throws(() => parseCdxJson('{"a":1}'), /not a list/);
+ assert.equal(waybackReplayUrl("20260101000000", "https://a.example/x"), "https://web.archive.org/web/20260101000000/https://a.example/x");
+ assert.equal(
+ waybackCdxUrl("https://a.example/x?v=1", { okOnly: true, limit: 5 }),
+ "https://web.archive.org/cdx/search/cdx?url=https%3A%2F%2Fa.example%2Fx%3Fv%3D1&output=json&filter=statuscode%3A200&limit=5",
+ );
+});
+
+test("captures: every one oldest first, only the 200s, none for an uncaptured page", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 });
+ assert.deepEqual((await c.captures(BREAD)).map((x) => [x.timestamp, x.status]), [
+ ["20260106120000", "200"],
+ ["20260301080000", "302"],
+ ]);
+ assert.deepEqual((await c.captures(BREAD, { okOnly: true })).map((x) => x.timestamp), ["20260106120000"]);
+ const gone = await c.captures(GONE, { okOnly: true });
+ assert.equal(gone[0]!.replayUrl, `https://web.archive.org/web/20260125093000/${GONE}`);
+ assert.deepEqual(await c.captures("https://video.example/watch?v=never"), []);
+ assert.equal(c.requests, 4);
+ } finally {
+ await wb.close();
+ }
+});
+
+test("a 429 is waited out (Retry-After) and asked again; one that persists stops with rateLimited", async () => {
+ const wb = await startFakeWayback({ busyTimes: 1 });
+ try {
+ const waits: number[] = [];
+ const c = new WaybackClient({ fetch: wb.fetch, sleep: async (ms) => void waits.push(ms) }, { minGapMs: 0 });
+ assert.equal((await c.captures(GONE)).length, 1);
+ assert.deepEqual(waits, [1_000]);
+ } finally {
+ await wb.close();
+ }
+ const busy = await startFakeWayback({ busyTimes: 10 });
+ try {
+ const c = new WaybackClient({ fetch: busy.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 3 });
+ await assert.rejects(c.captures(GONE), (e: unknown) => e instanceof ArchiveOrgRequestError && e.rateLimited);
+ } finally {
+ await busy.close();
+ }
+});
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -0,0 +1,118 @@
+// THE WAYBACK MACHINE'S CDX API (release 29 E2): which captures web.archive.org
+// holds of a URL — the deleted-video fallback asks it for a gone recording's
+// watch page (publish/findCopy.ts, `pnpm ops wayback-lookup`).
+//
+// web.archive.org is archive.org's, and is asked with archive.org's manners:
+// the same polite client (lib/archiveOrgClient.ts) — one request at a time, a
+// 2 s gap, the project's User-Agent, 429/503 waited out (Retry-After, else 5 s,
+// 10 s, … capped) a few times and then stopped — as its own instance, so a
+// Wayback lookup and an archive.org import each keep their own gap.
+//
+// A capture's replay URL is `https://web.archive.org/web/<timestamp>/<url>`:
+// the page as captured, which is also what yt-dlp's Wayback extractor reads
+// a YouTube watch page's video from.
+
+import {
+ ArchiveOrgClient,
+ ArchiveOrgRequestError,
+ type ArchiveOrgClientDeps,
+ type ArchiveOrgClientOpts,
+} from "./archiveOrgClient";
+
+export const WAYBACK_ORIGIN = "https://web.archive.org";
+
+export type WaybackCapture = {
+ // YYYYMMDDhhmmss
+ timestamp: string;
+ // The URL as captured.
+ original: string;
+ // The HTTP status the capture recorded ("200", "302", "-" for a revisit).
+ status: string;
+ mimetype?: string;
+ // The capture's page on web.archive.org.
+ replayUrl: string;
+};
+
+export function waybackReplayUrl(timestamp: string, original: string): string {
+ return `${WAYBACK_ORIGIN}/web/${timestamp}/${original}`;
+}
+
+export function waybackCdxUrl(url: string, o: { limit?: number; okOnly?: boolean } = {}): string {
+ const q = new URLSearchParams();
+ q.set("url", url);
+ q.set("output", "json");
+ if (o.okOnly) q.set("filter", "statuscode:200");
+ if (o.limit) q.set("limit", String(o.limit));
+ return `${WAYBACK_ORIGIN}/cdx/search/cdx?${q.toString()}`;
+}
+
+// The CDX API's JSON answer: a header row naming the columns, then one row per
+// capture. `[]`, an empty body or a header alone: no captures. Anything else
+// that is not that shape is an error (the API changed, or answered a page).
+export function parseCdxJson(body: string): WaybackCapture[] {
+ const text = body.trim();
+ if (!text) return [];
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ throw new Error(`the CDX API did not answer JSON (${text.slice(0, 80)})`);
+ }
+ if (!Array.isArray(raw)) throw new Error("the CDX API's answer is not a list");
+ if (raw.length === 0) return [];
+ const [header, ...rows] = raw as unknown[][];
+ if (!Array.isArray(header)) throw new Error("the CDX API's answer has no header row");
+ const col = (name: string) => header.indexOf(name);
+ const ts = col("timestamp");
+ const orig = col("original");
+ const st = col("statuscode");
+ const mt = col("mimetype");
+ if (ts < 0 || orig < 0) throw new Error("the CDX API's header names no timestamp or original");
+ const out: WaybackCapture[] = [];
+ for (const row of rows) {
+ if (!Array.isArray(row)) continue;
+ const timestamp = String(row[ts] ?? "");
+ const original = String(row[orig] ?? "");
+ if (!/^\d{14}$/.test(timestamp) || !original) continue;
+ const mimetype = mt >= 0 && typeof row[mt] === "string" ? (row[mt] as string) : undefined;
+ out.push({
+ timestamp,
+ original,
+ status: st >= 0 ? String(row[st] ?? "") : "",
+ ...(mimetype ? { mimetype } : {}),
+ replayUrl: waybackReplayUrl(timestamp, original),
+ });
+ }
+ return out;
+}
+
+export class WaybackClient {
+ private readonly http: ArchiveOrgClient;
+
+ constructor(deps: ArchiveOrgClientDeps = {}, opts: ArchiveOrgClientOpts = {}) {
+ this.http = new ArchiveOrgClient(deps, opts);
+ }
+
+ // Requests sent (each attempt), for tests and logs.
+ get requests(): number {
+ return this.http.requests;
+ }
+
+ // The captures of `url`, oldest first: every capture, or (`okOnly`) only the
+ // ones that recorded a 200. Throws ArchiveOrgRequestError when the API kept
+ // refusing (`rateLimited`) or answered an error.
+ async captures(
+ url: string,
+ o: { limit?: number; okOnly?: boolean; signal?: AbortSignal } = {},
+ ): Promise<WaybackCapture[]> {
+ const body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal);
+ try {
+ return parseCdxJson(body);
+ } catch (e) {
+ throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false);
+ }
+ }
+}
+
+// THE process's Wayback client: one chain, one gap.
+export const waybackClient = new WaybackClient();
diff --git a/common/publish/composeReports.test.ts b/common/publish/composeReports.test.ts
@@ -512,6 +512,55 @@ test("a citation without prepared media fails compose with the list, unless --al
}
});
+test("a gone source with no prepared media is its words only, marked sourceGone; a live one is still refused", async () => {
+ // The recording deleted on its platform (lib/sourceGone.ts reads
+ // availability.json), the post deleted in posts-availability.json; neither
+ // has prepared media.
+ const avail = path.join(paths.channelsDir, VIDEOS, "data", "abc123", "availability.json");
+ const postsAvail = path.join(paths.channelsDir, SOCIAL, "posts-availability.json");
+ writeJson(avail, { checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" });
+ writeJson(postsAvail, { "3kabc": { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" } });
+ seedMedia("cited", [`${VIDEOS}/abc123/10.00-20.00`, `${SOCIAL}/3kabc`]);
+ try {
+ await compose("cited");
+ const span = readJson<Record<string, unknown>>(pub("m", VIDEOS, "abc123", "10.00-20.00", "moment.json"));
+ assert.equal(span.sourceGone, "deleted");
+ assert.equal(span.clip, undefined);
+ assert.ok(Array.isArray(span.cues) && (span.cues as unknown[]).length > 0, "its words are there");
+ const post = readJson<Record<string, unknown> & { post: { shot?: string } }>(pub("m", SOCIAL, "3kabc", "moment.json"));
+ assert.equal(post.sourceGone, "deleted");
+ assert.equal(post.post.shot, undefined);
+ const view = readJson<{ citations: Record<string, { sourceGone?: string }> }>(pub("pages", REPORT, "page.json"));
+ assert.equal(view.citations.c01.sourceGone, "deleted");
+ assert.equal(view.citations.p01.sourceGone, "deleted");
+ // A moment of a live recording with media keeps its clip, unmarked.
+ assert.equal(view.citations.c02.sourceGone, undefined);
+ assert.ok(!existsSync(pub("media", "clips", VIDEOS, "abc123")));
+
+ // Made private reads as gone too; live again (no availability): refused.
+ writeJson(avail, { checkedAt: "2026-10-01T00:00:00.000Z", availability: "private" });
+ await compose("cited");
+ assert.equal(readJson<Record<string, unknown>>(pub("m", VIDEOS, "abc123", "10.00-20.00", "moment.json")).sourceGone, "private");
+ rmSync(avail);
+ rmSync(postsAvail);
+ await assert.rejects(compose("cited"), (e: unknown) => {
+ assert.ok(e instanceof ComposeReportsError);
+ assert.deepEqual(
+ e.problems.map((p) => [p.kind, p.moment]),
+ [
+ ["missing-media", `${VIDEOS}/abc123/10.00-20.00`],
+ ["missing-media", `${SOCIAL}/3kabc`],
+ ],
+ );
+ return true;
+ });
+ } finally {
+ rmSync(avail, { force: true });
+ rmSync(postsAvail, { force: true });
+ seedMedia("cited");
+ }
+});
+
test("a report's video: copied beside its page and named in the view; a missing or oversize one fails compose", async () => {
const dir = path.join(paths.sitesDir, "cited", "reports", REPORT);
const file = path.join(dir, "report.json");
diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts
@@ -150,6 +150,8 @@ import { publishReportHistory, readReportHistoryView, reportHistoryRef, storeHis
import { hostCorpusLink, siteReportHost, type ReportHost } from "./reportHost";
import type { ReportHistoryRef, ReportHistoryView } from "../lib/report/revisions";
import { LEGACY_SITE_REPORTS_DIR, SITE_REPORTS_BASE, reportBaseDir, type ReportBase } from "../lib/report/routes";
+import { SOURCE_GONE_LABELS, type GoneState } from "../lib/sourceGone";
+import { postGoneState, recordGoneState } from "../lib/sourceGone-server";
// The public dir's entries this stage owns for a host serving its reports
// under `base`: its reports, the moments, the cited media. Every compose
@@ -264,6 +266,8 @@ export type ComposedReports = {
moments: string[];
// Media problems let through by `allowMissingMedia`.
allowed: ComposeReportsProblem[];
+ // The moments published with their words only, their source gone.
+ sourceGone?: SourceGoneMoment[];
// The reports whose revision history was published.
histories?: string[];
};
@@ -504,8 +508,13 @@ export type ResolvedSiteReports = {
mediaOf: Map<string, ReportMediaEntry>;
cacheDir: string;
allowed: ComposeReportsProblem[];
+ // The moments accepted with no media because their source is gone (a
+ // warning, never a problem): each shows its words only, marked.
+ sourceGone: SourceGoneMoment[];
};
+export type SourceGoneMoment = { moment: string; state: GoneState; citations: string[] };
+
export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promise<ResolvedSiteReports> {
const { site, ...rest } = opts;
return resolveReports({ ...rest, host: siteReportHost(opts.paths, site) });
@@ -659,6 +668,8 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
const citedIn = buildCitedIn(reports);
const momentInfo = new Map(citedMoments(reports).map((m) => [m.key, m]));
const mediaOf = new Map<string, ReportMediaEntry>();
+ // moment key → its source's gone state, for a moment accepted with no media.
+ const sourceGone = new Map<string, GoneState>();
for (const key of Object.keys(citedIn)) {
const m = momentInfo.get(key);
if (!m || refusedChannel.has(m.moment.channel)) continue;
@@ -667,6 +678,18 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
const missing = (kind: ComposeReportsProblemKind, message: string) =>
problems.push({ kind, moment: key, message: `${message} (cited by ${[...new Set(citedBy)].join(", ")})` });
if (!entry) {
+ // A SOURCE GONE FROM ITS PLATFORM with no media prepared (release 29 E2):
+ // accepted as a text-only moment, marked — the recording deleted or made
+ // private (lib/sourceGone.ts), the post deleted in posts-availability.json.
+ // A live source with no media is still refused.
+ const gone =
+ m.kind === "post"
+ ? await postGoneState(paths.channelsDir, m.moment.channel, m.moment.id)
+ : await recordGoneState(paths.channelsDir, m.moment.channel, m.moment.id);
+ if (gone) {
+ sourceGone.set(key, gone);
+ continue;
+ }
missing("missing-media", "no prepared media — run Prepare evidence media (archilyzer reports prepare)");
continue;
}
@@ -787,6 +810,10 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
const post = postsByChannel.get(c.channel)?.get(c.id);
return post ? { author: postAuthor(post), text: post.text, shot: postShot(c) } : undefined;
},
+ sourceGone: (c) => {
+ const k = momentKeyOf(c);
+ return k ? sourceGone.get(k) : undefined;
+ },
downloads: opts.downloads?.(report.id),
history: opts.history?.(report.id),
feeds: opts.feeds?.(report.id),
@@ -820,6 +847,7 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
...(c.speaker ? { speaker: c.speaker } : {}),
...(c.date ? { date: c.date } : {}),
...(c.verification ? { verification: c.verification } : {}),
+ ...(sourceGone.has(key) ? { sourceGone: sourceGone.get(key)! } : {}),
citedIn: citedInViews(entries, views, host.base),
} as const;
if (c.kind === "post") {
@@ -868,7 +896,13 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
});
}
moments.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
- return { reports, views, index, moments, mediaOf, cacheDir, allowed };
+ const gone = [...sourceGone].map(([moment, state]) => ({
+ moment,
+ state,
+ citations: [...new Set(citedIn[moment].map((e) => `${e.reportId}#${e.citationId}`))],
+ }));
+ for (const g of gone) log(`[reports] warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`);
+ return { reports, views, index, moments, mediaOf, cacheDir, allowed, sourceGone: gone };
}
// ─── The stage ───
@@ -937,7 +971,7 @@ export async function composeHostReports(opts: ComposeHostReportsOptions): Promi
if (historyProblems.length > 0) throw new ComposeReportsError(historyProblems, composedReportsNoun(host));
// A timeline's feeds link absolutely: a site with no public URL publishes none.
const siteUrl = host.siteUrl;
- const { reports, views, index, moments, mediaOf, cacheDir, allowed } = await resolveReports({
+ const { reports, views, index, moments, mediaOf, cacheDir, allowed, sourceGone } = await resolveReports({
...opts,
history: (id) => histories.get(id)?.ref,
feeds: siteUrl ? (id) => reportFeedUrls(siteUrl, id, base) : undefined,
@@ -1009,9 +1043,16 @@ export async function composeHostReports(opts: ComposeHostReportsOptions): Promi
}
log(
`[reports] ${reports.length} report(s), ${moments.length} moment page(s), ${copied} media file(s)` +
- `${allowed.length ? `, ${allowed.length} without media` : ""}.`,
+ `${allowed.length ? `, ${allowed.length} without media` : ""}` +
+ `${sourceGone.length ? `, ${sourceGone.length} whose source is gone (words only)` : ""}.`,
);
- return { reports: index.reports, moments: moments.map((m) => m.key), allowed, histories: [...histories.keys()] };
+ return {
+ reports: index.reports,
+ moments: moments.map((m) => m.key),
+ allowed,
+ ...(sourceGone.length ? { sourceGone } : {}),
+ histories: [...histories.keys()],
+ };
}
// A clip's published path: the moment's (lib/report/views.ts), `.m4a` for a
diff --git a/common/publish/findCopy.test.ts b/common/publish/findCopy.test.ts
@@ -0,0 +1,209 @@
+// find-copy (release 29 E2) over the fake Wayback and the fake archive.org on
+// loopback, through the real polite clients: per gone recording, Wayback first,
+// archive.org second, none → its words only; the fetch-windows items carry the
+// copy's URL and the copy; one recording at a time; a dry run starts nothing.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopy.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import { ITEMS, startFakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs";
+import { ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { WaybackClient } from "../lib/waybackClient";
+import type { MissingEvidenceWindows, UnfetchableEvidenceWindow } from "./reportMedia";
+import type { ReportHost } from "./reportHost";
+import type { Paths } from "../lib/paths";
+import type { FetchWindowsItem } from "../controller/fetchWindows";
+import {
+ findArchiveOrgMirrors,
+ findCopies,
+ pickMirrorFile,
+ runFindCopy,
+ youtubeIdOf,
+ youtubeIdQuery,
+} from "./findCopy";
+
+const CH = "synth-kitchen";
+const watch = (id: string) => `https://video.example/watch?v=${id}`;
+
+// A second mirror, for a recording the Wayback has no capture of.
+const OTHER_MIRROR = {
+ metadata: {
+ identifier: "youtube-otherupload1",
+ title: "Another lost upload",
+ mediatype: "movies",
+ description: "Mirror of https://video.example/watch?v=otherupload1",
+ },
+ files: [
+ { name: "Another lost upload-otherupload1.mkv", source: "original", format: "Matroska", size: "4000" },
+ { name: "Another lost upload-otherupload1.mp4", source: "original", format: "MPEG4", size: "3000" },
+ ],
+};
+
+const gone = (id: string, from: number, clip: string): UnfetchableEvidenceWindow => ({
+ slug: CH,
+ id,
+ from,
+ to: from + 10,
+ clipId: clip,
+ citations: [clip],
+ reason: `the words of ${id}`,
+ why: "gone",
+ gone: "deleted",
+ message: "the source says the video is deleted",
+});
+
+const NEED: MissingEvidenceWindows = {
+ siteId: "articles",
+ missing: [],
+ onDisk: 0,
+ problems: [],
+ unfetchable: [
+ gone("gone-video-05", 0, "a#c1"),
+ gone("gone-video-05", 30, "a#c2"),
+ gone("otherupload1", 5, "a#c3"),
+ gone("nothing00001", 5, "a#c4"),
+ { ...gone("elsewhere001", 1, "a#c5"), why: "not-in-site", gone: undefined },
+ ],
+};
+
+async function fakes(o: { waybackBusy?: number } = {}) {
+ const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0 });
+ const ia = await startFakeArchiveOrg({ items: [...ITEMS, OTHER_MIRROR] });
+ const deps = {
+ wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }),
+ archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }),
+ missing: async () => NEED,
+ webpageUrl: async (_p: Paths, _slug: string, id: string) => watch(id),
+ };
+ return { wb, ia, deps, close: async () => Promise.all([wb.close(), ia.close()]) };
+}
+
+const opts = (deps: unknown) => ({ paths: {} as Paths, host: { id: "articles" } as ReportHost, deps: deps as never });
+
+test("youtubeIdOf and the mirror query", () => {
+ assert.equal(youtubeIdOf("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "x"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf("https://youtu.be/dQw4w9WgXcQ?t=4", "x"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf("https://www.youtube.com/shorts/dQw4w9WgXcQ", "x"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf(null, "dQw4w9WgXcQ"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf(null, "a/b"), null);
+ assert.match(youtubeIdQuery("dQw4w9WgXcQ"), /^identifier:\(youtube-dQw4w9WgXcQ\) OR originalurl:\(\*dQw4w9WgXcQ\*\)/);
+ assert.throws(() => youtubeIdQuery("no spaces allowed"), /not a YouTube id/);
+});
+
+test("pickMirrorFile: a file naming the id, an original before a derivative, mp4 before webm; a dump of many is no pick", () => {
+ const f = (name: string, source: string) => ({ name, source });
+ assert.deepEqual(pickMirrorFile({ files: [f("x-ID12345.webm", "original"), f("x-ID12345.mp4", "derivative")] }, "ID12345"), {
+ file: "x-ID12345.webm",
+ source: "original",
+ });
+ assert.equal(pickMirrorFile({ files: [f("a.mp4", "original"), f("b.webm", "original")] }, "ID12345"), null);
+ assert.equal(pickMirrorFile({ files: [f("only.mkv", "original"), f("only.mp4", "derivative")] }, "ID12345")?.file, "only.mkv");
+ assert.equal(pickMirrorFile({ files: [f("notes.txt", "original")] }, "ID12345"), null);
+});
+
+test("archive-search by YouTube id: each mirror's direct file URL, an original preferred", async () => {
+ const { deps, close } = await fakes();
+ try {
+ const r = await findArchiveOrgMirrors("gone-video-05", { client: deps.archive });
+ assert.equal(r.found, 1);
+ assert.deepEqual(r.mirrors, [
+ {
+ identifier: "youtube-gone-video-05",
+ title: "The old oven review",
+ file: "The old oven review-gone-video-05.webm",
+ url: "https://archive.org/download/youtube-gone-video-05/The%20old%20oven%20review-gone-video-05.webm",
+ source: "original",
+ size: 3000000,
+ },
+ ]);
+ assert.deepEqual((await findArchiveOrgMirrors("nothing00001", { client: deps.archive })).mirrors, []);
+ } finally {
+ await close();
+ }
+});
+
+test("find-copy: Wayback first, archive.org second, none → words only; one recording at a time", async () => {
+ const { wb, ia, deps, close } = await fakes();
+ try {
+ const lines: string[] = [];
+ const r = await findCopies({ ...opts(deps), onLog: (l) => lines.push(l) });
+ assert.deepEqual(
+ r.recordings.map((x) => [x.id, x.outcome, x.copy?.from ?? null, x.windows.length]),
+ [
+ ["gone-video-05", "fetch", "wayback", 2],
+ ["otherupload1", "fetch", "archive.org", 1],
+ ["nothing00001", "text-only", null, 1],
+ ],
+ );
+ const first = r.recordings[0]!;
+ assert.equal(first.copy!.url, `https://web.archive.org/web/20260125093000/${watch("gone-video-05")}`);
+ assert.deepEqual(first.tried.map((t) => [t.from, t.found]), [["wayback", true]], "archive.org not asked once Wayback had it");
+ assert.deepEqual(r.recordings[2]!.tried.map((t) => [t.from, t.found]), [
+ ["wayback", false],
+ ["archive.org", false],
+ ]);
+ assert.equal(r.recordings[1]!.copy!.url, "https://archive.org/download/youtube-otherupload1/Another%20lost%20upload-otherupload1.mp4");
+ // Per recording, the CDX first; the archive.org search only when it had none.
+ assert.deepEqual(
+ wb.requests.map((q) => new URL(q.path, "http://x").searchParams.get("url")),
+ ["gone-video-05", "otherupload1", "nothing00001"].map(watch),
+ );
+ assert.ok(ia.requests.every((q) => !q.includes("gone-video-05")), "no archive.org search for the one Wayback found");
+ assert.equal(ia.requests.filter((q) => q.startsWith("/advancedsearch.php")).length, 2);
+
+ // The items: each found copy's windows, its URL as webpageUrl, the copy.
+ assert.deepEqual(
+ r.items.map((i) => [i.id, i.from, i.to, i.clipId, i.webpageUrl === i.copy?.url, i.copy?.from]),
+ [
+ ["gone-video-05", 0, 10, "a#c1", true, "wayback"],
+ ["gone-video-05", 30, 40, "a#c2", true, "wayback"],
+ ["otherupload1", 5, 15, "a#c3", true, "archive.org"],
+ ],
+ );
+ assert.ok(lines.some((l) => l.includes("nothing00001") && l.includes("its words only")));
+ } finally {
+ await close();
+ }
+});
+
+test("runFindCopy: the found windows go to ONE fetch-windows call; a dry run and a run that finds nothing start none", async () => {
+ const { deps, close } = await fakes();
+ try {
+ const calls: FetchWindowsItem[][] = [];
+ const start = async (items: FetchWindowsItem[]) => {
+ calls.push(items);
+ return { jobId: "J1" };
+ };
+ const dry = await runFindCopy({ ...opts(deps), dryRun: true, startFetch: start });
+ assert.equal(calls.length, 0);
+ assert.equal(dry.items.length, 3);
+ const run = await runFindCopy({ ...opts(deps), startFetch: start });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0]!.length, 3);
+ assert.deepEqual(run.fetch, { jobId: "J1" });
+ const none = await runFindCopy({
+ ...opts({ ...deps, missing: async () => ({ ...NEED, unfetchable: [NEED.unfetchable[3]] }) }),
+ startFetch: start,
+ });
+ assert.equal(calls.length, 1);
+ assert.equal(none.fetch, undefined);
+ assert.equal(none.recordings[0]!.outcome, "text-only");
+ } finally {
+ await close();
+ }
+});
+
+test("a Wayback that keeps refusing stops the run there; the rest are left for a later run", async () => {
+ const { deps, close } = await fakes({ waybackBusy: 50 });
+ try {
+ const r = await findCopies(opts(deps));
+ assert.equal(r.recordings.length, 1);
+ assert.equal(r.recordings[0]!.outcome, "error");
+ assert.match(r.stopped ?? "", /kept refusing/);
+ assert.deepEqual(r.items, []);
+ } finally {
+ await close();
+ }
+});
diff --git a/common/publish/findCopy.ts b/common/publish/findCopy.ts
@@ -0,0 +1,387 @@
+// FIND A COPY OF A GONE RECORDING (release 29 E2) — the deleted-video fallback.
+//
+// A report cites a moment of a recording its platform no longer serves
+// (deleted or made private: lib/sourceGone.ts). Its window cannot be fetched
+// from its own page, so `missingEvidenceWindows` lists it as "unfetchable:
+// gone". This looks for a copy, per recording, in order:
+//
+// 1. THE WAYBACK MACHINE: a capture of the recording's page that recorded a
+// 200 (the CDX API, lib/waybackClient.ts) — the newest — whose replay URL
+// `https://web.archive.org/web/<ts>/<page>` yt-dlp reads the video from;
+// 2. ARCHIVE.ORG: a mirror that names the YouTube id (in its identifier, its
+// title, its description or its original URL) and holds a video file —
+// an original preferred — fetched by its direct URL
+// `https://archive.org/download/<identifier>/<file>`.
+//
+// A copy found: the recording's cited windows go to fetch-windows with the
+// copy's URL as each item's `webpageUrl` (controller/fetchWindows.ts), so the
+// clips land in the recording's own `data/<id>/clips/`, and each window's
+// sidecar records which copy (`copy: {from, url}`, lib/clipWindow.ts). None
+// found: the windows are left, and compose shows the moments' words only,
+// marked "source deleted".
+//
+// PACED: one recording at a time; every Wayback and archive.org request goes
+// through the polite clients (one at a time, 2 s apart, 429s waited out). A
+// lookup that archive.org keeps refusing stops the run there; the rest are
+// left for a later run. The fetch is ONE fetch-windows job on the archive.org
+// clip queue, which walks its windows one at a time — one stream.
+
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ClipCopy } from "../lib/clipWindow";
+import type { GoneState } from "../lib/sourceGone";
+import { loadAvailability } from "../lib/availability-server";
+import { archiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { archiveOrgDownloadUrl } from "../lib/archiveOrgId";
+import { archiveOrgRestriction, searchArchiveOrgItems } from "../controller/archiveOrgImport";
+import { isArchiveOrgVideoFileName, type ArchiveOrgItemMetadata } from "../lib/archiveOrg";
+import { waybackClient, type WaybackCapture } from "../lib/waybackClient";
+import { resolveVideoDirId } from "../lib/videoDir-server.mjs";
+import { channelConfigPlatform } from "../lib/videoId";
+import { readChannelConfig } from "../controller/channels";
+import { findVideoSourceUrl } from "../controller/undownloadedVideos";
+import { missingEvidenceWindows, type EvidenceWindow, type MissingEvidenceWindows } from "./reportMedia";
+import type { ReportHost } from "./reportHost";
+import type { FetchWindowsItem } from "../controller/fetchWindows";
+
+// ─── A recording's page and its YouTube id ───
+
+// The page a gone recording was served at: its metadata's `webpage_url`, else
+// the one its availability check recorded, else the playlist's.
+export async function recordWebpageUrl(paths: Paths, slug: string, id: string): Promise<string | null> {
+ const config = await readChannelConfig(paths, slug).catch(() => null);
+ const dirId = await resolveVideoDirId(paths.channelsDir, slug, id, config ? { platform: channelConfigPlatform(config) } : {});
+ const dir = path.join(paths.channelsDir, slug, "data", dirId);
+ try {
+ const meta = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")) as { webpage_url?: unknown };
+ if (typeof meta.webpage_url === "string" && /^https?:\/\//.test(meta.webpage_url)) return meta.webpage_url;
+ } catch {
+ // no metadata: the next source
+ }
+ const av = await loadAvailability(dir).catch(() => null);
+ if (av?.webpageUrl && /^https?:\/\//.test(av.webpageUrl)) return av.webpageUrl;
+ return config ? findVideoSourceUrl(paths, slug, dirId, config).catch(() => null) : null;
+}
+
+const YOUTUBE_ID = /^[A-Za-z0-9_-]{6,20}$/;
+
+// The id a mirror would name: a watch URL's `v`, a youtu.be path, a
+// /shorts/ or /live/ path — else the record's own id.
+export function youtubeIdOf(watchUrl: string | null, recordId: string): string | null {
+ if (watchUrl) {
+ try {
+ const u = new URL(watchUrl);
+ const v = u.searchParams.get("v");
+ if (v && YOUTUBE_ID.test(v)) return v;
+ const seg = u.pathname.split("/").filter(Boolean);
+ if (u.hostname.endsWith("youtu.be") && seg[0] && YOUTUBE_ID.test(seg[0])) return seg[0];
+ const k = seg.findIndex((s) => s === "shorts" || s === "live" || s === "embed");
+ if (k >= 0 && seg[k + 1] && YOUTUBE_ID.test(seg[k + 1])) return seg[k + 1];
+ } catch {
+ // not a URL: the record's id
+ }
+ }
+ return YOUTUBE_ID.test(recordId) ? recordId : null;
+}
+
+// ─── archive.org: a mirror by YouTube id ───
+
+// archive.org's advanced search for a mirror of one YouTube upload: a
+// mirroring tool's identifier (`youtube-<id>`), its original URL, or the id
+// in its description or title.
+export function youtubeIdQuery(id: string): string {
+ if (!YOUTUBE_ID.test(id)) throw new Error(`"${id}" is not a YouTube id`);
+ return `identifier:(youtube-${id}) OR originalurl:(*${id}*) OR description:("${id}") OR title:("${id}")`;
+}
+
+const EXT_RANK = ["mp4", "webm", "mkv", "m4v", "mov"];
+const extOf = (name: string) => (/\.([A-Za-z0-9]{1,8})$/.exec(name)?.[1] ?? "").toLowerCase();
+
+// The item's video file for the upload: among its video files (a file naming
+// the id first, else every one when the item holds a single original video),
+// an ORIGINAL before a derivative, then mp4, webm, mkv, … Null when the item
+// holds none, or several originals none of which names the id (a channel
+// dump: which file is the upload cannot be told).
+export function pickMirrorFile(
+ item: Pick<ArchiveOrgItemMetadata, "files">,
+ youtubeId: string,
+): { file: string; source: "original" | "derivative"; size?: number } | null {
+ const videos = item.files.filter(
+ (f) => isArchiveOrgVideoFileName(f.name) && (f.source === "original" || f.source === "derivative"),
+ );
+ const named = videos.filter((f) => f.name.includes(youtubeId));
+ const originals = videos.filter((f) => f.source === "original");
+ const pool = named.length > 0 ? named : originals.length === 1 ? videos : [];
+ if (pool.length === 0) return null;
+ const rank = (f: { name: string; source?: string }) =>
+ (f.source === "original" ? 0 : 100) + (EXT_RANK.includes(extOf(f.name)) ? EXT_RANK.indexOf(extOf(f.name)) : EXT_RANK.length);
+ const best = [...pool].sort((a, b) => rank(a) - rank(b))[0]!;
+ const size = best.size && /^\d+$/.test(best.size) ? Number(best.size) : undefined;
+ return { file: best.name, source: best.source === "original" ? "original" : "derivative", ...(size !== undefined ? { size } : {}) };
+}
+
+export type ArchiveOrgMirror = {
+ identifier: string;
+ title?: string;
+ file: string;
+ // The file's direct download URL.
+ url: string;
+ source: "original" | "derivative";
+ size?: number;
+};
+
+export type ArchiveOrgMirrorSearch = {
+ youtubeId: string;
+ query: string;
+ found: number;
+ mirrors: ArchiveOrgMirror[];
+ // Items the search found that are not a usable mirror, and why.
+ skipped: { identifier: string; why: string }[];
+};
+
+const textOf = (v: unknown): string =>
+ typeof v === "string" ? v : Array.isArray(v) ? v.filter((x) => typeof x === "string").join(" ") : "";
+
+// archive.org mirrors of one YouTube upload: the search (one request), then
+// each hit's metadata (one request each, cached), at most `limit` items. An
+// item that does not name the id, is restricted, or holds no video file the
+// upload can be told by is skipped, with why.
+export async function findArchiveOrgMirrors(
+ youtubeId: string,
+ o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number } = {},
+): Promise<ArchiveOrgMirrorSearch> {
+ const client = o.client ?? archiveOrgClient;
+ const query = youtubeIdQuery(youtubeId);
+ const hits = await searchArchiveOrgItems(query, { client, rows: o.limit ?? 10, ...(o.signal ? { signal: o.signal } : {}) });
+ const mirrors: ArchiveOrgMirror[] = [];
+ const skipped: { identifier: string; why: string }[] = [];
+ for (const hit of hits.items) {
+ const item = await client.itemMetadata(hit.identifier, o.signal);
+ const meta = item.metadata as Record<string, unknown>;
+ const said = [item.metadata.identifier, textOf(meta.title), textOf(meta.description), textOf(meta.originalurl), ...item.files.map((f) => f.name)].join(" ");
+ if (!said.includes(youtubeId)) {
+ skipped.push({ identifier: hit.identifier, why: "it does not name the id" });
+ continue;
+ }
+ if (archiveOrgRestriction(item).item) {
+ skipped.push({ identifier: hit.identifier, why: "archive.org restricts it" });
+ continue;
+ }
+ const pick = pickMirrorFile(item, youtubeId);
+ if (!pick) {
+ skipped.push({ identifier: hit.identifier, why: "no video file of the upload can be told in it" });
+ continue;
+ }
+ const title = textOf(meta.title) || hit.title;
+ mirrors.push({
+ identifier: item.metadata.identifier,
+ ...(title ? { title } : {}),
+ file: pick.file,
+ url: archiveOrgDownloadUrl(item.metadata.identifier, pick.file),
+ source: pick.source,
+ ...(pick.size !== undefined ? { size: pick.size } : {}),
+ });
+ }
+ // Originals first, then the search's order.
+ mirrors.sort((a, b) => (a.source === b.source ? 0 : a.source === "original" ? -1 : 1));
+ return { youtubeId, query, found: hits.found, mirrors, skipped };
+}
+
+// ─── Wayback: the captures of a page ───
+
+export type WaybackLookup = { url: string; captures: WaybackCapture[] };
+
+// The captures of a page (every one, or only the 200s). Throws
+// ArchiveOrgRequestError when the CDX API keeps refusing.
+export async function waybackLookup(
+ url: string,
+ o: { client?: { captures: typeof waybackClient.captures }; okOnly?: boolean; limit?: number; signal?: AbortSignal } = {},
+): Promise<WaybackLookup> {
+ const client = o.client ?? waybackClient;
+ const captures = await client.captures(url, {
+ ...(o.okOnly ? { okOnly: true } : {}),
+ ...(o.limit ? { limit: o.limit } : {}),
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ return { url, captures };
+}
+
+// ─── find-copy ───
+
+export type FindCopyAttempt = {
+ from: ClipCopy["from"];
+ found: boolean;
+ url?: string;
+ // What was found or why not, in a phrase.
+ detail?: string;
+ error?: string;
+};
+
+export type FindCopyRecording = {
+ slug: string;
+ id: string;
+ gone: GoneState;
+ watchUrl: string | null;
+ youtubeId: string | null;
+ // The cited windows of the recording.
+ windows: EvidenceWindow[];
+ tried: FindCopyAttempt[];
+ copy?: ClipCopy;
+ // fetch a copy found: its windows go to fetch-windows
+ // text-only no copy: the moments show their words only ("source deleted")
+ // error a lookup failed: a later run tries again
+ outcome: "fetch" | "text-only" | "error";
+};
+
+export type FindCopyResult = {
+ host: string;
+ recordings: FindCopyRecording[];
+ // The fetch-windows items: each found copy's windows, its URL as the item's
+ // webpageUrl and the copy for the provenance.
+ items: FetchWindowsItem[];
+ // Why the run stopped before its last recording, when it did.
+ stopped?: string;
+};
+
+export type FindCopyDeps = {
+ wayback: { captures: typeof waybackClient.captures };
+ archive: ArchiveOrgClient;
+ missing: (paths: Paths, host: ReportHost) => Promise<MissingEvidenceWindows>;
+ webpageUrl: (paths: Paths, slug: string, id: string) => Promise<string | null>;
+};
+
+const DEFAULT_DEPS: FindCopyDeps = {
+ wayback: waybackClient,
+ archive: archiveOrgClient,
+ missing: (paths, host) => missingEvidenceWindows(paths, host),
+ webpageUrl: recordWebpageUrl,
+};
+
+// Look for a copy of every gone recording the host's reports cite: Wayback,
+// then archive.org, one recording at a time. Nothing is fetched here; the
+// answer's `items` are what fetch-windows is given (the caller starts it).
+export async function findCopies(opts: {
+ paths: Paths;
+ host: ReportHost;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<FindCopyDeps>;
+}): Promise<FindCopyResult> {
+ const deps: FindCopyDeps = { ...DEFAULT_DEPS, ...opts.deps };
+ const log = (line: string) => opts.onLog?.(line);
+ const need = await deps.missing(opts.paths, opts.host);
+ const byRecording = new Map<string, { slug: string; id: string; gone: GoneState; windows: EvidenceWindow[] }>();
+ for (const w of need.unfetchable) {
+ if (w.why !== "gone" || !w.gone) continue;
+ const key = `${w.slug}/${w.id}`;
+ const r = byRecording.get(key) ?? { slug: w.slug, id: w.id, gone: w.gone, windows: [] };
+ r.windows.push(w);
+ byRecording.set(key, r);
+ }
+ const result: FindCopyResult = { host: opts.host.id, recordings: [], items: [] };
+ log(`find-copy ${opts.host.id}: ${byRecording.size} gone recording(s) cited, ${[...byRecording.values()].reduce((n, r) => n + r.windows.length, 0)} window(s).`);
+
+ for (const r of byRecording.values()) {
+ if (opts.signal?.aborted) {
+ result.stopped = "cancelled";
+ break;
+ }
+ const watchUrl = await deps.webpageUrl(opts.paths, r.slug, r.id);
+ const youtubeId = youtubeIdOf(watchUrl, r.id);
+ const rec: FindCopyRecording = { ...r, watchUrl, youtubeId, tried: [], outcome: "text-only" };
+ result.recordings.push(rec);
+ let refused: string | undefined;
+
+ // 1. The Wayback Machine: the newest capture of the page that recorded a 200.
+ if (watchUrl) {
+ try {
+ const { captures } = await waybackLookup(watchUrl, { client: deps.wayback, okOnly: true, ...(opts.signal ? { signal: opts.signal } : {}) });
+ const ok = captures.filter((c) => c.status === "200");
+ const newest = ok[ok.length - 1];
+ if (newest) {
+ rec.copy = { from: "wayback", url: newest.replayUrl };
+ rec.tried.push({ from: "wayback", found: true, url: newest.replayUrl, detail: `${ok.length} capture(s) of the page; the newest, ${newest.timestamp}` });
+ } else {
+ rec.tried.push({ from: "wayback", found: false, detail: "no capture of the page" });
+ }
+ } catch (e) {
+ rec.tried.push({ from: "wayback", found: false, error: (e as Error).message });
+ if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message;
+ }
+ } else {
+ rec.tried.push({ from: "wayback", found: false, detail: "the recording's page is not known" });
+ }
+
+ // 2. archive.org: a mirror naming the YouTube id.
+ if (!rec.copy && !refused) {
+ if (youtubeId) {
+ try {
+ const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, ...(opts.signal ? { signal: opts.signal } : {}) });
+ const m = found.mirrors[0];
+ if (m) {
+ rec.copy = { from: "archive.org", url: m.url };
+ rec.tried.push({ from: "archive.org", found: true, url: m.url, detail: `${m.identifier}: ${m.file} (${m.source})` });
+ } else {
+ rec.tried.push({
+ from: "archive.org",
+ found: false,
+ detail: found.found ? `${found.found} item(s), none a mirror (${found.skipped.map((s) => `${s.identifier}: ${s.why}`).join("; ")})` : "no item names the id",
+ });
+ }
+ } catch (e) {
+ rec.tried.push({ from: "archive.org", found: false, error: (e as Error).message });
+ if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message;
+ }
+ } else {
+ rec.tried.push({ from: "archive.org", found: false, detail: "no YouTube id to search for" });
+ }
+ }
+
+ if (rec.copy) {
+ rec.outcome = "fetch";
+ for (const w of r.windows) {
+ result.items.push({
+ slug: w.slug,
+ id: w.id,
+ from: w.from,
+ to: w.to,
+ clipId: w.clipId,
+ ...(w.reason ? { reason: w.reason.slice(0, 400) } : {}),
+ webpageUrl: rec.copy.url,
+ copy: rec.copy,
+ });
+ }
+ } else if (rec.tried.some((t) => t.error)) {
+ rec.outcome = "error";
+ }
+ log(
+ ` ${r.slug}/${r.id} (${r.gone}, ${r.windows.length} window(s)): ` +
+ rec.tried.map((t) => `${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`).join("; ") +
+ ` → ${rec.outcome === "fetch" ? `fetch from the ${rec.copy!.from === "wayback" ? "Wayback capture" : "archive.org file"}` : rec.outcome === "text-only" ? "its words only" : "try again later"}`,
+ );
+ if (refused) {
+ result.stopped = `archive.org kept refusing (${refused}); the rest are left for a later run`;
+ log(`find-copy: ${result.stopped}.`);
+ break;
+ }
+ }
+ return result;
+}
+
+// find-copy, whole: the lookups, then (unless `dryRun`) ONE fetch-windows of
+// every found copy's windows through `startFetch` (the editor's job). A run
+// with nothing found starts nothing.
+export async function runFindCopy<T>(opts: {
+ paths: Paths;
+ host: ReportHost;
+ dryRun?: boolean;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<FindCopyDeps>;
+ startFetch: (items: FetchWindowsItem[]) => Promise<T>;
+}): Promise<FindCopyResult & { fetch?: T }> {
+ const found = await findCopies(opts);
+ if (opts.dryRun || found.items.length === 0) return found;
+ return { ...found, fetch: await opts.startFetch(found.items) };
+}
diff --git a/common/publish/missingEvidenceWindows.test.ts b/common/publish/missingEvidenceWindows.test.ts
@@ -124,6 +124,8 @@ test("on disk, to fetch, and what no window can fill", async () => {
elsewhere: "not-in-site",
});
assert.match(r.unfetchable.find((u) => u.id === "gone1")!.message, /deleted/);
+ // Release 29 E2: the one gone reading (lib/sourceGone.ts) names which.
+ assert.equal(r.unfetchable.find((u) => u.id === "gone1")!.gone, "deleted");
// The refusal names both keys that would let the site cite the channel.
assert.match(r.unfetchable.find((u) => u.id === "elsewhere")!.message, /`channels` nor its `citedChannels`/);
});
diff --git a/common/publish/reportMedia.test.ts b/common/publish/reportMedia.test.ts
@@ -281,3 +281,39 @@ test("a cited-only channel's moment is prepared; a channel in neither key is not
);
assert.match(index.problems[0].message, /"elsewhere" is in neither this site's `channels` nor its `citedChannels`/);
});
+
+// RELEASE 29 E2: a gone source with no media is a WARNING (`source-gone`), never
+// a problem — compose shows its words only. A live one with no media is still
+// a problem.
+test("a gone recording or a deleted, never-captured post with no media is a warning, not a problem", async () => {
+ const GSITE = "gone-site";
+ writeJson(path.join(videoDir(CH, "gone2"), "availability.json"), { checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" });
+ writeJson(path.join(paths.channelsDir, X, "posts-availability.json"), {
+ "333": { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" },
+ });
+ writeJson(path.join(paths.sitesDir, GSITE, "site.json"), { title: "Gone", channels: [{ slug: CH }, { slug: X }], reports: ["g1"] });
+ writeJson(
+ path.join(paths.sitesDir, GSITE, "reports", "g1", "report.json"),
+ report("g1", {
+ g01: { kind: "video", channel: CH, id: "gone2", start: 1, end: 2, quote: "gone" },
+ g02: { kind: "post", channel: X, id: "333", quote: "deleted" },
+ g03: { kind: "video", channel: CH, id: "missing2", start: 1, end: 2, quote: "live, no media" },
+ }),
+ );
+ const lines: string[] = [];
+ const index = await prepareReportMedia({ siteId: GSITE, settings: PUBLIC, onLog: (l) => lines.push(l) });
+ assert.deepEqual(
+ (index.warnings ?? []).map((w) => [w.kind, w.moment, w.citations]),
+ [
+ ["source-gone", `${CH}/gone2/1.00-2.00`, ["g1#g01"]],
+ ["source-gone", `${X}/333`, ["g1#g02"]],
+ ],
+ );
+ assert.match(index.warnings![0].message, /deleted.*words only.*Source deleted/);
+ assert.deepEqual(
+ index.problems.map((p) => [p.kind, p.moment]),
+ [["missing-media", `${CH}/missing2/1.00-2.00`]],
+ );
+ assert.ok(lines.some((l) => l.startsWith(` ! ${CH}/gone2/`)));
+ assert.ok(lines.some((l) => /1 problem\(s\), 2 warning\(s\)/.test(l)));
+});
diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts
@@ -65,9 +65,9 @@ import { momentKey, momentOf, momentProblem, type Moment } from "../lib/citation
import type { CitationPad } from "../lib/citations/schema";
import { parseReport } from "../lib/report/validate";
import { isReportId, type Report } from "../lib/report/schema";
-import { isPermanentlyGone } from "../lib/availability";
-import { loadAvailability } from "../lib/availability-server";
import { resolveVideoDir } from "../lib/videoDir-server.mjs";
+import { SOURCE_GONE_LABELS, type GoneState } from "../lib/sourceGone";
+import { postGoneState, sourceGoneState } from "../lib/sourceGone-server";
import { MAX_CLIP_WINDOW_SECONDS } from "../lib/clipWindow";
import {
citedEvidenceSpan,
@@ -159,7 +159,11 @@ export type ReportMediaProblemKind =
| "missing-media"
| "unreachable"
| "too-big"
- | "cut-failed";
+ | "cut-failed"
+ // A WARNING, never a problem (release 29 E2): a cited moment whose source is
+ // gone (lib/sourceGone.ts) and whose media is not on disk. Compose takes it
+ // as a text-only moment marked "source deleted".
+ | "source-gone";
export type ReportMediaProblem = {
kind: ReportMediaProblemKind;
@@ -180,6 +184,9 @@ export type ReportMediaIndex = {
preparedAt: string;
moments: Record<string, ReportMediaEntry>;
problems: ReportMediaProblem[];
+ // What does not fail the run: a gone source's moment with no media
+ // (`source-gone`). Absent when there is none.
+ warnings?: ReportMediaProblem[];
};
// One cited moment and everything that cites it.
@@ -292,6 +299,11 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
problems.push({ kind, moment: m.key, citations: m.citedBy, message });
log(` ✗ ${m.key}: ${message}`);
};
+ const warnings: ReportMediaProblem[] = [];
+ const warnGone = (m: CitedMoment, message: string) => {
+ warnings.push({ kind: "source-gone", moment: m.key, citations: m.citedBy, message });
+ log(` ! ${m.key}: ${message}`);
+ };
const posts: CitedMoment[] = [];
for (const m of moments) {
@@ -339,6 +351,11 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
fail(m, "unreachable", `${r.message}; the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`);
continue;
}
+ const gone = await sourceGoneState(await resolveVideoDir(paths.channelsDir, slug, m.moment.id));
+ if (gone) {
+ warnGone(m, `the source says the video is ${gone} and no copy is on disk: the moment shows its words only, marked "${SOURCE_GONE_LABELS[gone]}" (pnpm ops find-copy looks for a copy)`);
+ continue;
+ }
fail(m, "missing-media", `${r.message} — fetch the window or persist the video in the editor`);
continue;
}
@@ -359,7 +376,12 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
}
for (const miss of copiedPosts.missing) {
const m = postMoment.get(`${miss.channel}/${miss.id}`);
- if (m) fail(m, "missing-media", miss.message);
+ if (!m) continue;
+ if (await postGoneState(paths.channelsDir, miss.channel, miss.id)) {
+ warnGone(m, `the post is deleted and was never captured: the moment shows its words only, marked "${SOURCE_GONE_LABELS.deleted}"`);
+ continue;
+ }
+ fail(m, "missing-media", miss.message);
}
// The cache holds what the manifest names: a clip no moment names goes.
@@ -372,6 +394,7 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
preparedAt: (opts.now?.() ?? new Date()).toISOString(),
moments: Object.fromEntries(Object.keys(entries).sort().map((k) => [k, entries[k]])),
problems,
+ ...(warnings.length > 0 ? { warnings } : {}),
};
await writeJsonAtomic(storeMediaIndexFile(host), index, { mkdir: true });
const bytes = Object.values(entries).reduce(
@@ -380,7 +403,9 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
);
log(
`${Object.keys(entries).length} of ${moments.length} moment(s) prepared (${mib(bytes)}); ` +
- `${problems.length} problem(s).`,
+ `${problems.length} problem(s)` +
+ (warnings.length ? `, ${warnings.length} warning(s) (a gone source's moment shows its words only)` : "") +
+ ".",
);
return index;
}
@@ -442,7 +467,9 @@ export async function readStoreMediaIndex(store: Pick<ReportStore, "stagingDir">
// not-in-site the channel is not one of the site's (prepare's not-in-site)
// unreachable the channel's media is on a drive that is not answering —
// not missing, and a fetch would write beside the wrong thing
-// gone availability.json says deleted, private or members-only
+// gone the source says the video is deleted or private (the one
+// reading, lib/sourceGone.ts; `gone` names which) — no window
+// can be fetched from it; find-copy looks for a copy
// audio-only a feed record: its media is the episode's audio, which a
// download fetches; a window selector has no picture to pick
// too-long longer than one window may be — persist the video instead
@@ -468,6 +495,8 @@ export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "audio-
export type UnfetchableEvidenceWindow = EvidenceWindow & {
why: UnfetchableReason;
+ // A `gone` window: what the source says (lib/sourceGone.ts).
+ gone?: GoneState;
message: string;
};
@@ -545,9 +574,9 @@ export async function missingEvidenceWindows(paths: Paths, siteOrHost: string |
unfetchable("unreachable", `the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`);
continue;
}
- const availability = (await loadAvailability(await resolveVideoDir(paths.channelsDir, slug, id)))?.availability;
- if (isPermanentlyGone(availability)) {
- unfetchable("gone", `the source says the video is ${availability}`);
+ const gone = await sourceGoneState(await resolveVideoDir(paths.channelsDir, slug, id));
+ if (gone) {
+ out.unfetchable.push({ ...window, why: "gone", gone, message: `the source says the video is ${gone}` });
continue;
}
if (audioOnly) {
diff --git a/common/social/blueskyEndpoints.ts b/common/social/blueskyEndpoints.ts
@@ -0,0 +1,58 @@
+// Where Bluesky is: the public AppView (the read API, no login), the web app
+// (bsky.app, the page a post capture screenshots) and the CDN (a post's
+// images). One place, so a test can put all three on a fake.
+//
+// TEST-ONLY: E2E_BLUESKY_ORIGIN_FILE names a file holding ONE loopback origin
+// (`http://127.0.0.1:<port>`). While that file exists, all three hosts are
+// that origin — the editor e2e suite's fake Bluesky
+// (common/testing/social/fakeBluesky.mjs), which a spec starts and names in
+// the file. The file is read per call, so a spec can start its fake after the
+// test server booted. Anything but a loopback origin in it is ignored. Unset
+// everywhere but the editor's e2e server. Unit tests pass endpoints directly.
+
+import { readFileSync } from "node:fs";
+
+export type BlueskyEndpoints = {
+ // The public AppView: com.atproto.identity.resolveHandle,
+ // app.bsky.feed.getPosts, getAuthorFeed, getProfile.
+ appview: string;
+ // The web app: /profile/<handle>/post/<rkey>.
+ web: string;
+ // The image CDN: a post's `embed.images[].fullsize`.
+ cdn: string;
+};
+
+export const BLUESKY_ENDPOINTS: Readonly<BlueskyEndpoints> = Object.freeze({
+ appview: "https://public.api.bsky.app",
+ web: "https://bsky.app",
+ cdn: "https://cdn.bsky.app",
+});
+
+const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/;
+
+export function blueskyEndpoints(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): BlueskyEndpoints {
+ const file = env.E2E_BLUESKY_ORIGIN_FILE;
+ if (file) {
+ let origin = "";
+ try {
+ origin = readFileSync(file, "utf8").trim().replace(/\/$/, "");
+ } catch {
+ origin = "";
+ }
+ if (LOOPBACK_ORIGIN.test(origin)) return { appview: origin, web: origin, cdn: origin };
+ }
+ return { ...BLUESKY_ENDPOINTS };
+}
+
+// A Bluesky URL (one of the three real hosts) on `endpoints`: the AppView's
+// image URLs name cdn.bsky.app, which a fake must serve. Any other URL is
+// returned as it is.
+export function onBlueskyEndpoints(url: string, endpoints: BlueskyEndpoints): string {
+ for (const key of ["appview", "web", "cdn"] as const) {
+ const real = BLUESKY_ENDPOINTS[key];
+ if (url === real || url.startsWith(`${real}/`)) return endpoints[key] + url.slice(real.length);
+ }
+ return url;
+}
diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts
@@ -30,8 +30,11 @@ import {
type SocialFetcher,
type SocialFetcherProbe,
} from "./fetchers";
+import { blueskyEndpoints } from "./blueskyEndpoints";
+import { captureBlueskyPosts, liveBlueskyCaptureDeps } from "./blueskyPostCapture";
-const APPVIEW = "https://public.api.bsky.app";
+// The AppView's origin, read per call (blueskyEndpoints.ts: a test's fake).
+const appview = () => blueskyEndpoints().appview;
const PLC_DIRECTORY = "https://plc.directory";
// getAuthorFeed's documented ceiling.
@@ -293,7 +296,7 @@ export async function resolveHandle(
handle: string,
signal?: AbortSignal,
): Promise<string> {
- const url = `${APPVIEW}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
+ const url = `${appview()}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
const body = await getJson<{ did?: string }>(url, signal);
if (!body.did) throw new Error(`No DID for handle ${handle}`);
return body.did;
@@ -312,7 +315,7 @@ export async function getProfile(
actor: string,
signal?: AbortSignal,
): Promise<BskyProfile> {
- const url = `${APPVIEW}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(actor)}`;
+ const url = `${appview()}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(actor)}`;
return getJson<BskyProfile>(url, signal);
}
@@ -354,7 +357,7 @@ async function getAuthorFeed(
});
if (cursor) params.set("cursor", cursor);
return getJson<BskyFeedResponse>(
- `${APPVIEW}/xrpc/app.bsky.feed.getAuthorFeed?${params.toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getAuthorFeed?${params.toString()}`,
signal,
);
}
@@ -517,7 +520,7 @@ blueskyFetcher.checkAvailability = async ({ ids, handle, signal, onLog }) => {
}
try {
const body = await getJson<{ posts?: BskyPostView[] }>(
- `${APPVIEW}/xrpc/app.bsky.feed.getPosts?${params.toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getPosts?${params.toString()}`,
signal,
);
const alive = new Set(
@@ -551,7 +554,7 @@ blueskyFetcher.fetchOne = async ({ post, channelSlug, signal, onLog }: OnePostFe
const uri = `at://${did}/app.bsky.feed.post/${post.id}`;
onLog?.(`Reading ${uri}`);
const body = await getJson<{ posts?: BskyPostView[] }>(
- `${APPVIEW}/xrpc/app.bsky.feed.getPosts?${new URLSearchParams({ uris: uri }).toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getPosts?${new URLSearchParams({ uris: uri }).toString()}`,
signal,
);
const view = (body.posts ?? []).find((v) => rkeyFromAtUri(v.uri) === post.id);
@@ -561,4 +564,9 @@ blueskyFetcher.fetchOne = async ({ post, channelSlug, signal, onLog }: OnePostFe
}
};
+// A screenshot of each post as bsky.app renders it, and its images (release
+// 29 E1): blueskyPostCapture.ts — the AppView for liveness and image URLs, a
+// headless browser with no login for the shot.
+blueskyFetcher.captureByIds = (input) => captureBlueskyPosts(input, liveBlueskyCaptureDeps(input));
+
registerSocialFetcher(blueskyFetcher);
diff --git a/common/social/blueskyPostCapture.test.ts b/common/social/blueskyPostCapture.test.ts
@@ -0,0 +1,313 @@
+// The Bluesky post capture (release 29 E1), over the fake Bluesky on loopback
+// (common/testing/social/fakeBluesky.mjs): its AppView answers liveness and
+// image URLs, its CDN the images, and its bsky.app-shaped page the shot — in
+// a stub page for the run's logic, and in a real headless Chromium for the
+// crop (skipped, saying why, on a host with no browser). No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/blueskyPostCapture.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { PNG as FAKE_PNG, startFakeBluesky } from "../testing/social/fakeBluesky.mjs";
+import { blueskyEndpoints, onBlueskyEndpoints, BLUESKY_ENDPOINTS } from "./blueskyEndpoints";
+import {
+ blueskyPageGapMs,
+ blueskyPostImages,
+ captureBlueskyPosts,
+ openFreshBlueskyPage,
+ shootBlueskyPost,
+ type BlueskyCaptureDeps,
+} from "./blueskyPostCapture";
+import { blueskyFetcher } from "./blueskyFetcher";
+import { capturePostsProblem } from "../controller/capturePosts";
+import { readPostCapture, SHOT_FILENAME } from "./postCapture";
+import type { PageLike } from "./playwrightRuntime";
+import type { PostCaptureInput } from "./fetchers";
+import { pngSize } from "../publish/citedPostCaptures";
+
+const HANDLE = "synthbaker.bsky.social";
+const IMAGE_POST = "3lsynthpost0001";
+const TEXT_POST = "3lsynthpost0002";
+const DELETED_POST = "3lsynthpost0003";
+
+// A page that answers the capture's calls without a browser: the post is
+// there (one thread item by the author), its box a fixed rect, its shot a PNG.
+function stubPage() {
+ const visited: string[] = [];
+ const page: PageLike = {
+ goto: async (url: string) => {
+ visited.push(url);
+ return { status: () => 200 };
+ },
+ waitForSelector: async () => ({}),
+ waitForTimeout: async () => {},
+ evaluate: async (fn: string) =>
+ fn.includes("postThreadItem-by-") ? { count: 1, rect: { x: 220, y: 70, width: 600, height: 300 }, text: "" } : 0,
+ on: () => {},
+ screenshot: async () => new Uint8Array(FAKE_PNG),
+ };
+ return { page, visited };
+}
+
+async function setup(opts: { busyTimes?: number } = {}) {
+ const bsky = await startFakeBluesky(opts);
+ const outDir = await mkdtemp(path.join(os.tmpdir(), "bsky-capture-"));
+ const pauses: number[] = [];
+ const stub = stubPage();
+ let opened = 0;
+ const deps: BlueskyCaptureDeps = {
+ fetch: (url, init) => bsky.fetch(url, init),
+ endpoints: { ...BLUESKY_ENDPOINTS },
+ openPage: async () => {
+ opened++;
+ return { page: stub.page, close: async () => {} };
+ },
+ pageGapMs: () => 3_500,
+ imageGapMs: () => 1_200,
+ pause: async (ms) => {
+ pauses.push(ms);
+ },
+ now: () => new Date("2026-10-15T12:00:00.000Z"),
+ };
+ const input = (ids: string[], extra: Partial<PostCaptureInput> = {}): PostCaptureInput => ({
+ ids,
+ handle: HANDLE,
+ outDir,
+ signal: new AbortController().signal,
+ ...extra,
+ });
+ return {
+ bsky,
+ outDir,
+ pauses,
+ stub,
+ deps,
+ input,
+ opened: () => opened,
+ close: async () => {
+ await bsky.close();
+ await rm(outDir, { recursive: true, force: true });
+ },
+ };
+}
+
+test("endpoints: the real hosts by default; a test's loopback origin from E2E_BLUESKY_ORIGIN_FILE, nothing else", async () => {
+ assert.deepEqual(blueskyEndpoints({}), BLUESKY_ENDPOINTS);
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bsky-origin-"));
+ try {
+ const file = path.join(dir, "origin");
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), BLUESKY_ENDPOINTS, "no file yet");
+ await writeFile(file, "http://127.0.0.1:4567\n");
+ const o = "http://127.0.0.1:4567";
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), { appview: o, web: o, cdn: o });
+ await writeFile(file, "https://evil.example");
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), BLUESKY_ENDPOINTS, "not loopback: ignored");
+ const fake = { appview: o, web: o, cdn: o };
+ assert.equal(onBlueskyEndpoints("https://cdn.bsky.app/img/x/y@jpeg", fake), `${o}/img/x/y@jpeg`);
+ assert.equal(onBlueskyEndpoints("https://bsky.app/profile/a/post/b", fake), `${o}/profile/a/post/b`);
+ assert.equal(onBlueskyEndpoints("https://example.com/a.png", fake), "https://example.com/a.png");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the fetcher can capture: capturePostsProblem passes a Bluesky channel with no special case", () => {
+ assert.equal(typeof blueskyFetcher.captureByIds, "function");
+ assert.equal(capturePostsProblem(blueskyFetcher), null);
+});
+
+test("images: an images embed, a recordWithMedia's media, the full size first", () => {
+ assert.deepEqual(
+ blueskyPostImages({ embed: { images: [{ fullsize: "https://cdn.bsky.app/a", thumb: "https://cdn.bsky.app/t", alt: "A" }] } }),
+ [{ url: "https://cdn.bsky.app/a", alt: "A" }],
+ );
+ assert.deepEqual(blueskyPostImages({ embed: { media: { images: [{ thumb: "https://cdn.bsky.app/t" }] } } }), [
+ { url: "https://cdn.bsky.app/t" },
+ ]);
+ assert.deepEqual(blueskyPostImages({}), []);
+});
+
+test("the page gap: at least 3 s, jittered up to double; a channel's longer pause raises it", () => {
+ assert.equal(blueskyPageGapMs(() => 0), 3_000);
+ assert.equal(blueskyPageGapMs(() => 0.999), 5_997);
+ assert.equal(blueskyPageGapMs(() => 0, 1_000), 3_000, "never under the floor");
+ assert.equal(blueskyPageGapMs(() => 0.5, 10_000), 15_000);
+});
+
+test("a capture: the image post (shot, 2 images, record), the text post, the deleted post — paced, one page at a time", async () => {
+ const s = await setup();
+ try {
+ const res = await captureBlueskyPosts(s.input([IMAGE_POST, TEXT_POST, DELETED_POST]), s.deps);
+ assert.equal(res.stoppedEarly, undefined);
+ assert.deepEqual(
+ res.outcomes.map((o) => [o.id, o.state, o.availability, o.files]),
+ [
+ [IMAGE_POST, "captured", "available", 3],
+ [TEXT_POST, "captured", "available", 1],
+ [DELETED_POST, "deleted", "deleted", 0],
+ ],
+ );
+
+ const imageDir = path.join(s.outDir, IMAGE_POST);
+ assert.deepEqual((await readdir(imageDir)).sort(), ["capture.json", "media-1.png", "media-2.png", SHOT_FILENAME]);
+ assert.deepEqual(new Uint8Array(await readFile(path.join(imageDir, "media-1.png"))), new Uint8Array(FAKE_PNG));
+ const rec = await readPostCapture(imageDir);
+ assert.equal(rec?.state, "captured");
+ assert.equal(rec?.url, `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`);
+ assert.equal(rec?.shot?.name, SHOT_FILENAME);
+ assert.equal(rec?.mediaState, "ok");
+ assert.deepEqual(
+ rec?.media.map((m) => [m.name, m.url]),
+ [
+ ["media-1.png", "https://cdn.bsky.app/img/did:plc:synthbaker0000000000000/oven.png"],
+ ["media-2.png", "https://cdn.bsky.app/img/did:plc:synthbaker0000000000000/shop.png"],
+ ],
+ );
+
+ const text = await readPostCapture(path.join(s.outDir, TEXT_POST));
+ assert.equal(text?.mediaState, "none");
+ assert.ok(text?.shot);
+
+ const gone = await readPostCapture(path.join(s.outDir, DELETED_POST));
+ assert.equal(gone?.state, "deleted");
+ assert.equal(gone?.shot, undefined);
+
+ // Two pages (never the deleted post's), one browser, the gap before the second.
+ assert.deepEqual(s.stub.visited, [
+ `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`,
+ `https://bsky.app/profile/${HANDLE}/post/${TEXT_POST}`,
+ ]);
+ assert.equal(s.opened(), 1);
+ assert.deepEqual(s.pauses, [1_200, 3_500], "an image gap, then the page gap");
+ // One handle lookup, ONE getPosts for all three.
+ const xrpc = s.bsky.requests.filter((r) => r.startsWith("/xrpc/"));
+ assert.equal(xrpc.length, 2);
+ assert.match(xrpc[1], /getPosts\?uris=.*uris=.*uris=/);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a second run skips what is captured; force asks again; a deleted post is settled", async () => {
+ const s = await setup();
+ try {
+ await captureBlueskyPosts(s.input([IMAGE_POST, DELETED_POST]), s.deps);
+ const before = s.bsky.requests.length;
+ const again = await captureBlueskyPosts(s.input([IMAGE_POST, DELETED_POST]), s.deps);
+ assert.deepEqual(again.outcomes, []);
+ assert.equal(s.bsky.requests.length, before, "nothing asked");
+ const forced = await captureBlueskyPosts(s.input([IMAGE_POST], { force: true }), s.deps);
+ assert.deepEqual(forced.outcomes.map((o) => o.state), ["captured"]);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a 429 from the AppView is waited out (its Retry-After) and asked again", async () => {
+ const s = await setup({ busyTimes: 1 });
+ try {
+ const res = await captureBlueskyPosts(s.input([TEXT_POST], { media: false }), s.deps);
+ assert.deepEqual(res.outcomes.map((o) => o.state), ["captured"]);
+ assert.equal(s.pauses[0], 1_000, "Retry-After: 1");
+ assert.equal(s.bsky.requests.filter((r) => r.includes("resolveHandle")).length, 2);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a 429 that persists stops the run with nothing recorded about the posts", async () => {
+ const s = await setup({ busyTimes: 50 });
+ try {
+ const res = await captureBlueskyPosts(s.input([TEXT_POST]), { ...s.deps, maxAttempts: 3 });
+ assert.deepEqual(res.outcomes, []);
+ assert.match(res.stoppedEarly ?? "", /Could not resolve .*429/);
+ assert.equal(s.pauses.length, 2, "two waits between three attempts");
+ } finally {
+ await s.close();
+ }
+});
+
+test("a cancelled run stops between posts; the rest are left", async () => {
+ const s = await setup();
+ try {
+ const ctl = new AbortController();
+ const deps: BlueskyCaptureDeps = {
+ ...s.deps,
+ pause: async (ms) => {
+ s.pauses.push(ms);
+ ctl.abort();
+ },
+ };
+ const res = await captureBlueskyPosts(s.input([TEXT_POST, IMAGE_POST], { signal: ctl.signal, media: false }), deps);
+ assert.deepEqual(res.outcomes.map((o) => o.id), [TEXT_POST]);
+ assert.match(res.stoppedEarly ?? "", /Cancelled/);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a page that does not show the post is an error; the AppView's liveness stands", async () => {
+ const s = await setup();
+ try {
+ const stub = stubPage();
+ stub.page.waitForSelector = async () => {
+ throw new Error("Timeout 20000ms exceeded");
+ };
+ stub.page.evaluate = async () => ({ count: 0, rect: null, text: "post not found" });
+ const deps: BlueskyCaptureDeps = { ...s.deps, openPage: async () => ({ page: stub.page, close: async () => {} }) };
+ const res = await captureBlueskyPosts(s.input([TEXT_POST], { media: false }), deps);
+ assert.equal(res.outcomes[0].state, "error");
+ assert.equal(res.outcomes[0].availability, "available", "the AppView said it is live");
+ assert.match(res.outcomes[0].error ?? "", /did not render/);
+ } finally {
+ await s.close();
+ }
+});
+
+// ─── A real browser over the fake's page ───
+
+test("a real headless Chromium shoots the post, cropped to it, over the fake page on loopback", async (t) => {
+ let opened;
+ try {
+ opened = await openFreshBlueskyPage();
+ } catch (e) {
+ t.skip(`no headless Chromium on this host: ${(e as Error).message.split("\n")[0].slice(0, 120)}`);
+ return;
+ }
+ const bsky = await startFakeBluesky();
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bsky-shot-"));
+ try {
+ const res = await shootBlueskyPost(opened.page, {
+ url: bsky.pageUrl(HANDLE, IMAGE_POST),
+ canonicalUrl: `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`,
+ handle: HANDLE,
+ text: "The second shop opens in the spring. Small place, big oven.",
+ dir,
+ signal: new AbortController().signal,
+ });
+ assert.equal(res.state, "captured", res.error);
+ const size = await pngSize(path.join(dir, SHOT_FILENAME));
+ assert.ok(size, "a PNG");
+ // The thread item is 600 CSS px wide in a 1280-px window, at 2x: cropped to
+ // the post, not the page (its header, side bar and the reply below).
+ assert.equal(size!.width, 1200);
+ assert.ok(size!.height > 100 && size!.height < 800, `height ${size!.height}`);
+ const gone = await shootBlueskyPost(opened.page, {
+ url: bsky.pageUrl(HANDLE, DELETED_POST),
+ canonicalUrl: "x",
+ handle: HANDLE,
+ text: "",
+ dir: path.join(dir, "gone"),
+ signal: new AbortController().signal,
+ postTimeoutMs: 1_500,
+ });
+ assert.equal(gone.state, "error");
+ } finally {
+ await opened.close();
+ await bsky.close();
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/social/blueskyPostCapture.ts b/common/social/blueskyPostCapture.ts
@@ -0,0 +1,579 @@
+// Capturing specific Bluesky posts (release 29 E1): a screenshot of each post
+// as bsky.app renders it, and its images, into `posts-media/<id>/`
+// (postCapture.ts owns the layout and the record). No login, ever.
+//
+// TWO SOURCES, EACH ASKED AS LITTLE AS IT CAN BE:
+// - the public AppView (`app.bsky.feed.getPosts`, 25 posts a request, the
+// same batch the deleted-post sweep uses) says which posts are live — one
+// absent from the answer is deleted, recorded as X's capture records it —
+// and where each live post's images are (`embed.images[].fullsize`, or a
+// recordWithMedia's `media.images`);
+// - a headless Chromium, ONE fresh context with no profile and no cookies,
+// opens each live post's page (`bsky.app/profile/<handle>/post/<rkey>`),
+// waits for the post (`[data-testid="postThreadItem-by-<handle>"]`) and
+// shoots that element — cropped to the post, not the page — as shot.png.
+//
+// PACED: one page at a time, a real gap (3–6 s, jittered; a channel's
+// `postPagePauseSeconds` raises it) before every page after the first, a
+// timeout per page, cancellable between and during posts. A 429 from the
+// AppView or the CDN is waited out (its Retry-After, else 5 s, 10 s, … capped)
+// and asked again a few times; one that persists stops the run there, the
+// rest left for a later run. A page that answers 429 is waited out once; a
+// second stops the run.
+//
+// What a capture finds, per post:
+// captured live, shot (and its images downloaded)
+// deleted absent from getPosts — the platform says the post is gone; no
+// page is opened, and what an earlier capture took is kept
+// error the page did not show the post (a timeout, an author who
+// shows posts only to signed-in users, a post the page could
+// not tell from others), or an image failed; a later run tries
+// again
+//
+// Base URLs are injectable (deps.endpoints; blueskyEndpoints.ts for the e2e
+// suite's fake), and so is everything that waits or touches the network.
+
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { postPermalink, type PostAvailability } from "../lib/posts";
+import { parseRetryAfterMs } from "../lib/archiveOrgClient";
+import { blueskyEndpoints, onBlueskyEndpoints, type BlueskyEndpoints } from "./blueskyEndpoints";
+import type { PostCaptureInput, PostCaptureOutcome, PostCaptureResult } from "./fetchers";
+import { importPlaywright, type PageLike } from "./playwrightRuntime";
+import {
+ captureWork,
+ describeCapturedFile,
+ postCaptureDir,
+ readPostCapture,
+ SHOT_FILENAME,
+ writePostCapture,
+ type CapturedFile,
+ type CaptureMediaState,
+ type PostCaptureRecord,
+ type PostCaptureState,
+} from "./postCapture";
+
+// ─── The AppView's answer (only what the capture reads) ───
+
+type ImageView = { fullsize?: string; thumb?: string; alt?: string };
+export type BlueskyPostView = {
+ uri?: string;
+ author?: { did?: string; handle?: string };
+ record?: { text?: string };
+ embed?: { $type?: string; images?: ImageView[]; media?: { images?: ImageView[] } };
+};
+
+const rkeyOf = (uri: string | undefined): string | null => {
+ const i = uri?.lastIndexOf("/") ?? -1;
+ return uri && i >= 0 && i < uri.length - 1 ? uri.slice(i + 1) : null;
+};
+
+// A live post's images, as the AppView names them: an images embed, or the
+// media half of a recordWithMedia. The full-size URL, else the thumbnail.
+export function blueskyPostImages(view: BlueskyPostView): { url: string; alt?: string }[] {
+ const list = view.embed?.images ?? view.embed?.media?.images ?? [];
+ const out: { url: string; alt?: string }[] = [];
+ for (const im of list) {
+ const url = im?.fullsize ?? im?.thumb;
+ if (typeof url !== "string" || !/^https?:\/\//.test(url)) continue;
+ out.push({ url, ...(im.alt ? { alt: im.alt } : {}) });
+ }
+ return out;
+}
+
+// getPosts' documented ceiling.
+export const GET_POSTS_BATCH = 25;
+
+// The gap before each page after a run's first: 3–6 s, or the channel's own
+// pause (at least 3 s) jittered to [1, 2) of itself.
+export const MIN_PAGE_GAP_MS = 3_000;
+export function blueskyPageGapMs(random: () => number, baseMs?: number): number {
+ const base = Math.max(MIN_PAGE_GAP_MS, baseMs ?? MIN_PAGE_GAP_MS);
+ return Math.round(base * (1 + random()));
+}
+
+// ─── Deps ───
+
+export type BlueskyCaptureDeps = {
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
+ endpoints: BlueskyEndpoints;
+ // A page in a fresh browser context: opened on the first shot, closed at the
+ // end of the run.
+ openPage: () => Promise<{ page: PageLike; close: () => Promise<void> }>;
+ // The gap before each page after the first, and between two images.
+ pageGapMs: () => number;
+ imageGapMs: () => number;
+ pause: (ms: number, signal: AbortSignal) => Promise<void>;
+ now?: () => Date;
+ // A 429/503 retry's wait when the answer names none (doubling per attempt),
+ // its cap, and how many attempts a request gets.
+ backoffBaseMs?: number;
+ backoffMaxMs?: number;
+ maxAttempts?: number;
+ // How long a page may take to load, and the post to appear on it.
+ pageTimeoutMs?: number;
+ postTimeoutMs?: number;
+};
+
+export function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (ms <= 0 || signal.aborted) return resolve();
+ const timer = setTimeout(done, ms);
+ function done() {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", done);
+ resolve();
+ }
+ signal.addEventListener("abort", done, { once: true });
+ });
+}
+
+// A headless Chromium with a fresh context: no profile directory, no cookies,
+// no stored state — what a logged-out reader sees.
+export async function openFreshBlueskyPage(): Promise<{ page: PageLike; close: () => Promise<void> }> {
+ const { chromium } = await importPlaywright();
+ const browser = await chromium.launch({ headless: true });
+ try {
+ const context = await browser.newContext({
+ viewport: { width: 1280, height: 1600 },
+ deviceScaleFactor: 2,
+ locale: "en-US",
+ colorScheme: "light",
+ });
+ const page = await context.newPage();
+ return {
+ page,
+ close: async () => {
+ await context.close().catch(() => {});
+ await browser.close().catch(() => {});
+ },
+ };
+ } catch (err) {
+ await browser.close().catch(() => {});
+ throw err;
+ }
+}
+
+export function liveBlueskyCaptureDeps(input: Pick<PostCaptureInput, "pagePauseMs">): BlueskyCaptureDeps {
+ return {
+ fetch: (url, init) => fetch(url, init),
+ endpoints: blueskyEndpoints(),
+ openPage: openFreshBlueskyPage,
+ pageGapMs: () => blueskyPageGapMs(Math.random, input.pagePauseMs),
+ imageGapMs: () => 1_000 + Math.round(Math.random() * 1_000),
+ pause: sleepUnlessAborted,
+ };
+}
+
+// ─── Requests, with the 429 back-off ───
+
+type Got =
+ | { ok: true; res: Response }
+ | { ok: false; error: string; rateLimited?: boolean; status?: number };
+
+async function politeGet(
+ deps: BlueskyCaptureDeps,
+ url: string,
+ accept: string,
+ signal: AbortSignal,
+ onLog?: (line: string) => void,
+): Promise<Got> {
+ const attempts = deps.maxAttempts ?? 4;
+ const base = deps.backoffBaseMs ?? 5_000;
+ const cap = deps.backoffMaxMs ?? 120_000;
+ const now = () => (deps.now ?? (() => new Date()))().getTime();
+ let last = "";
+ for (let attempt = 1; attempt <= attempts; attempt++) {
+ let res: Response;
+ try {
+ res = await deps.fetch(url, { signal, headers: { accept } });
+ } catch (err) {
+ if (signal.aborted) return { ok: false, error: "cancelled" };
+ return { ok: false, error: firstLine(err) };
+ }
+ if (res.ok) return { ok: true, res };
+ if (res.status !== 429 && res.status !== 503) {
+ await res.arrayBuffer().catch(() => {});
+ return { ok: false, error: `HTTP ${res.status}`, status: res.status };
+ }
+ last = `HTTP ${res.status}`;
+ await res.arrayBuffer().catch(() => {});
+ if (attempt === attempts) break;
+ const wait = Math.min(cap, parseRetryAfterMs(res.headers.get("retry-after"), now()) ?? base * 2 ** (attempt - 1));
+ onLog?.(`Bluesky answered ${res.status}; waiting ${Math.round(wait / 1000)} s before asking again.`);
+ await deps.pause(wait, signal);
+ if (signal.aborted) return { ok: false, error: "cancelled" };
+ }
+ return { ok: false, error: `Bluesky kept answering ${last} after ${attempts} attempts`, rateLimited: true };
+}
+
+// ─── One page's shot ───
+
+// The post on its page: the thread items by its author (a self-thread's
+// parents and replies share the test id), the one holding the post's text —
+// or the only one. Marked for the shot; its box in document coordinates.
+const SNAPSHOT_SCRIPT = (handle: string, text: string) => `(() => {
+ const sel = ${JSON.stringify(`[data-testid="postThreadItem-by-${handle}"]`)};
+ const norm = (s) => (s || "").replace(/\\s+/g, " ").trim().toLowerCase();
+ const want = norm(${JSON.stringify(text)}).slice(0, 80);
+ const all = Array.from(document.querySelectorAll(sel));
+ let own = all.length === 1 ? all[0] : null;
+ if (!own && want) own = all.find((el) => norm(el.innerText).includes(want)) || null;
+ for (const el of document.querySelectorAll("[data-archilyzer-capture]")) el.removeAttribute("data-archilyzer-capture");
+ if (!own) return { count: all.length, rect: null, text: norm(document.body && document.body.innerText).slice(0, 2000) };
+ own.setAttribute("data-archilyzer-capture", "");
+ const r = own.getBoundingClientRect();
+ return { count: all.length, rect: { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }, text: "" };
+})()`;
+
+// Let the post's images finish loading (each capped), so the shot is not of
+// grey boxes.
+const IMAGES_LOADED_SCRIPT = `(() => {
+ const own = document.querySelector("[data-archilyzer-capture]") || document;
+ const imgs = Array.from(own.querySelectorAll("img")).filter((i) => !i.complete);
+ return Promise.all(imgs.map((i) => new Promise((r) => {
+ i.addEventListener("load", r, { once: true });
+ i.addEventListener("error", r, { once: true });
+ setTimeout(r, 5000);
+ }))).then(() => imgs.length);
+})()`;
+
+type Snapshot = { count: number; rect: { x: number; y: number; width: number; height: number } | null; text: string };
+
+export type BlueskyShotResult = {
+ state: PostCaptureState;
+ shot?: CapturedFile;
+ error?: string;
+ // The page answered 429.
+ rateLimited?: boolean;
+};
+
+function raceAbort<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) return Promise.reject(new Error("cancelled"));
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(new Error("cancelled"));
+ signal.addEventListener("abort", onAbort, { once: true });
+ p.then(
+ (v) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(v);
+ },
+ (e) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(e);
+ },
+ );
+ });
+}
+
+// One post's screenshot: load its page, wait for the post, shoot that element.
+// Writes `shot.png` into `dir` only for a post that rendered. `url` is the
+// page to open; `canonicalUrl` the bsky.app URL the record names.
+export async function shootBlueskyPost(
+ page: PageLike,
+ o: {
+ url: string;
+ canonicalUrl: string;
+ handle: string;
+ text: string;
+ dir: string;
+ signal: AbortSignal;
+ pageTimeoutMs?: number;
+ postTimeoutMs?: number;
+ },
+): Promise<BlueskyShotResult> {
+ let response: unknown;
+ try {
+ response = await raceAbort(
+ page.goto(o.url, { waitUntil: "domcontentloaded", timeout: o.pageTimeoutMs ?? 45_000 }),
+ o.signal,
+ );
+ } catch (err) {
+ return { state: "error", error: `Could not load ${o.canonicalUrl}: ${firstLine(err)}` };
+ }
+ const status = (response as { status?: () => number } | null)?.status?.();
+ if (status === 429) return { state: "error", error: "bsky.app answered 429", rateLimited: true };
+ const sel = `[data-testid="postThreadItem-by-${o.handle}"]`;
+ const appeared = await raceAbort(
+ page.waitForSelector(sel, { timeout: o.postTimeoutMs ?? 20_000 }).then(
+ () => true,
+ () => false,
+ ),
+ o.signal,
+ ).catch(() => false);
+ if (o.signal.aborted) return { state: "error", error: "cancelled" };
+ if (!appeared) {
+ const snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text)).catch(() => null)) as Snapshot | null;
+ const body = snap?.text ?? "";
+ if (/sign in|log in/.test(body) && /(required|to view|logged-in|signed-in)/.test(body)) {
+ return { state: "error", error: "The author shows their posts only to signed-in users; the capture has no login." };
+ }
+ return { state: "error", error: `The post did not render (no ${sel} on the page).` };
+ }
+ await page.waitForTimeout(1_000);
+ let snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text))) as Snapshot;
+ if (!snap.rect) {
+ return { state: "error", error: `${snap.count} posts by @${o.handle} on the page, none of them this one's text.` };
+ }
+ await page.evaluate(IMAGES_LOADED_SCRIPT).catch(() => {});
+ // Re-read the box: images that loaded may have grown it.
+ snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text))) as Snapshot;
+ const rect = snap.rect;
+ if (!rect || rect.width < 1 || rect.height < 1) {
+ return { state: "error", error: "The post rendered with no size to shoot." };
+ }
+ let png: Uint8Array;
+ try {
+ // fullPage, so a post taller than the window is shot whole; the clip is in
+ // document coordinates, which is what the snapshot measured.
+ png = await page.screenshot({
+ type: "png",
+ fullPage: true,
+ clip: {
+ x: Math.max(0, Math.floor(rect.x)),
+ y: Math.max(0, Math.floor(rect.y)),
+ width: Math.ceil(rect.width),
+ height: Math.ceil(rect.height),
+ },
+ });
+ } catch (err) {
+ return { state: "error", error: `The screenshot failed: ${firstLine(err)}` };
+ }
+ await mkdir(o.dir, { recursive: true });
+ await writeFile(path.join(o.dir, SHOT_FILENAME), png);
+ return { state: "captured", shot: await describeCapturedFile(o.dir, SHOT_FILENAME, o.canonicalUrl) };
+}
+
+// ─── The images ───
+
+const EXT_BY_TYPE: Record<string, string> = {
+ "image/jpeg": "jpg",
+ "image/png": "png",
+ "image/gif": "gif",
+ "image/webp": "webp",
+ "image/avif": "avif",
+};
+
+function imageExt(url: string, contentType: string | null): string {
+ const ct = (contentType ?? "").split(";")[0].trim().toLowerCase();
+ if (EXT_BY_TYPE[ct]) return EXT_BY_TYPE[ct];
+ // The CDN names the format after an "@": …/<cid>@jpeg.
+ const at = /@(jpeg|jpg|png|webp|gif)$/i.exec(url);
+ if (at) return at[1].toLowerCase() === "jpeg" ? "jpg" : at[1].toLowerCase();
+ const m = /\.([a-z0-9]{2,5})(?:[?#]|$)/i.exec(url);
+ return m ? m[1].toLowerCase() : "jpg";
+}
+
+// ─── The run ───
+
+// A run's errors in a row that stop it: a host whose network or browser is
+// failing every post should not page through the rest of the list.
+const STOP_AFTER_ERRORS = 3;
+
+export async function captureBlueskyPosts(
+ input: PostCaptureInput,
+ deps: BlueskyCaptureDeps,
+): Promise<PostCaptureResult> {
+ const { signal, onLog } = input;
+ const wanted = { shots: input.shots ?? true, media: input.media ?? true, force: input.force ?? false };
+ const now = deps.now ?? (() => new Date());
+ const outcomes: PostCaptureOutcome[] = [];
+ const stopped = (why: string): PostCaptureResult => {
+ onLog?.(why);
+ return { outcomes, stoppedEarly: why };
+ };
+
+ // What each post is owed, from what is on disk.
+ const owed: { id: string; dir: string; existing: PostCaptureRecord | null; shot: boolean; media: boolean }[] = [];
+ for (const id of input.ids) {
+ const dir = postCaptureDir(input.outDir, id);
+ const existing = await readPostCapture(dir);
+ const work = captureWork(existing, { ...wanted, articles: false });
+ if (!work.shot && !work.media) {
+ onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`);
+ continue;
+ }
+ owed.push({ id, dir, existing, shot: work.shot, media: work.media });
+ }
+ if (owed.length === 0) return { outcomes };
+
+ // The account's DID: getPosts takes AT-URIs.
+ const appview = deps.endpoints.appview;
+ let did = input.handle;
+ if (!did.startsWith("did:")) {
+ const got = await politeGet(
+ deps,
+ `${appview}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(input.handle)}`,
+ "application/json",
+ signal,
+ onLog,
+ );
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (!got.ok) return stopped(`Could not resolve @${input.handle}: ${got.error}. Nothing was recorded.`);
+ const body = (await got.res.json().catch(() => null)) as { did?: string } | null;
+ if (!body?.did) return stopped(`Could not resolve @${input.handle}: no DID in the answer. Nothing was recorded.`);
+ did = body.did;
+ }
+
+ // Liveness and images, 25 posts a request. A post absent from a batch that
+ // answered is deleted; a batch that failed says nothing about its posts.
+ const views = new Map<string, BlueskyPostView>();
+ const unanswered = new Map<string, string>();
+ for (let i = 0; i < owed.length; i += GET_POSTS_BATCH) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ const batch = owed.slice(i, i + GET_POSTS_BATCH);
+ const params = new URLSearchParams();
+ for (const o of batch) params.append("uris", `at://${did}/app.bsky.feed.post/${o.id}`);
+ const got = await politeGet(deps, `${appview}/xrpc/app.bsky.feed.getPosts?${params.toString()}`, "application/json", signal, onLog);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (!got.ok) {
+ if (got.rateLimited) return stopped(`${got.error}; stopping — the posts are left for a later run.`);
+ for (const o of batch) unanswered.set(o.id, `getPosts failed: ${got.error}`);
+ continue;
+ }
+ const body = (await got.res.json().catch(() => null)) as { posts?: BlueskyPostView[] } | null;
+ if (!body || !Array.isArray(body.posts)) {
+ for (const o of batch) unanswered.set(o.id, "getPosts answered no post list");
+ continue;
+ }
+ for (const v of body.posts) {
+ const rkey = rkeyOf(v.uri);
+ if (rkey) views.set(rkey, v);
+ }
+ }
+
+ let pages = 0;
+ let errorsInARow = 0;
+ let browser: { page: PageLike; close: () => Promise<void> } | undefined;
+ try {
+ for (const [i, o] of owed.entries()) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run.");
+ const { id, dir, existing } = o;
+ onLog?.(`[${i + 1}/${owed.length}] ${id}`);
+ const view = views.get(id);
+ const failedLookup = unanswered.get(id);
+ const author = view?.author?.handle || input.handle;
+ const canonicalUrl = postPermalink("bluesky", author, id);
+
+ let state: PostCaptureState;
+ let availability: PostAvailability | undefined;
+ let shot = existing?.shot;
+ let mediaState: CaptureMediaState = existing?.mediaState ?? "skipped";
+ let media: CapturedFile[] = existing?.media ?? [];
+ let error: string | undefined;
+ let stop: string | undefined;
+
+ if (failedLookup) {
+ // Nothing learned about the post: what is on disk stands.
+ state = "error";
+ error = failedLookup;
+ } else if (!view) {
+ // The platform says it is gone. What an earlier capture took is kept.
+ state = "deleted";
+ availability = "deleted";
+ } else {
+ availability = "available";
+ // A run that does not shoot keeps the shot's verdict on disk.
+ state = o.shot ? "error" : (existing?.state ?? "captured");
+ if (o.shot) {
+ if (pages++ > 0) await deps.pause(deps.pageGapMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ browser ??= await deps.openPage();
+ const shotArgs = {
+ url: onBlueskyEndpoints(`https://bsky.app/profile/${author}/post/${id}`, deps.endpoints),
+ canonicalUrl,
+ handle: author,
+ text: view.record?.text ?? "",
+ dir,
+ signal,
+ ...(deps.pageTimeoutMs ? { pageTimeoutMs: deps.pageTimeoutMs } : {}),
+ ...(deps.postTimeoutMs ? { postTimeoutMs: deps.postTimeoutMs } : {}),
+ };
+ let res = await shootBlueskyPost(browser.page, shotArgs);
+ if (res.rateLimited) {
+ const wait = Math.max(deps.backoffBaseMs ?? 30_000, deps.pageGapMs());
+ onLog?.(`bsky.app answered 429; waiting ${Math.round(wait / 1000)} s before one more try.`);
+ await deps.pause(wait, signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ res = await shootBlueskyPost(browser.page, shotArgs);
+ if (res.rateLimited) stop = "bsky.app answered 429 twice; stopping.";
+ }
+ state = res.state;
+ if (res.shot) shot = res.shot;
+ if (res.error) error = res.error;
+ }
+ const postIsThere = state === "captured" || !o.shot;
+ if (o.media && postIsThere && !stop) {
+ const images = blueskyPostImages(view);
+ if (images.length === 0) {
+ mediaState = "none";
+ media = [];
+ } else {
+ media = [];
+ let failed = 0;
+ for (const [n, im] of images.entries()) {
+ if (n > 0) await deps.pause(deps.imageGapMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ const got = await politeGet(deps, onBlueskyEndpoints(im.url, deps.endpoints), "image/*", signal, onLog);
+ if (!got.ok) {
+ failed++;
+ onLog?.(`${id}: image ${n + 1} failed: ${got.error}`);
+ if (got.rateLimited) {
+ stop = `${got.error}; stopping.`;
+ break;
+ }
+ continue;
+ }
+ const name = `media-${n + 1}.${imageExt(im.url, got.res.headers.get("content-type"))}`;
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, name), new Uint8Array(await got.res.arrayBuffer()));
+ media.push(await describeCapturedFile(dir, name, im.url));
+ }
+ mediaState = failed > 0 ? "error" : "ok";
+ if (failed > 0) error = error ? `${error}; ${failed} image(s) failed` : `${failed} image(s) failed`;
+ }
+ if (!o.shot && !existing && mediaState === "error") state = "error";
+ }
+ }
+
+ const record: PostCaptureRecord = {
+ version: 1,
+ id,
+ url: canonicalUrl,
+ capturedAt: now().toISOString(),
+ state,
+ ...(shot ? { shot } : {}),
+ mediaState,
+ media,
+ ...(error ? { error } : {}),
+ };
+ await writePostCapture(dir, record);
+ outcomes.push({
+ id,
+ state,
+ ...(availability ? { availability } : {}),
+ files: (shot ? 1 : 0) + media.length,
+ ...(error ? { error } : {}),
+ });
+ onLog?.(
+ `${id}: ${state}` +
+ (state === "captured" && o.shot ? ", shot" : "") +
+ (mediaState === "ok" ? `, ${media.length} image(s)` : mediaState === "none" && view ? ", no images" : "") +
+ (error ? ` — ${error}` : ""),
+ );
+ if (stop) return stopped(`${stop} Stopped at ${id}; the rest are left for a later run.`);
+ errorsInARow = state === "error" ? errorsInARow + 1 : 0;
+ if (errorsInARow >= STOP_AFTER_ERRORS) {
+ return stopped(`${STOP_AFTER_ERRORS} posts in a row failed; stopping rather than paging through the rest.`);
+ }
+ }
+ return { outcomes };
+ } finally {
+ await browser?.close().catch(() => {});
+ }
+}
+
+function firstLine(err: unknown): string {
+ return ((err as Error)?.message ?? String(err)).split("\n")[0];
+}
diff --git a/common/testing/archiveOrg/fakeArchiveOrg.mjs b/common/testing/archiveOrg/fakeArchiveOrg.mjs
@@ -13,7 +13,12 @@
// Routes:
// GET /advancedsearch.php?q=…&rows=N items whose identifier, title or
// subject contains every word of q
-// (`*` matches all), identifier order
+// (`*` matches all), identifier order;
+// a q of `field:value` clauses joined by
+// OR (release 29: a YouTube id search)
+// matches an item whose metadata field
+// contains any clause's value (quotes,
+// parentheses, `*` and `\` dropped)
// GET /metadata/<id> the item, or {} (archive.org's answer
// for an unknown id)
// opts.busyTimes the first N requests answer 429
@@ -50,6 +55,26 @@ export const ITEMS = [
},
files: [{ name: "members.mp4", source: "original", format: "MPEG4", size: "5000" }],
},
+ // A mirror of a recording deleted on its platform (release 29): the corpus's
+ // GONE_RECORD, uploaded by a mirroring tool with the id in its identifier,
+ // its description and its original URL. Not "bakery": the search tests
+ // count those.
+ {
+ metadata: {
+ identifier: "youtube-gone-video-05",
+ title: "The old oven review",
+ date: "2026-01-20",
+ mediatype: "movies",
+ collection: ["opensource_movies"],
+ description: "Mirror of https://video.example/watch?v=gone-video-05",
+ originalurl: "https://video.example/watch?v=gone-video-05",
+ },
+ files: [
+ { name: "The old oven review-gone-video-05.webm", source: "original", format: "WebM", size: "3000000", length: "20.0" },
+ { name: "The old oven review-gone-video-05.mp4", source: "derivative", format: "h.264", original: "The old oven review-gone-video-05.webm", size: "2000000" },
+ { name: "The old oven review-gone-video-05.info.json", source: "original", format: "JSON", size: "1500" },
+ ],
+ },
{
metadata: {
identifier: "synth-radio-tape-01",
@@ -88,8 +113,18 @@ export async function startFakeArchiveOrg(opts = {}) {
const q = u.searchParams.get("q") ?? "";
const rows = Number(u.searchParams.get("rows") ?? 50);
const want = q.trim() === "*" ? [] : words(q);
+ const clauses = q.split(/\s+OR\s+/).map((c) => c.trim().replace(/^\(+|\)+$/g, ""));
+ const fielded = clauses.length > 0 && clauses.every((c) => /^[a-z_]+:/i.test(c));
+ const fieldMatch = (it) =>
+ clauses.some((c) => {
+ const i = c.indexOf(":");
+ const field = c.slice(0, i);
+ const value = c.slice(i + 1).replace(/["()*\\]/g, "").trim().toLowerCase();
+ return value !== "" && flat(it.metadata[field]).toLowerCase().includes(value);
+ });
const hits = items
.filter((it) => {
+ if (fielded) return fieldMatch(it);
const hay = new Set(words(`${it.metadata.identifier} ${flat(it.metadata.title)} ${flat(it.metadata.subject)}`));
return want.every((w) => hay.has(w));
})
diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts
@@ -34,6 +34,7 @@ import {
clipsDirFor,
clipWindowFile,
clipWindowName,
+ type ClipCopy,
type ClipProvenance,
} from "../lib/clipWindow";
import {
@@ -92,6 +93,8 @@ export type FetchWindowProvenance = {
reason?: string;
pad?: number;
requestedAt?: string;
+ // The copy of a gone recording the URL is (release 29 E2, find-copy).
+ copy?: ClipCopy;
};
export type FetchWindowOpts = {
@@ -353,6 +356,7 @@ export async function fetchWindowManaged(
...(typeof opts.provenance.pad === "number"
? { pad: opts.provenance.pad }
: {}),
+ ...(opts.provenance.copy ? { copy: opts.provenance.copy } : {}),
bytes: st.size,
fetchedAt: new Date().toISOString(),
ytdlp: { args },
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,14 @@
# Changelog
## [Unreleased]
+- **The verdict bench asks to the operator's standard, and says which prompt it asked with.** What each verdict means is written once (`common/lib/report/verdicts.mjs`) and read by the bench's prompt, REPORT.md and umtool's bench page: CORROBORATED when 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), PARTLY only when a part is shown overstated or wrong, and when in doubt between the two, CORROBORATED. The model now writes its reason before its verdict, and sees the report's title, the claim's section, and each cited line's speaker and recording date. Each run records its prompt version and a hash of its items; a run made before this is version 1, and a run is never resumed under another version. Needs a restart of the editor and umtool.
+- **`archilyzer reports bench-verdicts` takes `--items-from <run>`, `--window-mode seconds|turn` and a stratified `--limit`.** `--items-from vb-r28` asks the same items again (for example a local model on a new prompt, at no cost). `--window-mode turn` shows the cited speaker's turn instead of a fixed number of seconds either side, bounded by `--window`. `--limit` keeps every verdict the operator ruled, in proportion. A re-run of a run asks only the models it names, so a local-only re-run never asks a paid model again. A citation that gives no transcript is listed with its reason instead of being left out silently. `pnpm ops bench-verdicts` takes the same keys (`itemsFrom`, `windowMode`, `limit`).
+- **umtool's verdict bench compares runs and takes your marks.** `/tools/bench` shows each run's prompt version and items hash, and **compare with** lists the runs over the same items: each model's agreement in both and every claim whose answer changed. Each disagreement has **Right** and **Wrong** (was the model right?), kept beside the run, and the not-CORROBORATED precision and recall beside the bar are shown as ruled and with your marks, so the bar can be set from what you marked. "What the verdicts mean" lists the definitions.
+- **A cited video that was deleted no longer stops a report from publishing.** When a report cites a moment of a recording that its platform has since deleted or made private, and no copy of it is on disk, the report's page now shows that moment's words only, marked **Source deleted** (or **Source made private**), on its card and its moment page — instead of `reports prepare` and the build refusing the whole report. A deleted post that was never captured is shown the same way. `reports prepare` and `reports check` list each one as a warning. A moment of a recording that is still up and has no clip is still refused, as before. Needs a restart of the editor; the sites show it after their next build.
+- **`pnpm ops find-copy` looks for a copy of a deleted video and fetches the cited seconds from it.** For one article (`{"article": "<id>"}`), every published article (`{"articles": true}`) or a site's reports (`{"siteId": "<id>"}`), it takes each cited recording that is deleted or private, looks for a Wayback Machine capture of its page, then for an archive.org mirror that names its YouTube id, and fetches the cited windows from the copy it finds as one paced job. The clips land with the recording's other clips, and each one's record says which copy it came from. With `"dryRun": true` it only says what it found. A recording with no copy anywhere is left to show its words only. Needs a restart of the editor.
+- **`pnpm ops wayback-lookup` lists the Wayback Machine's captures of a page** — a URL, or a recording's own page (`{"slug", "id"}`), with `"okOnly": true` for the captures that loaded. **`pnpm ops archive-search --json '{"youtubeId": "<id>"}'`** finds archive.org mirrors of one YouTube video and gives each one's direct video file link. Both are read only and paced as archive.org asks.
+- **Fetch windows refuses a window of a deleted or private video** unless the item names another page to fetch it from (what `find-copy` does), instead of asking the dead page.
+- **Capture posts works for Bluesky channels, with no login.** `pnpm ops capture-posts --json '{"slug": "<channel>", "ids": [...]}'` on a Bluesky channel now reads which posts are still up from Bluesky's public API, opens each live post's bsky.app page in a headless browser with no account, and saves a screenshot cropped to the post (`shot.png`) and the post's images beside it, in the channel's `posts-media/<id>/` — what a report's moment page shows. A post Bluesky no longer has is recorded as deleted in the channel's post availability, and nothing is opened for it. One page at a time, a few seconds apart; a "slow down" from Bluesky is waited out, and one that persists stops the run with the rest left for later. Needs a restart of the editor.
- **The research board keeps a key pressed just after a save, too.** A key that arrived after a save's answer, or after its redraw but before the moved line took the focus back, could still lose `e`'s field (the claim then went nowhere). The board now waits until the redraw is fully done before acting on any key. Needs a restart of umtool.
- **A recurring report's tick no longer calls a capped scan "nothing new".** Triage used to take the scope from one `enumerate_matches(".")`, which stops at 2,000 recordings — the co-host pilot's five channels hold 23,284, the newest read last, so its first tick found "0 new" and ended quiet. Tier 0 now lists the scope from the build's own per-channel manifests (every recording, uncapped, dated by the build's index) and reads the terms only over the new recordings (and, on a first run, from the start date). A scan that still hits a cap or misses a channel is **partial**: the tick says "partial — not reached: …" as a **Your call** card in umtool (never quiet, no quiet edition recorded), the triage run says so on its page, and its set of seen recordings is not kept, so the next run counts new from the last complete run (or from its start date). The same rule holds for a Refresh's search again (a capped search with nothing new ends **partial**, not "no change"), a series' window check, and the Inbox's daily refresh check (a partial check still raises its card, naming what it did not reach; `umtool refresh --check` prints PARTIAL). Needs a restart of the editor and umtool.
- **`enumerate_matches` takes `ids`.** Only the pages that hold those recordings are read, so the scan is bounded by them rather than by the scope; the footer says how many the scope holds. A sweep restricted to given recordings (a refresh's update, a triage's escalation) now scans only theirs.
diff --git a/editor/app/api/ops/_benchVerdicts.test.ts b/editor/app/api/ops/_benchVerdicts.test.ts
@@ -73,6 +73,12 @@ test("the body: models required, the run id and reports checked, numbers as numb
assert.throws(() => parseBenchVerdictsBody({ models: ["m"], reports: ["Bad Id"] }), /"reports" is a list of article ids/);
assert.throws(() => parseBenchVerdictsBody({ models: ["m"], window: "60" }), /"window" is a number/);
assert.deepEqual(parseBenchVerdictsBody({ models: "a, b", maxUsd: 2, limit: 3 }), { models: ["a", "b"], maxUsd: 2, limit: 3 });
+ // Release 29 V1: the window mode and items-from.
+ assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], windowMode: "turn" }), { models: ["q"], windowMode: "turn" });
+ assert.throws(() => parseBenchVerdictsBody({ models: ["q"], windowMode: "line" }), /"windowMode" is "seconds" or "turn"/);
+ 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/);
});
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 () => {
diff --git a/editor/app/api/ops/_research.test.ts b/editor/app/api/ops/_research.test.ts
@@ -50,3 +50,51 @@ test("import-post: refused before any job — not a post URL, not a posts channe
assert.equal(noUrl.status, 400);
assert.deepEqual(await corpus.listJobIds(), before, "nothing was queued");
});
+
+// Release 29 E2: archive-search's YouTube-id mode, wayback-lookup and find-copy
+// — refused at the door before anything reaches archive.org.
+test("archive-search: youtubeId or query, not both; an id is an id", async () => {
+ const search = await route("archive-search");
+ const both = await callPost(search, { query: "x", youtubeId: "dQw4w9WgXcQ" });
+ assert.equal(both.status, 400);
+ assert.match(String(both.body.error), /either "query" or "youtubeId"/);
+ const bad = await callPost(search, { youtubeId: "not an id" });
+ assert.equal(bad.status, 400);
+ assert.match(String(bad.body.error), /is not a YouTube id/);
+});
+
+test("wayback-lookup: a URL or a record, not both; an http(s) URL; a record with no known page is a 404", async () => {
+ const lookup = await route("wayback-lookup");
+ const none = await callPost(lookup, {});
+ assert.equal(none.status, 400);
+ assert.match(String(none.body.error), /"url" \(a page\) or "slug" and "id"/);
+ const both = await callPost(lookup, { url: "https://a.example/x", slug: "test-youtube", id: "x" });
+ assert.equal(both.status, 400);
+ const ftp = await callPost(lookup, { url: "ftp://a.example/x" });
+ assert.equal(ftp.status, 400);
+ assert.match(String(ftp.body.error), /http\(s\) URL/);
+ const big = await callPost(lookup, { url: "https://a.example/x", limit: 501 });
+ assert.equal(big.status, 400);
+ // A record of no channel: no page to look up (a YouTube channel's record would
+ // be given its watch URL from its id, and asked of the real Wayback — never
+ // in a test).
+ const unknown = await callPost(lookup, { slug: "no-such-channel", id: "no-such-video" });
+ assert.equal(unknown.status, 404);
+ assert.match(String(unknown.body.error), /no page is known for no-such-channel\/no-such-video/);
+});
+
+test("find-copy: exactly one of article, articles, siteId; an unknown one is refused before any lookup", async () => {
+ const find = await route("find-copy");
+ const before = await corpus.listJobIds();
+ assert.equal((await callPost(find, {})).status, 400);
+ const two = await callPost(find, { article: "a", siteId: "b" });
+ assert.equal(two.status, 400);
+ assert.match(String(two.body.error), /send one of "article"/);
+ const noArticle = await callPost(find, { article: "no-such-article", dryRun: true });
+ assert.equal(noArticle.status, 400);
+ assert.match(String(noArticle.body.error), /no article "no-such-article"/);
+ const noSite = await callPost(find, { siteId: "no-such-site" });
+ assert.equal(noSite.status, 400);
+ assert.match(String(noSite.body.error), /No site "no-such-site"/);
+ assert.deepEqual(await corpus.listJobIds(), before, "nothing was queued");
+});
diff --git a/editor/app/api/ops/archive-search/route.ts b/editor/app/api/ops/archive-search/route.ts
@@ -4,21 +4,50 @@ import {
ARCHIVE_ORG_SEARCH_MAX_ROWS,
searchArchiveOrgItems,
} from "yt-dlp-transcript-common/controller/archiveOrgImport";
-import { OpsInputError, ops, opsFail, optPositiveInt, reqString } from "../_lib";
+import { findArchiveOrgMirrors } from "yt-dlp-transcript-common/publish/findCopy";
+import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqString } from "../_lib";
export const dynamic = "force-dynamic";
// POST { query, limit? } -> { ok: true, query, found, items: [{ identifier, title? }] }
+// | { youtubeId, limit? } -> { ok: true, youtubeId, query, found,
+// items: [{ identifier, title?, file, url, source, size? }],
+// skipped: [{ identifier, why }] }
//
// An archive.org search (its advanced-search syntax), read only: ONE request
// through the editor's polite archive.org client — the same client, gap and
// back-off an import uses (controller/archiveOrgImport.ts) — the first
// `limit` items (default 50, at most 500) in identifier order. Nothing is
// written; `import-archive-org` with `query` imports what a search finds.
+//
+// `youtubeId` (release 29 E2) looks for MIRRORS of one YouTube upload: items
+// naming the id in their identifier, title, description or original URL
+// (publish/findCopy.ts), each read for its files (one request each), and
+// answers each mirror's direct video file URL
+// (`https://archive.org/download/<identifier>/<file>`, an original preferred).
+// An item that does not name the id, is restricted, or holds no file the
+// upload can be told by is `skipped`, with why. `limit` defaults to 10 here.
const ARCHIVE_SEARCH_DEFAULT_LIMIT = 50;
+const MIRROR_DEFAULT_LIMIT = 10;
export async function POST(request: Request) {
- return ops(request, ["query", "limit"], async (body) => {
+ return ops(request, ["query", "limit", "youtubeId"], async (body) => {
+ const youtubeId = optString(body, "youtubeId")?.trim();
+ if (youtubeId !== undefined && body.query !== undefined) {
+ throw new OpsInputError('send either "query" or "youtubeId", not both');
+ }
+ if (youtubeId !== undefined) {
+ if (!/^[A-Za-z0-9_-]{6,20}$/.test(youtubeId)) throw new OpsInputError(`"${youtubeId}" is not a YouTube id`);
+ const limit = optPositiveInt(body, "limit") ?? MIRROR_DEFAULT_LIMIT;
+ if (limit > ARCHIVE_ORG_SEARCH_MAX_ROWS) throw new OpsInputError(`"limit" is at most ${ARCHIVE_ORG_SEARCH_MAX_ROWS}`);
+ try {
+ const r = await findArchiveOrgMirrors(youtubeId, { limit });
+ return NextResponse.json({ ok: true, youtubeId, query: r.query, found: r.found, items: r.mirrors, skipped: r.skipped });
+ } catch (e) {
+ if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, 502);
+ throw e;
+ }
+ }
const query = reqString(body, "query");
const limit = optPositiveInt(body, "limit") ?? ARCHIVE_SEARCH_DEFAULT_LIMIT;
if (limit > ARCHIVE_ORG_SEARCH_MAX_ROWS) {
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?, maxUsd?, limit? }
+// POST { models, run?, reports?, window?, windowMode?, maxUsd?, limit?, itemsFrom? }
// -> { ok: true, jobId, run }
//
// The verdict bench (release 28 M7), as a `bench-verdicts` job: every ruled
@@ -16,7 +16,9 @@ export const dynamic = "force-dynamic";
// whole run (default 5); an API run is refused past the day's cap. `run`
// names a run to continue (its answered pairs are skipped). The results are
// local-only: `.generation/bench/verdicts/<run>/` (umtool's /bench reads
-// them). `job cancel` stops it; the log ends `@@bench-verdicts {json}`.
+// them). Release 29 V1: `windowMode` ("turn": the cited speaker's turn),
+// a stratified `limit`, `itemsFrom` (an earlier run's exact items).
+// `job cancel` stops it; the log ends `@@bench-verdicts {json}`.
//
// AN ADAPTER: the refusals are the controller's (controller/benchVerdicts.ts).
export async function POST(request: Request) {
diff --git a/editor/app/api/ops/capture-posts/route.test.ts b/editor/app/api/ops/capture-posts/route.test.ts
@@ -94,6 +94,16 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive
name: "Example (Bluesky)",
url: "https://bsky.app/profile/example.bsky.social",
});
+ // An X channel on the Nitter fetcher, which has no capture.
+ await channel("example-nitter", {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "x-nitter",
+ socialHandle: "example_user",
+ name: "Example (X, Nitter)",
+ url: "https://x.com/example_user",
+ });
// An X channel with an empty posts archive.
await channel("example-x", {
handling: "transcribe",
@@ -109,9 +119,15 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive
assert.equal(video.status, 400);
assert.equal(video.error, "test-filter is not a social channel.");
+ const nitter = await post({ slug: "example-nitter", ids: ["1"] });
+ assert.equal(nitter.status, 400);
+ assert.match(nitter.error, /cannot capture posts/);
+
+ // Bluesky captures (release 29 E1): its fetcher passes, and the id that is
+ // not in the channel's archive is what is refused.
const bsky = await post({ slug: "example-bsky", ids: ["1"] });
assert.equal(bsky.status, 400);
- assert.match(bsky.error, /cannot capture posts/);
+ assert.equal(bsky.error, "1 id(s) not in example-bsky's posts archive: 1");
const neither = await post({ slug: "example-x", ids: ["1"], shots: false, media: false });
assert.equal(neither.status, 400);
diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts
@@ -0,0 +1,40 @@
+import { NextResponse } from "next/server";
+import { findCopyAction } from "../../../channels/[slug]/videos/findCopyAction";
+import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { article } | { siteId } | { articles: true }, dryRun?
+// -> { ok, dryRun, host, recordings: [{ slug, id, gone, watchUrl, youtubeId,
+// windows, tried: [{ from, found, url?, detail?, error? }], copy?,
+// outcome: fetch | text-only | error }], items, stopped?, jobId? }
+//
+// A COPY OF EVERY GONE RECORDING THE REPORTS CITE (release 29 E2,
+// publish/findCopy.ts): of one article (`article`), every published
+// article (`articles`), or a site's reports (`siteId`), the cited windows
+// whose recording is deleted or private ("unfetchable: gone"). Per recording,
+// one at a time: the Wayback Machine (a capture of its page that recorded a
+// 200, the newest) then archive.org (a mirror naming its YouTube id, an
+// original video file preferred). The windows of every copy found go to ONE
+// fetch-windows job on the archive.org clip queue, each with the copy's URL as
+// its page, so the clips land in the recording's own clips/ with the copy in
+// their provenance. A recording with no copy is left: its moments show their
+// words only ("source deleted"). `dryRun` answers the lookups and starts
+// nothing. The lookups run in the request, paced.
+export async function POST(request: Request) {
+ return ops(request, ["article", "siteId", "articles", "dryRun"], async (body) => {
+ const article = optString(body, "article")?.trim();
+ const siteId = optString(body, "siteId")?.trim();
+ const articles = optBool(body, "articles") === true;
+ if ([article, siteId, articles || undefined].filter(Boolean).length !== 1) {
+ throw new OpsInputError('send one of "article" (an article id), "articles": true or "siteId"');
+ }
+ const r = await findCopyAction({
+ ...(article ? { article } : {}),
+ ...(siteId ? { siteId } : {}),
+ dryRun: optBool(body, "dryRun") === true,
+ });
+ if (!r.ok) return opsFail(r.error);
+ return NextResponse.json(r);
+ });
+}
diff --git a/editor/app/api/ops/wayback-lookup/route.ts b/editor/app/api/ops/wayback-lookup/route.ts
@@ -0,0 +1,50 @@
+import { NextResponse } from "next/server";
+import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { recordWebpageUrl, waybackLookup } from "yt-dlp-transcript-common/publish/findCopy";
+import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqSlug, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { url } | { slug, id }, okOnly?, limit? -> { ok: true, url, found,
+// captures: [{ timestamp, status, mimetype?, replayUrl }] }
+//
+// The Wayback Machine's captures of a page (its CDX API, release 29 E2): a
+// URL as given, or a record's page — its metadata's webpage_url, else the one
+// its availability check recorded, else the playlist's. Oldest first;
+// `okOnly` keeps only the captures that recorded a 200; `limit` at most 500
+// (default 100). ONE request through the editor's Wayback client, with
+// archive.org's manners (one at a time, a 2 s gap, the project's User-Agent,
+// 429s waited out a few times, then a 502). Read only; nothing is fetched.
+// `find-copy` is what fetches a gone recording's windows from a capture.
+const MAX_LIMIT = 500;
+
+export async function POST(request: Request) {
+ return ops(request, ["url", "slug", "id", "okOnly", "limit"], async (body) => {
+ const given = optString(body, "url")?.trim();
+ const hasRecord = body.slug !== undefined || body.id !== undefined;
+ if (given && hasRecord) throw new OpsInputError('send either "url" or "slug" and "id", not both');
+ let url: string;
+ if (given) {
+ if (!/^https?:\/\/[^\s]+$/.test(given)) throw new OpsInputError(`"url" must be an http(s) URL`);
+ url = given;
+ } else if (hasRecord) {
+ const slug = reqSlug(body, "slug");
+ const id = reqVideoId(body, "id");
+ const found = await recordWebpageUrl(getPaths(), slug, id);
+ if (!found) return opsFail(`no page is known for ${slug}/${id} (no metadata, availability check or playlist entry names one)`, 404);
+ url = found;
+ } else {
+ throw new OpsInputError('"url" (a page) or "slug" and "id" (a record) is required');
+ }
+ const limit = optPositiveInt(body, "limit") ?? 100;
+ if (limit > MAX_LIMIT) throw new OpsInputError(`"limit" is at most ${MAX_LIMIT}`);
+ try {
+ const r = await waybackLookup(url, { okOnly: optBool(body, "okOnly") === true, limit });
+ return NextResponse.json({ ok: true, url, found: r.captures.length, captures: r.captures });
+ } catch (e) {
+ if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, 502);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts
@@ -153,3 +153,29 @@ test("a held window a queued saved-video job will already cut is answered in inF
reg.forceRelease("HOLDER");
}
});
+
+// Release 29 E2: a recording gone from its platform (lib/sourceGone.ts) has no
+// page to fetch from — refused at the door — unless the item names a copy's
+// URL (find-copy), which is the only way such a window is fetched.
+test("a gone recording's window is refused at the door unless the item names a copy's URL", async () => {
+ const dir = path.join(ROOT, "channels", SLUG, "data", "deleted1");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "deleted1", webpage_url: "https://www.youtube.com/watch?v=deleted1" }));
+ await writeFile(path.join(dir, "availability.json"), JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" }));
+ const plain = await fetchWindowsAction({ items: [{ slug: SLUG, id: "deleted1", from: 1, to: 3 }], requestedBy: "test", dryRun: true });
+ assert.ok(plain.ok);
+ if (!plain.ok) return;
+ assert.equal(plain.groups.length, 0);
+ assert.equal(plain.unresolved.length, 1);
+ assert.match(plain.unresolved[0].error, /says the video is deleted.*find-copy/);
+ const copy = "https://web.archive.org/web/20260125093000/https://www.youtube.com/watch?v=deleted1";
+ const viaCopy = await fetchWindowsAction({
+ items: [{ slug: SLUG, id: "deleted1", from: 1, to: 3, webpageUrl: copy }],
+ requestedBy: "find-copy",
+ dryRun: true,
+ });
+ assert.ok(viaCopy.ok);
+ if (!viaCopy.ok) return;
+ assert.deepEqual(viaCopy.unresolved, []);
+ assert.deepEqual(viaCopy.groups.flatMap((g) => g.items.map((i) => i.webpageUrl)), [copy]);
+});
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -19,6 +19,7 @@ import {
isFetchMaxHeight,
} from "yt-dlp-transcript-common/lib/clipWindow";
import { findContainingClipWindow } from "yt-dlp-transcript-common/lib/clipWindow-server";
+import { sourceGoneState } from "yt-dlp-transcript-common/lib/sourceGone-server";
import { savedWindowSource } from "yt-dlp-transcript-common/lib/savedVideoWindow-server";
import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig";
import {
@@ -222,6 +223,23 @@ async function planFetchWindows(
groups.set(queueKey, group);
continue;
}
+ // A RECORDING GONE FROM ITS PLATFORM (lib/sourceGone.ts) has no page to
+ // fetch a window from: refused here, before any request — unless the item
+ // names a copy's URL (`webpageUrl`: find-copy's Wayback capture or
+ // archive.org file, release 29 E2), which is the only way such a window is
+ // fetched.
+ if (!item.webpageUrl?.trim()) {
+ const gone = await sourceGoneState(videoDir);
+ if (gone) {
+ unresolved.push({
+ item,
+ error:
+ `The source says the video is ${gone}: there is no page to fetch a window from. ` +
+ "pnpm ops find-copy looks for a copy (Wayback, archive.org) and fetches from it.",
+ });
+ continue;
+ }
+ }
const url =
item.webpageUrl?.trim() ||
(await findVideoSourceUrl(paths, item.slug, dirId, config));
diff --git a/editor/app/channels/[slug]/videos/findCopyAction.ts b/editor/app/channels/[slug]/videos/findCopyAction.ts
@@ -0,0 +1,71 @@
+"use server";
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site";
+import { clipWindowQueueKey } from "yt-dlp-transcript-common/lib/queueKeys";
+import { platformQueueKey } from "yt-dlp-transcript-common/lib/platform";
+import { articlesWorkHost, siteReportHost, type ReportHost } from "yt-dlp-transcript-common/publish/reportHost";
+import { runFindCopy, type FindCopyResult } from "yt-dlp-transcript-common/publish/findCopy";
+import { fetchWindowsJobAction } from "./fetchWindowsAction";
+
+// FIND A COPY OF THE GONE RECORDINGS A REPORT CITES, and fetch their windows
+// from it (release 29 E2; the lookups are publish/findCopy.ts). The windows
+// of every copy found go to ONE fetch-windows job on the archive.org clip
+// queue — Wayback captures and archive.org files are both archive.org's — so
+// they are fetched one at a time, paced, one stream.
+
+export type FindCopyActionResult =
+ | { ok: false; error: string }
+ | (FindCopyResult & {
+ ok: true;
+ dryRun: boolean;
+ // The fetch-windows job, when one started.
+ jobId?: string;
+ // Why the fetch did not start, when it did not.
+ refused?: string;
+ });
+
+// The archive.org clip queue: every copy's windows, one job, one stream.
+const FIND_COPY_QUEUE = clipWindowQueueKey(platformQueueKey("archiveorg"));
+
+export async function findCopyAction(req: { article?: string; siteId?: string; dryRun?: boolean }): Promise<FindCopyActionResult> {
+ const paths = getPaths();
+ let host: ReportHost;
+ try {
+ if (req.article) {
+ host = await articlesWorkHost(paths, [req.article], { only: true });
+ } else if (req.siteId) {
+ if (!isValidSiteId(req.siteId)) return { ok: false, error: `"${req.siteId}" is not a valid site id` };
+ if (!listSiteIds(paths).includes(req.siteId)) return { ok: false, error: `No site "${req.siteId}"` };
+ host = siteReportHost(paths, getSite(req.siteId, paths));
+ } else {
+ host = await articlesWorkHost(paths);
+ }
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ let refused: string | undefined;
+ const r = await runFindCopy({
+ paths,
+ host,
+ dryRun: req.dryRun,
+ startFetch: async (items) => {
+ const res = await fetchWindowsJobAction({ items, requestedBy: "find-copy", manifest: host.id, queueKey: FIND_COPY_QUEUE });
+ if (!res.ok) {
+ refused = res.error;
+ return null;
+ }
+ // Nobody reads the stream: the job's log is on disk.
+ void res.stream.cancel().catch(() => {});
+ return res.jobId;
+ },
+ });
+ const { fetch: jobId, ...found } = r;
+ return {
+ ok: true,
+ dryRun: req.dryRun === true,
+ ...found,
+ ...(typeof jobId === "string" ? { jobId } : {}),
+ ...(refused ? { refused } : {}),
+ };
+}
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -8,6 +8,7 @@
// Server-only: reached through the retry actions in actions.ts ("use server"),
// so it is never bundled to the client.
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { coerceClipCopy } from "yt-dlp-transcript-common/lib/clipWindow";
import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot";
import type { JobSpec, ReplayBucket } from "yt-dlp-transcript-common/jobs/jobSpec";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
@@ -113,6 +114,8 @@ function windowItems(v: unknown): FetchWindowsItem[] {
reason: str(r.reason),
pad: num(r.pad),
webpageUrl: str(r.webpageUrl),
+ // find-copy's copy (release 29 E2): a replay records it again.
+ copy: coerceClipCopy(r.copy),
});
}
return out;
diff --git a/editor/e2e/capture-posts.spec.ts b/editor/e2e/capture-posts.spec.ts
@@ -0,0 +1,130 @@
+// Capture posts for a Bluesky channel (release 29 E1), end to end over the
+// fake Bluesky (common/testing/social/fakeBluesky.mjs): the AppView, the
+// bsky.app-shaped post page and the image CDN all on one loopback origin,
+// named to the test server through E2E_BLUESKY_ORIGIN_FILE (e2e/servers.ts).
+// The real Bluesky is never contacted.
+//
+// The job runs as `pnpm ops capture-posts` runs it: the AppView says which
+// posts are live and where their images are, a headless Chromium with no login
+// shoots each live post cropped to it, the images come down beside the shot,
+// and the deleted post lands in posts-availability.json as deleted.
+
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { startFakeBluesky, BSKY_POSTS, ACCOUNTS } from "yt-dlp-transcript-common/testing/social/fakeBluesky.mjs";
+import { writePosts } from "yt-dlp-transcript-common/lib/posts-server";
+import { uploadDateFromCreatedAt, type Post } from "yt-dlp-transcript-common/lib/posts";
+import { baseUrl } from "./baseUrl";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { blueskyOriginFile } from "./servers";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "synth-bsky";
+const HANDLE = ACCOUNTS[0].handle;
+
+async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> {
+ let last = { status: "", tail: [] as string[] };
+ await expect
+ .poll(
+ async () => {
+ const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=40`, { headers: AUTH });
+ const body = (await res.json()) as { job: { status: string }; tail?: string[] };
+ last = { status: body.job.status, tail: body.tail ?? [] };
+ return last.status;
+ },
+ { timeout: 90_000, intervals: [1_000] },
+ )
+ .toMatch(/^(done|failed|cancelled)$/);
+ return last;
+}
+
+test("capture-posts on a Bluesky channel: shots cropped to the post, its images, and the deleted post recorded", async ({
+ request,
+}) => {
+ test.setTimeout(150_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0 });
+
+ const channelRoot = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+ await mkdir(channelRoot, { recursive: true });
+ await writeFile(
+ path.join(channelRoot, "config.json"),
+ JSON.stringify(
+ {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "bluesky",
+ postFetcher: "bluesky-atproto",
+ socialHandle: HANDLE,
+ name: "Synth Baker (Bluesky)",
+ url: `https://bsky.app/profile/${HANDLE}`,
+ },
+ null,
+ 2,
+ ),
+ );
+ // The three invented posts, archived as a fetch would have left them.
+ const posts: Post[] = BSKY_POSTS.map((p) => ({
+ id: p.rkey,
+ slug: `${SLUG}/${p.rkey}`,
+ channelSlug: SLUG,
+ author: p.handle,
+ createdAt: p.createdAt,
+ uploadDate: uploadDateFromCreatedAt(p.createdAt),
+ text: p.text,
+ url: `https://bsky.app/profile/${p.handle}/post/${p.rkey}`,
+ platform: "bluesky",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ }));
+ await writePosts(channelRoot, posts);
+
+ const bsky = await startFakeBluesky();
+ const originFile = blueskyOriginFile(resolvePath(testPaths().transcriptsDir));
+ await writeFile(originFile, bsky.base);
+ try {
+ const ids = BSKY_POSTS.map((p) => p.rkey);
+ const res = await request.post(`${baseUrl}/api/ops/capture-posts`, { headers: AUTH, data: { slug: SLUG, ids } });
+ const body = (await res.json()) as { ok?: boolean; jobId?: string; error?: string };
+ expect(res.status(), body.error).toBe(200);
+ const job = await waitForJob(request, body.jobId!);
+ expect(job.status, job.tail.join("\n")).toBe("done");
+
+ const media = path.join(channelRoot, "posts-media");
+ const [withImages, textOnly, deleted] = ids;
+ expect((await readdir(path.join(media, withImages))).sort()).toEqual([
+ "capture.json",
+ "media-1.png",
+ "media-2.png",
+ "shot.png",
+ ]);
+ expect((await readdir(path.join(media, textOnly))).sort()).toEqual(["capture.json", "shot.png"]);
+ const gone = JSON.parse(await readFile(path.join(media, deleted, "capture.json"), "utf8")) as { state: string; shot?: unknown };
+ expect(gone.state).toBe("deleted");
+ expect(gone.shot).toBeUndefined();
+
+ // The shot is the post, not the page: the fake's thread item is 600 CSS
+ // px wide in a 1280-px window, shot at 2x.
+ const png = await readFile(path.join(media, withImages, "shot.png"));
+ expect(png.readUInt32BE(16)).toBe(1200);
+
+ const availability = JSON.parse(await readFile(path.join(channelRoot, "posts-availability.json"), "utf8")) as Record<
+ string,
+ { availability: string }
+ >;
+ expect(availability[deleted]?.availability).toBe("deleted");
+ expect(availability[withImages]?.availability).toBe("available");
+
+ // The page was opened for the live posts only; the deleted one never.
+ const pages = bsky.requests.filter((r) => r.startsWith("/profile/"));
+ expect(pages).toEqual([
+ `/profile/${HANDLE}/post/${withImages}`,
+ `/profile/${HANDLE}/post/${textOnly}`,
+ ]);
+ } finally {
+ await rm(originFile, { force: true });
+ await bsky.close();
+ }
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -47,6 +47,11 @@ export const E2E_SERVER_ENV: Record<string, string> = {
EXPORT_NEXT_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-next.mjs"),
};
+/** The file naming a slot's fake Bluesky (common/social/blueskyEndpoints.ts). */
+export function blueskyOriginFile(transcriptsDir: string): string {
+ return join(transcriptsDir, ".fake-bluesky-origin");
+}
+
/** The start-mode build directory (scripts/e2e-stamp.mjs PACKAGES.editor.distDir). */
export const E2E_DIST_DIR = ".next/e2e";
const EXPORT_SITES_DIR = join(EDITOR_ROOT, "e2e", "fixtures", "sites");
@@ -192,6 +197,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
const ports = slotPorts(slot, env);
const paths = testPathsFor(slotRoot(slot));
const editorEnv: Record<string, string> = { ...E2E_SERVER_ENV };
+ // Where a spec names its fake Bluesky's origin (capture-posts.spec): the
+ // slot's own test data, so two slots never share one.
+ editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir);
// A start-mode server runs the stamped build (shared, read-only); a second
// `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`).
if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR;
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -30,6 +30,10 @@ import { currentSlot } from "./e2e/testPaths";
// batch (30–45 s in production; 2 s here), so
// fetch-window.spec sees the one it owes
// (common/controller/fetchWindows.ts)
+// E2E_BLUESKY_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec
+// writes its fake Bluesky's loopback origin into,
+// which the AppView, bsky.app and the image CDN
+// then are (common/social/blueskyEndpoints.ts)
// E2E_MODE `start` (the default): the editor runs under
// `next start` from a build the stamp vouches for
// (scripts/e2e-stamp.mjs — rebuilt through the
diff --git a/export/app/lib/reports.test.ts b/export/app/lib/reports.test.ts
@@ -77,6 +77,7 @@ test("params: every report and every moment, as the index files list them", () =
{ moment: ["demo-channel", "abc123", "3126.00-3151.00"] },
{ moment: ["demo-podcast", "ep-042", "610.50-628.00"] },
{ moment: ["demo-social", "1234567890"] },
+ { moment: ["demo-channel", "gone99", "1200.00-1210.00"] },
]);
});
@@ -147,7 +148,7 @@ test("the report page: header, tally, sections and claims, inline cites, referen
assert.match(html, /data-inline-cite="w01"[^]*?data-cite-number="4"/);
// every numbered citation has its reference entry, in number order
const refs = [...html.matchAll(/<li id="c-([^"]+)" value="(\d+)"/g)].map((m) => `${m[2]}:${m[1]}`);
- assert.deepEqual(refs, ["1:c01", "2:au1", "3:a01", "4:w01", "5:a02", "6:p01"]);
+ assert.deepEqual(refs, ["1:c01", "2:au1", "3:a01", "4:w01", "5:a02", "6:p01", "7:g01"]);
assert.match(html, /href="\/pages\/demo-factcheck\/citations.json" download=""/);
assert.match(html, /href="\/pages\/demo-factcheck\/citations.csv" download=""/);
const meta = await reportPage.generateMetadata({ params });
diff --git a/export/e2e-report/report-site.spec.ts b/export/e2e-report/report-site.spec.ts
@@ -18,14 +18,16 @@ import { readFixtureReport } from "../fixtures/report-site/fixture";
//
// The site is export/fixtures/report-site, staged and built by
// e2e-report/stage.ts: one fact-check citing a video span (c01), an audio
-// span (au1), a post (p01), the article's own sentences (a01, a02) and a web
-// page (w01). It has two revisions (report.v1.json, then report.json), and
+// span (au1), a post (p01), the article's own sentences (a01, a02), a web
+// page (w01), and a span of a stream deleted since (g01: its words only,
+// "Source deleted"). It has two revisions (report.v1.json, then report.json), and
// publishes their history.
const REPORT = "/pages/demo-factcheck/";
const VIDEO_MOMENT = "/m/demo-channel/abc123/3126.00-3151.00/";
const AUDIO_MOMENT = "/m/demo-podcast/ep-042/610.50-628.00/";
const POST_MOMENT = "/m/demo-social/1234567890/";
+const GONE_MOMENT = "/m/demo-channel/gone99/1200.00-1210.00/";
const HISTORY = "/pages/demo-factcheck/history/";
const inlineCite = (page: Page, id: string): Locator => page.locator(`[data-inline-cite="${id}"]`).first();
@@ -235,10 +237,10 @@ test("a post citation's preview shows the captured shot", async ({ page }) => {
test("a citation's number jumps to its entry in the reference list", async ({ page }) => {
await page.goto(REPORT);
const refs = page.locator("[data-reference-list] [data-reference]");
- await expect(refs).toHaveCount(6);
+ await expect(refs).toHaveCount(7);
await expect
.poll(() => refs.evaluateAll((els) => els.map((el) => el.id)))
- .toEqual(["c-c01", "c-au1", "c-a01", "c-w01", "c-a02", "c-p01"]);
+ .toEqual(["c-c01", "c-au1", "c-a01", "c-w01", "c-a02", "c-p01", "c-g01"]);
await inlineCite(page, "w01").locator("[data-cite-number]").click();
await expect(page).toHaveURL(`${REPORT}#c-w01`);
@@ -298,7 +300,7 @@ test("report.html opens with no network: one file, no script, every image inline
expect(await img.getAttribute("src")).toMatch(/^data:image\//);
await expect.poll(() => img.evaluate((el) => (el as HTMLImageElement).naturalWidth)).toBeGreaterThan(0);
}
- await expect(page.locator("[data-reference-list] > li")).toHaveCount(6);
+ await expect(page.locator("[data-reference-list] > li")).toHaveCount(7);
// The page's tiers, its flag pill and the added mark, as the site has them.
await expect(page.locator("[data-report-tier]")).toHaveCount(3);
await expect(page.locator("[data-claim-flag]").first()).toContainText("No source given");
@@ -435,6 +437,21 @@ test("an audio moment plays its clip as sound", async ({ page, request }) => {
await expect(page.locator(`[data-cited-in] a[href="${REPORT}#claim-2"]`)).toHaveCount(1);
});
+// Release 29 E2: a cited recording deleted on its platform with no copy found
+// is its words only, said in plain words on its card and its moment page.
+test("a source-deleted moment: its words, no clip, \"Source deleted\" on the card and the page", async ({ page }) => {
+ await page.goto(REPORT);
+ const card = page.locator('#c-g01');
+ await expect(card.locator("[data-source-gone]")).toHaveText(/Source deleted/);
+ await expect(card.getByRole("link", { name: /^Open / })).toHaveAttribute("href", /\/m\/demo-channel\/gone99\/1200\.00-1210\.00\//);
+ await page.goto(GONE_MOMENT);
+ await expect(page.locator("[data-moment]")).toHaveAttribute("data-moment-kind", "video");
+ await expect(page.locator('[data-moment] p[data-source-gone="deleted"]')).toHaveText("Source deleted");
+ await expect(page.locator("video, audio")).toHaveCount(0);
+ await expect(page.locator("[data-cue-lines] li[data-in-span]")).toHaveText([/I was standing right there when they cut the ribbon\./]);
+ await expect(page.locator(`[data-cited-in] a[href="${REPORT}#claim-5"]`)).toHaveCount(1);
+});
+
test("a post moment shows the captured shot and the post", async ({ page }) => {
await page.goto(POST_MOMENT);
await expect(page.locator("[data-moment]")).toHaveAttribute("data-moment-kind", "post");
diff --git a/export/fixtures/report-site/fixture.ts b/export/fixtures/report-site/fixture.ts
@@ -69,6 +69,16 @@ const RECORDS: Record<string, RecordView> = {
date: "2026-01-10",
platform: "youtube",
},
+ // A stream deleted on its platform since (release 29 E2): no copy of it was
+ // found, so its moment is its words only, marked "Source deleted".
+ "demo-channel/gone99": {
+ channel: "demo-channel",
+ channelTitle: "Demo Channel",
+ id: "gone99",
+ title: "Demo stream: the ribbon, told again",
+ date: "2026-03-01",
+ platform: "youtube",
+ },
"demo-podcast/ep-042": {
channel: "demo-podcast",
channelTitle: "Demo Podcast",
@@ -87,6 +97,11 @@ const RECORDS: Record<string, RecordView> = {
const POSTER = "/pages/demo-factcheck/stills/poster.png";
+// The recordings gone from their platform with no media published: compose's
+// `sourceGone` (common/publish/composeReports.ts).
+const GONE: Record<string, "deleted" | "private"> = { "demo-channel/gone99": "deleted" };
+const goneOf = (c: { channel: string; id: string }) => GONE[`${c.channel}/${c.id}`];
+
// A post's captured screenshot, where compose copies a cited capture
// (publish/citedPostCaptures.ts): committed under public/media/posts/.
function shotFor(c: { channel: string; id: string }): string {
@@ -116,7 +131,8 @@ function recordFor(channel: string, id: string, seconds?: number): RecordView {
export function buildFixtureReportView(report = readFixtureReport()): ReportPageView {
return buildReportPageView(report, {
record: (c) => recordFor(c.channel, c.id, c.kind === "post" ? undefined : c.start),
- poster: (c) => (c.kind === "video" ? POSTER : undefined),
+ poster: (c) => (c.kind === "video" && !goneOf(c) ? POSTER : undefined),
+ sourceGone: (c) => goneOf(c),
post: (c) => ({
author: "@demo_account",
text: `${c.quote}\n\nPosted to settle it.`,
@@ -152,6 +168,11 @@ const CUES: Record<string, { start: number; end: number; text: string }[]> = {
{ start: 3151, end: 3160, text: "Anyway, back to the mail." },
{ start: 3160, end: 3170, text: "Next letter is from a long-time viewer." },
],
+ "demo-channel/gone99": [
+ { start: 1190, end: 1200, text: "People keep asking about the ribbon thing." },
+ { start: 1200, end: 1210, text: "I was standing right there when they cut the ribbon." },
+ { start: 1210, end: 1220, text: "Anyway, that was years ago." },
+ ],
"demo-podcast/ep-042": [
{ start: 600, end: 610.5, text: "So when did you first go back there?" },
{ start: 610.5, end: 628, text: "Like I said before, spring twenty nineteen." },
@@ -187,14 +208,15 @@ export function buildFixtureMomentViews(
...(c.verification ? { verification: c.verification } : {}),
start: span.start,
end: span.end,
- clip: {
+ ...(goneOf(c) ? { sourceGone: goneOf(c) } : {}),
+ ...(goneOf(c) ? {} : { clip: {
// A clip cut as sound is an .m4a beside the video clips (compose's
// clipPath).
src: c.kind === "audio" ? evidenceClipPath(span).replace(/\.mp4$/, ".m4a") : evidenceClipPath(span),
start: Math.max(0, span.start - before),
end: span.end + after,
...(c.kind === "video" ? { poster: POSTER } : {}),
- },
+ } }),
cues: (CUES[`${c.channel}/${c.id}`] ?? []).map((q) => ({
...q,
inSpan: q.end > span.start && q.start < span.end,
diff --git a/export/fixtures/report-site/public/m/demo-channel/gone99/1200.00-1210.00/moment.json b/export/fixtures/report-site/public/m/demo-channel/gone99/1200.00-1210.00/moment.json
@@ -0,0 +1,57 @@
+{
+ "format": "archilyzer-moment-page",
+ "version": 1,
+ "key": "demo-channel/gone99/1200.00-1210.00",
+ "kind": "video",
+ "record": {
+ "channel": "demo-channel",
+ "channelTitle": "Demo Channel",
+ "id": "gone99",
+ "title": "Demo stream: the ribbon, told again",
+ "date": "2026-03-01",
+ "platform": "youtube",
+ "originalUrl": "https://media.example.org/demo-channel/gone99?t=1200"
+ },
+ "quote": "I was standing right there when they cut the ribbon.",
+ "start": 1200,
+ "end": 1210,
+ "sourceGone": "deleted",
+ "cues": [
+ {
+ "start": 1190,
+ "end": 1200,
+ "text": "People keep asking about the ribbon thing.",
+ "inSpan": false
+ },
+ {
+ "start": 1200,
+ "end": 1210,
+ "text": "I was standing right there when they cut the ribbon.",
+ "inSpan": true
+ },
+ {
+ "start": 1210,
+ "end": 1220,
+ "text": "Anyway, that was years ago.",
+ "inSpan": false
+ }
+ ],
+ "citedIn": [
+ {
+ "reportId": "demo-factcheck",
+ "sectionId": "moving",
+ "claimId": "claim-5",
+ "citationId": "g01",
+ "href": "/pages/demo-factcheck/#claim-5",
+ "reportTitle": "Demo Checks: Checking an example article",
+ "sectionTitle": "Moving away",
+ "claimText": "He was at the opening.",
+ "verdict": "CORROBORATED",
+ "verdictStyle": {
+ "label": "Corroborated",
+ "color": "#3fbf7f"
+ },
+ "number": 7
+ }
+ ]
+}
diff --git a/export/fixtures/report-site/public/m/index.json b/export/fixtures/report-site/public/m/index.json
@@ -4,6 +4,7 @@
"moments": [
"demo-channel/abc123/3126.00-3151.00",
"demo-podcast/ep-042/610.50-628.00",
- "demo-social/1234567890"
+ "demo-social/1234567890",
+ "demo-channel/gone99/1200.00-1210.00"
]
}
diff --git a/export/fixtures/report-site/public/pages/demo-factcheck/page.json b/export/fixtures/report-site/public/pages/demo-factcheck/page.json
@@ -155,6 +155,26 @@
"author": "@demo_account",
"text": "Never said I would move. Not once.\n\nPosted to settle it.",
"shot": "/media/posts/demo-social/1234567890/shot.png"
+ },
+ "g01": {
+ "kind": "video",
+ "id": "g01",
+ "number": 7,
+ "quote": "I was standing right there when they cut the ribbon.",
+ "moment": "demo-channel/gone99/1200.00-1210.00",
+ "href": "/m/demo-channel/gone99/1200.00-1210.00/",
+ "start": 1200,
+ "end": 1210,
+ "record": {
+ "channel": "demo-channel",
+ "channelTitle": "Demo Channel",
+ "id": "gone99",
+ "title": "Demo stream: the ribbon, told again",
+ "date": "2026-03-01",
+ "platform": "youtube",
+ "originalUrl": "https://media.example.org/demo-channel/gone99?t=1200"
+ },
+ "sourceGone": "deleted"
}
},
"entries": [
@@ -249,9 +269,10 @@
"id": "claim-5",
"text": "He was at the opening.",
"verdict": "CORROBORATED",
- "findings": "He says [he was there](cite:c01).",
+ "findings": "He says [he was there](cite:c01), and told it again on a stream since [deleted](cite:g01).",
"citations": [
- "c01"
+ "c01",
+ "g01"
]
}
]
diff --git a/export/fixtures/report-site/public/pages/index.json b/export/fixtures/report-site/public/pages/index.json
@@ -11,7 +11,7 @@
"published": "2026-10-01",
"updated": "2026-10-04",
"href": "/pages/demo-factcheck/",
- "citationCount": 6,
+ "citationCount": 7,
"claimCount": 5,
"tally": [
{
diff --git a/export/fixtures/report-site/source/demo-factcheck/report.json b/export/fixtures/report-site/source/demo-factcheck/report.json
@@ -59,6 +59,14 @@
"quote": "Never said I would move. Not once.",
"date": "2025-03-14"
},
+ "g01": {
+ "kind": "video",
+ "channel": "demo-channel",
+ "id": "gone99",
+ "start": 1200,
+ "end": 1210,
+ "quote": "I was standing right there when they cut the ribbon."
+ },
"a01": {
"kind": "source",
"source": "s0",
@@ -156,8 +164,8 @@
"id": "claim-5",
"text": "He was at the opening.",
"verdict": "CORROBORATED",
- "findings": "He says [he was there](cite:c01).",
- "citations": ["c01"]
+ "findings": "He says [he was there](cite:c01), and told it again on a stream since [deleted](cite:g01).",
+ "citations": ["c01", "g01"]
}
]
}
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9460,3 +9460,67 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
plan and confirm guard it, there is no red button and no Signal outline since P6b); a toggle that is on is
`pressed` (the panel ground); a state that is not a judgement wears `badgeVariants` `state` (a dashed ink edge);
Meter is measurement. `e2e/visual-audit.spec.ts` measures every page's actions by computed colour.
+
+## Release 29 V1: the verdict bench, v2 (verified 2026-10-15, branch `r29/verdicts`)
+
+- **What a verdict means is written once:** `VERDICT_MEANINGS` and `VERDICT_TIE_RULE` in
+ `common/lib/report/verdicts.mjs` (typed through `verdicts.ts`). The bench's system prompt, REPORT.md's verdicts table
+ (`lib/report/docs.ts`), `CLAIM_FIELD_DOCS.verdict` (a pointer to it) and umtool's `/tools/bench` read them; nothing
+ else spells them out. Changing a sentence changes the prompt: bump `PROMPT_VERSION`.
+- **The prompt version contract.** `PROMPT_VERSION` (`draft/bench/prompt.ts`) is a string bumped BY HAND with any change
+ to the system prompt, the meanings, the answer schema or the user prompt's shape. A run records `summary.promptVersion`;
+ a run without one is release 28's, `M7_PROMPT_VERSION` `"1"`. A run is never resumed under another version (refused,
+ naming `--items-from`). The answer schema is `{reason, verdict}`, reason first.
+- **An items hash** (`benchItemsHash`): sha256 (16 hex) of each item's key, ruling and windows (recording, from, to,
+ cue count) — not its context lines. `summary.itemsHash`; a run before V1 has it computed from its `items.jsonl`.
+ Two runs "on the same items" means equal hashes; umtool compares only those.
+- **`--items-from <run>`** (`itemsFrom`): a new run takes that run's `items.jsonl` exactly (and its skipped, dropped,
+ window and limit), filling the context lines (title, section, a quote's date) an older item lacks from the registry
+ as it is now — the hash does not change. Refused with `--report`, `--window`, `--window-mode` or `--limit`.
+- **Resume asks only the invocation's models** (`runVerdictBench` iterates `validateBenchOptions(o).models`);
+ `summary.models` is the union, in first-asked order. A qwen-only re-run of a run never re-asks an API pair.
+- **Window modes** (`items.ts`): `seconds` (±windowS, M7's) and `turn` — the cited speaker's run of attribution
+ segments (`diskTurnsOf`, `attribution.json`), else the cues until a ≥ `TURN_GAP_S` (2 s) pause or a `>>` cue,
+ clipped to ±windowS; each window's `bound` is `seconds | speaker | pause | limit`. A citation of a kept claim that
+ gives no window is `dropped` with its reason (`summary.dropped`); a `--limit` is `stratifiedLimit` (every ruled verdict
+ kept, the rarest first, the rest in proportion) and the rest are skipped "left out by the limit".
+- **A run's dir gains** `trace.jsonl` (appended: a `start` line per invocation with the system prompt and schema, a
+ `call` line per call with the user prompt, the raw answer, the verdict, ms, usd) and `marks.json`
+ (`archilyzer-bench-marks` v1, `{marks: {<model>: {<report>/<claim>: {verdict: right|wrong, answer, at}}}}`, written
+ by umtool alone — `umtool/lib/bench-marks.mjs`, R6's discipline; read by common's `readBenchMarks`). A mark says
+ whether the MODEL was right on a disagreement; it applies only while the model's answer is still `answer`.
+- **Scores** (`score.ts`): `notCorroborated {tp, fp, fn, precision, recall}` per model (a failed answer is never a
+ positive); `compareBenchRuns(a, b)` (shared item keys, models asked in both: agreement each, `changed`, `fixed`,
+ `broke`); `markedScore` (a disagreement marked Right counts as agreeing) tallied by `markTally`
+ (`draft/triage/types.ts`, which `precisionOf` now uses too).
+- **The injected model** is `BenchDeps.ask(system, user, schema, model)` — no Meter, so an injected ask costs nothing
+ in the run's spend.
+
+## 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
+ and image URLs from the public AppView's `getPosts` (25 a request; absent = `deleted`, merged into
+ `posts-availability.json` by `capturePosts` as X's), the shot from a headless Chromium with a FRESH context (no
+ profile, no cookies) on `bsky.app/profile/<handle>/post/<rkey>`, cropped to
+ `[data-testid="postThreadItem-by-<handle>"]` (the one holding the post's text when several), images as
+ `media-<n>.<ext>` beside it; the record is postCapture.ts's (`url` the canonical bsky.app permalink). A deleted
+ post keeps an earlier capture's shot and media. One page at a time, ≥ 3 s jittered gaps, 429s waited out then
+ stopped.
+- **Bluesky's hosts are one module** (`common/social/blueskyEndpoints.ts`): the AppView, bsky.app and the CDN.
+ `E2E_BLUESKY_ORIGIN_FILE` (test-only) names a file whose loopback origin all three become, read per call.
+- **"Is this source gone?" has one reading** (`common/lib/sourceGone.ts`, `sourceGone-server.ts`): a recording's
+ effective availability as a viewer state is `deleted` or `private` (members-only, `error`, unlisted and never
+ checked are NOT gone); a post is gone when `posts-availability.json` says `deleted`. Refresh's delta, compose,
+ `missingEvidenceWindows` (its `gone` field), fetch-windows' door and find-copy all read it.
+- **`sourceGone` on the composed views** (`lib/report/views.ts`): a span or post citation view and its moment page
+ carry `sourceGone: "deleted" | "private"` when compose accepted the moment with no media because its source is
+ gone; the page shows `SOURCE_GONE_LABELS` ("Source deleted"). The report-media index's `warnings` (kind
+ `source-gone`) say the same at prepare and never fail it; a live source with no media is still `missing-media`.
+- **A window fetched from a copy names the copy** (`ClipProvenance.copy = {from: "wayback" | "archive.org", url}`,
+ `lib/clipWindow.ts`; written by `fetchWindowManaged` from `FetchWindowsItem.copy`). find-copy
+ (`publish/findCopy.ts`) puts every copy's windows in one fetch-windows job on `clips:archiveorg`, the copy's URL
+ as each item's `webpageUrl`; the clips land in the recording's own `data/<id>/clips/`. fetch-windows' door refuses a
+ gone recording's window whose item names no `webpageUrl`.
+- **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.
+
diff --git a/plans/release-29.md b/plans/release-29.md
@@ -179,6 +179,199 @@ The three release 28 smoke drafts deleted through `archilyzer reports delete <id
`r28-smoke-research` and `r28-smoke-research2` (articles in the making — 265 KiB and 262 KiB). The usage ledger's rows
and the shared prepared-media cache are kept, as the command keeps them.
+### V1, as shipped (2026-10-15, lane B, `r29/verdicts`)
+
+Bench v2: the verdict bench asks to the operator's standard, says which prompt and which items a run used, and can be
+compared and marked, so the bar can be set from marked precision. No real calls were made (the fakes and the injected
+`ask` only); V2's runs are the orchestrator's.
+
+- **The meanings are written once** — `VERDICT_MEANINGS` and `VERDICT_TIE_RULE` in `common/lib/report/verdicts.mjs`
+ (typed in `verdicts.ts`): 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); PARTLY = a part is shown overstated or wrong (a part only
+ not shown is not PARTLY); CONTRADICTED and NOT_FOUND sharpened to the claim's substance; UNTESTABLE as before; the tie
+ rule "In doubt between CORROBORATED and PARTLY: CORROBORATED, unless a part of the claim is shown overstated or
+ wrong." The bench's system prompt, REPORT.md's verdicts table (a "Means" column and the tie rule, `docs.ts`),
+ `CLAIM_FIELD_DOCS.verdict` (a pointer) and umtool's `/tools/bench` read them.
+- **The prompt** (`bench/prompt.ts`): rules only (Q0), the meanings and the tie rule, "write the reason first"; the
+ answer schema `{reason, verdict}` (reason first); the user prompt carries `Report:` (the title), `Section:` (the
+ claim's heading), each cited line's speaker (the citation's, else the channel) and recording date (the citation's,
+ else the record's `upload_date` — `bench/disk.ts` `diskDateOf`), each window headed with its channel and date.
+ `PROMPT_VERSION = "2"`; a run without one is `"1"` (`M7_PROMPT_VERSION`). The local prompt stays under 7,800
+ estimated tokens (the window trimmed, as before).
+- **Items** (`bench/items.ts`): `--window-mode seconds|turn` — `turn` is the cited speaker's run of attribution
+ segments (`diskTurnsOf`), else the cues until a ≥ 2 s pause or a `>>` cue, clipped to ±`--window`; a window's
+ `bound` says which. A citation of a kept claim that gives no window is DROPPED with its reason (not in the report's
+ citations, not a video or audio citation, the recording has no cues, no cues around the cited seconds) and listed in
+ `summary.dropped`, the dry run and the page. `--limit` is stratified (`stratifiedLimit`: every ruled verdict kept,
+ the rarest first, the rest in proportion, the largest remainder); the rest are skipped "left out by the limit".
+ `unruledItemsOfReport` is M8's reading of the unruled claims.
+- **Runs** (`bench/run.ts`, `store.ts`): `--items-from <run>` takes that run's exact items (context lines filled from
+ the registry; refused with `--report`, `--window`, `--window-mode`, `--limit`); a resume asks ONLY this invocation's
+ models (a qwen-only re-run never re-asks an API pair; `summary.models` the union); the summary records
+ `promptVersion`, `itemsHash` (`benchItemsHash`: keys, rulings and windows), `windowMode`, `itemsFrom`, `dropped`; a
+ resume under another prompt version, or with `itemsFrom` naming other items, is refused. Every call is traced
+ (`trace.jsonl` in the run dir: a `start` line per invocation with the system prompt and schema, a `call` line with the
+ user prompt, the raw answer, the verdict, ms, usd). The model is injectable (`BenchDeps.ask(system, user, schema,
+ model)`, R6's shape).
+- **Scores** (`bench/score.ts`): `notCorroborated {tp, fp, fn, precision, recall}` per model and the baseline;
+ `compareBenchRuns` (each model asked in both: agreement in each over the shared items, the claims whose answers
+ changed, fixed and broke); `markedScore` (a disagreement marked Right counts as the model agreeing) tallied by
+ `markTally`, which triage's `precisionOf` now uses too (its output and tests unchanged).
+- **umtool `/tools/bench`** (inside the page, on the redesign's primitives): the status line names the window mode, the
+ prompt version (`data-prompt-version`) and the items hash (`data-items-hash`, and `from <run>`); **compare with**
+ (`nav "compare with"`, chips `<run> · prompt v<n>` over the runs with the same items hash) and its table (region
+ `compare`, `data-compare`, `data-metric` `agreement-a|agreement-b|changed`, list `changed answers`); **Right** /
+ **Wrong** (pressed when set, again to unmark; `data-mark`) on every answered disagreement, kept in the run's
+ `marks.json` (`lib/bench-marks.mjs`, R6's discipline, umtool the one writer; `POST /api/bench/marks {run, model,
+ key, verdict}`, refused on an agreement); region `precision` beside the bar (`data-metric`
+ `precision|marked-precision|marks`); "what the verdicts mean" (`data-meaning`); the dropped citations.
+- **CLI/ops:** `archilyzer reports bench-verdicts` gains `--window-mode`, `--items-from` and the stratified `--limit`;
+ the body keys `windowMode`, `itemsFrom` (controller, the editor route, `pnpm ops` help); COMMANDS.md and REPORT.md
+ regenerated.
+
+| Commit | What |
+| --- | --- |
+| `243cf1ec` | common, editor: the meanings, the prompt v2, window modes, drops, the stratified limit, items-from, the resume, the items hash, the new scores, the injected ask and the trace; CLI/ops/route flags; `bench.test.ts` (+5), `reports-bench-verdicts.test.ts`, `_benchVerdicts.test.ts`; COMMANDS.md, REPORT.md |
+| `452446a9` | umtool: `/tools/bench` — version, hash, compare, marks, precision, meanings, drops; `lib/bench-marks.mjs` (+ test), `/api/bench/marks`, `MarkButtons`; `verdict-bench.spec` (+2) and its fixture's second run |
+| (this commit) | this record, FACTS, CHANGELOG |
+
+Gates (at `452446a9`; branch start `3217bdfb` in brackets):
+
+| Gate | Result |
+| --- | --- |
+| repo-wide `tsc --noEmit` | clean at each commit |
+| common `pnpm --filter yt-dlp-transcript-common test` | **4198/4198** [4193] (+5 in `bench.test.ts`: the meanings, tie rule, schema order and context; the turn mode and the drops; the stratified limit; the injected ask, the trace, items-from, the resume over its own models, a cross-version resume refused; not-CORROBORATED, the compare, the marks) |
+| editor unit `pnpm --filter editor test` | 304/304 [304] (`_benchVerdicts.test.ts` gains the two body keys) |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | 370/370 [370] |
+| `pnpm run test:scripts` | 1014 tests, 1011 pass, 3 skipped, 0 fail [1013: 1009 pass, 3 skipped, 1 fail — `queue-lock.test.mjs` "two builds never overlap", the timing flake D1 owns; green this time] (+1 `bench-marks.test.mjs`) |
+| `pnpm --filter umtool test` | 33/33 [33] |
+| `archilyzer docs cli|files|env --check`, `settings example --check` | clean |
+| umtool e2e `verdict-bench.spec.ts` (foreground, queued; its prebuild 69 s) | **4 passed**, 0 failed, 24.6 s |
+
+Found and left:
+- **No dry run over the real registry was made** from the worktree (it has no corpus and no `vb-r28`); the first
+ `--dry --items-from vb-r28` is V2's, through the primary.
+- **The turn mode without attribution** reads the cues' pauses: on a stream whose cues run back to back (as the
+ synthetic ones do) a turn is the whole ±window, `bound: "limit"`. With an `attribution.json` it is the speaker's run
+ of segments.
+- **An injected `ask` has no Meter**: its calls cost nothing in the run's spend (the cap still applies to the estimate).
+
+### E1, as shipped (2026-10-15, lane A, `r29/evidence`)
+
+Bluesky captures posts with no login, as ruled: the real bsky.app page, headless. Built as the plan's Shape row, with
+these as built:
+- `blueskyFetcher.captureByIds` is `captureBlueskyPosts` (`common/social/blueskyPostCapture.ts`) over live deps. Per
+ run: the handle resolved to its DID once; `getPosts` in batches of 25 for the posts owed (`captureWork`); a post
+ absent from a batch that answered is `deleted` (availability `deleted`, no page opened, an earlier capture's shot and
+ media kept in the record); a batch that failed says nothing about its posts (state `error`, no availability).
+- A live post: ONE headless Chromium per run, a fresh context (no profile, no cookies, 1280×1600 at 2×, en-US,
+ light), `bsky.app/profile/<author handle>/post/<rkey>`; the post is the `[data-testid="postThreadItem-by-<handle>"]`
+ element — the only one, else the one whose text holds the post's first 80 characters (a self-thread's parents and
+ replies share the test id); `shot.png` is that element's box (`fullPage` + clip, as X's). A post that does not
+ render is `error` (a page that asks to sign in says so: the capture has no login).
+- Images: `embed.images[].fullsize` (else `thumb`), or a recordWithMedia's `media.images`, downloaded as
+ `media-<n>.<ext>` (the content type, else the CDN's `@jpeg`). Video embeds are not downloaded (`mediaState` `none`).
+- Pacing: a gap before every page after the run's first, `blueskyPageGapMs` = max(3 s, the channel's
+ `postPagePauseSeconds`) × [1, 2); 1–2 s between images; an AppView or CDN 429/503 waited out (Retry-After, else 5 s
+ doubling, capped 2 min, 4 attempts) and then the run stops; a page 429 is waited out once (≥ 30 s), a second stops
+ the run; 45 s per page load, 20 s for the post to appear; cancel and drain checked between posts and raced against
+ a page load; three errors in a row stop the run.
+- Base URLs: `common/social/blueskyEndpoints.ts` — the AppView, bsky.app and the CDN, injected as `deps.endpoints`;
+ the fetcher's own AppView reads (`fetch`, `checkAvailability`, `fetchOne`) now read it per call. Test-only:
+ `E2E_BLUESKY_ORIGIN_FILE` names a file holding one loopback origin that all three then are; the editor e2e server
+ sets it per slot (`<test-transcripts>/.fake-bluesky-origin`, `blueskyOriginFile` in `editor/e2e/servers.ts`).
+- Not done (optional): image URLs as `Post.media[]` in `normalizeBlueskyItem` — the PostModal lists a post's `media`
+ as links on every site, a visible change nobody asked for; the capture reads the URLs from `getPosts` instead.
+
+| Commit | What |
+| --- | --- |
+| `0295636d` | common, editor: `blueskyPostCapture.ts`, `blueskyEndpoints.ts`, `blueskyFetcher.captureByIds`; `E2E_BLUESKY_ORIGIN_FILE` (envVars, ENVIRONMENT.md, `servers.ts`, the config's header); unit tests; the editor `capture-posts.spec.ts`; the capture-posts route test (a Bluesky channel now passes the fetcher check and is refused as a stray id; the "cannot capture" case is a Nitter channel) |
+| (this commit) | this record, FACTS "Release 29 lane A", CHANGELOG |
+
+Gates (from the worktree root):
+- `pnpm -r exec tsc --noEmit`: clean.
+- common: 4188 at the branch's start (3 failing that run, not reproduced) → 4204, all pass
+ (`social/blueskyPostCapture.test.ts` 11, one of them a real headless Chromium over the fake's page: the shot is
+ 1200 px wide — the 600-px thread item at 2× — not the page).
+- editor unit: 304/304 (the branch-start run read 279 with 14 failing; not reproduced); mcp 370/370;
+ `test:scripts` 1010 + 3 skipped.
+- `docs env|files|cli --check`, `settings example --check`: clean.
+- editor e2e, one spec in the foreground: `capture-posts.spec.ts` 1/1 (26 s, the e2e build 51 s): the image post's
+ shot (1200 px wide) and two images, the text post's shot, the deleted post `deleted` in `posts-availability.json`,
+ bsky.app asked for the two live posts only.
+
+### E2, as shipped (2026-10-15, lane A, `r29/evidence`)
+
+The deleted-video fallback, as ruled: a copy when one is found, else a text-only moment marked "source deleted".
+Built as the plan's Shape row, with these as built:
+- **One gone reading**, `common/lib/sourceGone.ts` (`goneState`, `GONE_STATES` = deleted | private,
+ `SOURCE_GONE_LABELS`) and `sourceGone-server.ts` (`sourceGoneState(videoDir)` — `resolveEffectiveAvailability` →
+ `stateFromAvailability` → `goneState`, refresh's reading; `recordGoneState`; `postGoneState` — `deleted` in
+ `posts-availability.json`). Refresh's delta calls `goneState` (its one call; its tests unchanged and green).
+ `missingEvidenceWindows` reads it too (it read the explicit `availability.json` + `isPermanentlyGone` before), and
+ names the state on the window (`gone`). So a **members-only** recording is no longer "unfetchable: gone" there: it
+ is a window to fetch (member cookies fetch it), as refresh already read it.
+- **(a) `wayback-lookup`** `{url}` | `{slug, id}` (the record's page: its metadata's `webpage_url`, else its
+ availability check's `webpageUrl`, else the playlist's), `okOnly?`, `limit?` (100, ≤ 500) → the CDX captures,
+ oldest first (`timestamp`, `status`, `mimetype`, `replayUrl`). `lib/waybackClient.ts` is an `ArchiveOrgClient`
+ of its own (its UA, 2 s gap, 429/503 Retry-After back-off, then `ArchiveOrgRequestError` `rateLimited`); a new
+ `ArchiveOrgClient.getText` reads the CDX answer, whose empty forms (`[]`, an empty body, a header alone) are none.
+- **(b) `archive-search {youtubeId, limit?: 10}`**: the query
+ `identifier:(youtube-<id>) OR originalurl:(*<id>*) OR description:("<id>") OR title:("<id>")`, each hit's metadata
+ read; an item that does not name the id, is restricted, or holds no video file the upload can be told by (several
+ originals, none naming the id) is `skipped` with why; else its file — one naming the id first, an original before a
+ derivative, mp4 › webm › mkv › m4v › mov — as `https://archive.org/download/<identifier>/<file>`. The archive.org
+ fake gained a mirror of `GONE_RECORD` and `field:value` OR-clause searches (its existing tests green).
+- **(c) `find-copy`** `{article}` | `{articles: true}` | `{siteId}`, `dryRun?` (`publish/findCopy.ts`
+ `findCopies`/`runFindCopy`, `editor/app/channels/[slug]/videos/findCopyAction.ts`): the host's
+ `missingEvidenceWindows` "unfetchable: gone" windows, grouped by recording, one recording at a time: the newest
+ 200 Wayback capture of its page, else the first archive.org mirror; a lookup archive.org keeps refusing stops the
+ run (`stopped`); none found → `text-only`. Every found copy's windows go to ONE `fetchWindowsJobAction` on
+ `clips:archiveorg` (one job, one stream), each item's `webpageUrl` the copy's URL and `copy: {from: "wayback" |
+ "archive.org", url}`, which `fetchWindows` → `fetchWindowManaged` write into the window's sidecar
+ (`ClipProvenance.copy`, `coerceClipCopy`; a replay keeps it). The lookups run in the request. fetch-windows' door
+ (`planFetchWindows`) now refuses a gone recording's window unless the item names a `webpageUrl` — before, it would
+ have asked the dead page.
+- **(d) compose**: a cited moment with no prepared media whose recording is gone (`recordGoneState`) or whose post is
+ deleted (`postGoneState`) is accepted and flagged `sourceGone` on its citation view (`SpanCitationView`,
+ `PostCitationView`) and its moment page (`MomentPageView`), with no clip or shot; a live one is still
+ `missing-media`. `ResolvedSiteReports.sourceGone` / `ComposedReports.sourceGone` list them; compose and `reports
+ check` log each as a warning. `prepareReportMedia` writes them to the index's new `warnings` (kind `source-gone`)
+ instead of `problems` (checked after the unreachable-drive check), and `reports prepare` prints them; neither fails.
+ `MomentArticle` shows "Source deleted" (or "Source made private") where the clip would be; `CitationCard` says it
+ in the kind row and its link reads "Open <span>" for "Play". No schema doc lists the view shapes, so nothing was
+ regenerated; `REPORT_VIEWS_VERSION` stays 1 (an optional field).
+
+| Commit | What |
+| --- | --- |
+| `d40960d6` | common: `sourceGone.ts`/`-server.ts`, `waybackClient.ts`, `findCopy.ts`, `ClipProvenance.copy`, compose's acceptance and the views, prepare's warnings, `reports check`, the two components, the archive.org fake; tests |
+| `e479489f` | editor, export, scripts: the `find-copy` and `wayback-lookup` routes, `archive-search {youtubeId}`, the fetch-windows door, the replay; ops rows and help (capture-posts names Bluesky); COMMANDS.md, OPERATING.md; the report-site fixture's `g01` and its spec |
+| `b5d5721e` | common: find-copy moved to `publish/findCopy.ts` (controller/ may not import publish/: `architecture.test.ts` named the back-edge) |
+| (this commit) | this record, FACTS, CHANGELOG |
+
+Gates (from the worktree root):
+- `pnpm -r exec tsc --noEmit`: clean at every commit.
+- common: 4204 (E1) → 4218, all pass (+14: `lib/sourceGone.test.ts` 2, `lib/waybackClient.test.ts` 3,
+ `publish/findCopy.test.ts` 6, `controller/fetchWindows.test.ts` +1 (the copy in the sidecar),
+ `publish/composeReports.test.ts` +1 (acceptance, private, refusal), `publish/reportMedia.test.ts` +1 (the
+ warnings); `publish/missingEvidenceWindows.test.ts` names `gone`). Refresh's suites unchanged and green.
+- editor unit 304 → 308/308 (`_research.test.ts` +3: archive-search's id mode, wayback-lookup, find-copy refused at
+ the door; `fetchWindowsAction.test.ts` +1: the gone door). mcp 370/370; `test:scripts` 1010 + 3 skipped; export
+ unit 117/117 (`reports.test.ts`: the new moment's params, the reference numbers); homepage unit 25/25.
+- `docs env|files|cli --check`, `settings example --check`: clean.
+- Builds, capped, through the heavy slot, one at a time: editor `next build` 129 s, export `next build` 175 s.
+- export report suite, single specs in the foreground: `report-site.spec.ts` 24/24 (25.7 s, its stage built; the
+ source-deleted moment: "Source deleted" on the reference card and the moment page, no clip, its cue in span);
+ `slides.spec.ts` + `audit.spec.ts` 14/14 and `overview.spec.ts` + `timeline.spec.ts` 9/9 over the same stage
+ (`E2E_REPORT_SITE_REUSE=1`). Homepage `articles.spec.ts` 4/4 (it reads the same fixture).
+- One real request left the machine in a unit test, once, while it was being written: an editor route test asked
+ `wayback-lookup` for a record of a YouTube channel with no metadata, whose page `findVideoSourceUrl` rebuilt from the
+ id, and the default client asked web.archive.org's CDX for `youtube.com/watch?v=no-such-video` (200, no captures).
+ The test now names a record of no channel (404 before any request).
+
+Not done: the editor has no UI for find-copy (ops and the research door only — the brief named none); prepare's
+`warnings` are in the index and the job log, not on the editor's Reports tab.
+
## Not in this release
Auto-posting to X/Bluesky/YouTube (text only); any umtool restructuring; the "en track → 0 cues" bug (closed in r20).
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -103,6 +103,10 @@
// pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'
// pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'
// pnpm ops archive-item --json '{"item":"example-item"}'
+// pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'
+// pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'
+// pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'
+// pnpm ops find-copy --json '{"article":"demo-article"}' --wait
// pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait
// pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'
@@ -410,6 +414,13 @@ const ACTIONS = [
"archive-search",
"archive-item",
"import-post",
+ // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page
+ // ({url} or a record's {slug, id}), read only and paced; and find-copy — a
+ // copy of every gone recording a report cites (Wayback, then archive.org),
+ // its windows fetched from it as one fetch-windows job ({article} |
+ // {articles: true} | {siteId}, dryRun?).
+ "wayback-lookup",
+ "find-copy",
// GENERATION (release 27 S6): a sweep, a report or video revision, or a
// narration step over an article's iteration ({task, article, iteration?,
// model?, extractorModel?, feedback?, question?, channels?, copyOf?, maxUsd?,
@@ -424,7 +435,8 @@ const ACTIONS = [
// rejected ({article, iteration, ids?, approve?, note?}). Synchronous.
"research-approve",
// THE VERDICT BENCH (release 28 M7): ruled fact-check claims asked of each
- // model, one per call ({models, run?, reports?, window?, maxUsd?, limit?}),
+ // model, one per call ({models, run?, reports?, window?, windowMode?,
+ // maxUsd?, limit?, itemsFrom?}),
// as a bench-verdicts job on draft:local (any local model) or draft:api.
"bench-verdicts",
// RECURRING REPORTS (umtool R5): a living report or a dated series on a
@@ -1076,10 +1088,12 @@ export function usage() {
' 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 captures archived posts of a social channel (X, forum): a',
- ' screenshot of each through the connected X profile (a forum thread: its',
- ' host\'s forum profile), and its attached media through gallery-dl (a',
- ' forum thread: the same profile), into the channel\'s posts-media/<id>/:',
+ '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/<id>/:',
' {"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',
@@ -1220,6 +1234,11 @@ export function usage() {
' [{identifier, title?}]}, in identifier order. One request through the',
" editor's archive.org client, paced and backed off as an import is. Read",
' only; import-archive-org with "query" imports what a search finds.',
+ ' {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload',
+ ' instead: items naming the id in their identifier, title, description or',
+ ' original URL, each read for its files -> {query, found, items:',
+ ' [{identifier, title?, file, url, source, size?}], skipped: [{identifier,',
+ ' why}]}: each mirror\'s direct video file URL, an original preferred.',
"",
'archive-item answers one archive.org item\'s files from its metadata:',
' {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?,',
@@ -1228,6 +1247,29 @@ export function usage() {
" originals an import takes (one record each); restricted, what archive.org",
" will not hand out. Read only; nothing is downloaded.",
"",
+ 'wayback-lookup answers the Wayback Machine\'s captures of a page (its CDX',
+ ' API): {"url"} or a record\'s {"slug", "id"} (its metadata\'s page, else',
+ ' its availability check\'s, else the playlist\'s), "okOnly"?: only the',
+ ' captures that recorded a 200, "limit"?: 100 (at most 500) -> {url,',
+ ' found, captures: [{timestamp, status, mimetype?, replayUrl}]}, oldest',
+ " first. One request through the editor's Wayback client, with archive.org's",
+ " manners (one at a time, 2 s apart, 429s waited out). Read only.",
+ "",
+ 'find-copy looks for a copy of every gone recording (deleted or private) a',
+ ' report cites, and fetches the cited windows from it: {"article"} |',
+ ' {"articles": true} | {"siteId"}, "dryRun"?. Per recording, one at a time:',
+ " the Wayback Machine (the newest capture of its page that recorded a 200),",
+ " then archive.org (a mirror naming its YouTube id, an original video file",
+ " preferred). Every copy's windows go to ONE fetch-windows job on the",
+ " archive.org clip queue, the copy's URL as each window's page, so the clips",
+ " land in the recording's own clips/ with the copy (wayback or archive.org,",
+ " and its URL) in each window's provenance. A recording with no copy is",
+ ' left: its moments show their words only, marked "Source deleted". ->',
+ " {recordings: [{slug, id, gone, watchUrl, youtubeId, windows, tried:",
+ " [{from, found, url?, detail?, error?}], copy?, outcome: fetch | text-only",
+ " | error}], items, stopped?, jobId?, refused?}. dryRun answers the lookups",
+ " and starts nothing.",
+ "",
'import-post imports ONE post by its URL into a posts channel of its',
' platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a',
' Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read',
@@ -1313,15 +1355,20 @@ export function usage() {
"",
'bench-verdicts runs the verdict bench as a bench-verdicts job: {"models":',
' ["…"], "run"?, "reports"?: ["<article>"], "window"? (seconds, default 60),',
- ' "maxUsd"? (default 5), "limit"?} -> {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 claim,",
- " its quotes, the transcript within 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 (answered pairs are skipped). Results stay local, in",
- " .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with",
+ ' "windowMode"? ("seconds" | "turn": the cited speaker\'s turn, bounded by',
+ ' the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the',
+ ' operator\'s verdict), "itemsFrom"? (an earlier run\'s exact items; no',
+ ' reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim',
+ " of the registry's fact-checks (or of \"reports\") with the operator's verdict",
+ " and a citation with cues is asked of each model, one claim per call (the",
+ " report's title, the claim's section, the claim, its quotes, the transcript",
+ " in the window; never the findings or the verdict), and scored against the",
+ " rulings. On draft:local when any model is local (through the GPU arbiter;",
+ " unloaded at the end), else draft:api; the run stops at maxUsd, and an API",
+ " run is refused past caps.daily. A \"run\" that exists continues with this",
+ " call's models only (answered pairs are skipped; refused under another",
+ " prompt version). Results stay local, in .generation/bench/verdicts/<run>/",
+ " (umtool's /tools/bench). The log ends with",
" @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}.",
"",
'report-schedule keeps a recurring report on a cadence the editor ticks:',
diff --git a/umtool/app/api/bench/marks/route.ts b/umtool/app/api/bench/marks/route.ts
@@ -0,0 +1,26 @@
+import { markBenchItem } from "@/lib/bench";
+
+export const dynamic = "force-dynamic";
+
+// MARK A DISAGREEMENT (release 29 V1): the operator's Right / Wrong on one
+// model's answer that is not the ruling — was the MODEL right? — kept beside
+// the run (umtool's own file, lib/bench-marks.mjs); marked precision is read
+// from them on /tools/bench.
+// POST {run, model, key, verdict: "right" | "wrong" | null} -> {mark}
+// 400 a bad body or not a disagreement; 404 no such run, item or answer;
+// 409 a marks file that does not read
+export async function POST(request: Request) {
+ const headers = { "cache-control": "no-store" };
+ try {
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b || typeof b.run !== "string" || typeof b.model !== "string" || typeof b.key !== "string") {
+ return Response.json({ error: 'send {"run", "model", "key", "verdict": "right" | "wrong" | null}' }, { status: 400, headers });
+ }
+ const verdict = b.verdict === "right" || b.verdict === "wrong" ? b.verdict : b.verdict === null ? null : undefined;
+ if (verdict === undefined) return Response.json({ error: '"verdict" is "right", "wrong" or null' }, { status: 400, headers });
+ return Response.json(await markBenchItem(b.run, b.model, b.key, verdict), { headers });
+ } catch (e) {
+ const status = (e as { status?: number })?.status ?? 500;
+ return Response.json({ error: (e as Error)?.message ?? String(e) }, { status, headers });
+ }
+}
diff --git a/umtool/app/tools/bench/page.tsx b/umtool/app/tools/bench/page.tsx
@@ -1,17 +1,20 @@
import Link from "next/link";
import AppShell from "@/components/shell/AppShell";
import BarForm from "@/components/bench/BarForm";
+import MarkButtons from "@/components/bench/MarkButtons";
import { badgeVariants } from "@/components/ui/badge";
import {
BASELINE_MODEL,
VERDICTS,
+ VERDICT_MEANINGS,
+ VERDICT_TIE_RULE,
filterBenchRows,
passesBar,
readBenchRuns,
readBenchView,
readVerdictsPolicy,
} from "@/lib/bench";
-import type { ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index";
+import type { MarkedScore, ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index";
import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings";
export const dynamic = "force-dynamic";
@@ -24,9 +27,15 @@ export const dynamic = "force-dynamic";
// first. The bar (settings.generation.verdicts) is set here, and each model's
// pass or fail read against it — the handoff for the verdict proposals. The
// runs are local-only (`archilyzer reports bench-verdicts`); zero client JS
-// but the bar's form.
+// but the bar's form and the marks.
+//
+// Release 29 V1: the run's prompt version and items hash; "compare with" over
+// the runs with the same items (each model's agreement in both, the claims
+// 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).
-type Search = { run?: string; model?: string; verdict?: string };
+type Search = { run?: string; model?: string; verdict?: string; compare?: string };
const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 1000) / 10}%`);
@@ -34,7 +43,8 @@ export default async function BenchPage({ searchParams }: { searchParams: Promis
const sp = await searchParams;
const runs = await readBenchRuns();
const id = sp.run && runs.some((r) => r.id === sp.run) ? sp.run : runs[0]?.id;
- const view = id ? await readBenchView(id) : null;
+ const view = id ? await readBenchView(id, sp.compare) : null;
+ const sameItems = view ? runs.filter((r) => r.id !== id && r.itemsHash === view.itemsHash) : [];
let policy: GenerationVerdicts | null = null;
let policyError: string | null = null;
try {
@@ -81,7 +91,7 @@ export default async function BenchPage({ searchParams }: { searchParams: Promis
run {id} cannot be read
</p>
) : (
- <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} />
+ <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} sameItems={sameItems} />
)}
</>
)}
@@ -96,12 +106,14 @@ function RunView({
policyError,
sp,
qs,
+ sameItems,
}: {
view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>;
policy: GenerationVerdicts | null;
policyError: string | null;
sp: Search;
qs: (n: Partial<Search>) => string;
+ sameItems: Awaited<ReturnType<typeof readBenchRuns>>;
}) {
const { summary: s, score } = view;
const bar = policy?.bar ?? null;
@@ -110,7 +122,14 @@ function RunView({
return (
<div data-bench-run={s.id} data-status={s.status} className="flex flex-col gap-4">
<p role="status" className="text-[var(--color-dim)]">
- {s.status} · {s.items} items · {s.skipped.length} skipped · a {s.windowS} s window · ${s.spentUsd.toFixed(4)} of ${s.maxUsd} ·{" "}
+ {s.status} · {s.items} items · {s.skipped.length} skipped
+ {s.dropped?.length ? ` · ${s.dropped.length} citations dropped` : ""} ·{" "}
+ {s.windowMode === "turn" ? `the speaker's turn within ${s.windowS} s` : `a ${s.windowS} s window`} ·{" "}
+ <span data-prompt-version={view.promptVersion}>prompt v{view.promptVersion}</span> ·{" "}
+ <span data-items-hash={view.itemsHash} className="font-mono">
+ items {view.itemsHash}
+ </span>
+ {s.itemsFrom ? ` (from ${s.itemsFrom})` : ""} · ${s.spentUsd.toFixed(4)} of ${s.maxUsd} ·{" "}
{new Date(s.createdAt).toISOString().slice(0, 16).replace("T", " ")} UTC
{s.stopped?.length ? ` · stopped: ${s.stopped.join("; ")}` : ""}
</p>
@@ -119,15 +138,19 @@ function RunView({
<ModelTile key={m.model} m={m} baseline={m.model === BASELINE_MODEL ? null : score.baseline} pass={bar && m.model !== BASELINE_MODEL ? passesBar(m, bar) : null} />
))}
</section>
- <section aria-label="the bar" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
- {policy ? (
- <BarForm initial={policy} models={score.models} />
- ) : (
- <p role="alert" className="text-[var(--color-bad)]">
- the bar cannot be read: {policyError}
- </p>
- )}
- </section>
+ <div className="flex flex-wrap items-start gap-3">
+ <section aria-label="the bar" className="min-w-[24rem] flex-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
+ {policy ? (
+ <BarForm initial={policy} models={score.models} />
+ ) : (
+ <p role="alert" className="text-[var(--color-bad)]">
+ the bar cannot be read: {policyError}
+ </p>
+ )}
+ </section>
+ <Precision scores={score.models} marked={view.marked} />
+ </div>
+ <Compare view={view} sameItems={sameItems} qs={qs} current={sp.compare} />
<section aria-label="confusion" className="flex flex-wrap gap-4">
{score.models.map((m) => (
<Matrix key={m.model} m={m} />
@@ -176,6 +199,7 @@ function RunView({
<>
<span className={`font-mono ${a.verdict === r.verdict ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}`}>{a.verdict}</span>
{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} />}
</>
) : (
<span className="text-[var(--color-bad)]">
@@ -190,6 +214,30 @@ function RunView({
</tbody>
</table>
</section>
+ <details>
+ <summary className="micro cursor-pointer">what the verdicts mean</summary>
+ <dl aria-label="the verdicts" className="mt-1 grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5">
+ {VERDICTS.map((v) => (
+ <div key={v} className="contents">
+ <dt className="font-mono">{v}</dt>
+ <dd data-meaning={v}>{VERDICT_MEANINGS[v]}</dd>
+ </div>
+ ))}
+ </dl>
+ <p className="mt-1 text-[var(--color-dim)]">{VERDICT_TIE_RULE}</p>
+ </details>
+ {s.dropped && s.dropped.length > 0 && (
+ <details>
+ <summary className="micro cursor-pointer">dropped {s.dropped.length}</summary>
+ <ul aria-label="dropped" className="mt-1 flex flex-col gap-0.5">
+ {s.dropped.map((d) => (
+ <li key={`${d.key} ${d.citation}`} className="font-mono text-[var(--color-dim)]">
+ {d.key} {d.citation} — {d.reason}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
{s.skipped.length > 0 && (
<details>
<summary className="micro cursor-pointer">skipped {s.skipped.length}</summary>
@@ -206,6 +254,111 @@ function RunView({
);
}
+// "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[] }) {
+ return (
+ <section aria-label="precision" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
+ <span className="micro">not CORROBORATED · precision / recall</span>
+ <table className="mt-1 border-collapse">
+ <thead>
+ <tr className="micro text-left">
+ <th className="pr-3">model</th>
+ <th className="pr-3">as ruled</th>
+ <th className="pr-3">marked</th>
+ <th>marks</th>
+ </tr>
+ </thead>
+ <tbody>
+ {scores.map((m) => {
+ const k = marked.find((x) => x.model === m.model);
+ return (
+ <tr key={m.model} data-model={m.model}>
+ <td className="pr-3 font-mono">{m.model}</td>
+ <td className="pr-3" data-metric="precision">
+ {pct(m.notCorroborated.precision)} / {pct(m.notCorroborated.recall)}
+ </td>
+ <td className="pr-3" data-metric="marked-precision">
+ {k ? `${pct(k.notCorroborated.precision)} / ${pct(k.notCorroborated.recall)}` : "—"}
+ </td>
+ <td data-metric="marks">{k && k.marks.marked ? `${k.marks.right} right · ${k.marks.wrong} wrong` : "none yet"}</td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </section>
+ );
+}
+
+// Another run over the SAME items (the same hash): each model asked in both,
+// its agreement there and here, and every claim whose answer changed.
+function Compare({
+ view,
+ sameItems,
+ qs,
+ current,
+}: {
+ view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>;
+ sameItems: Awaited<ReturnType<typeof readBenchRuns>>;
+ qs: (n: Partial<Search>) => string;
+ current?: string;
+}) {
+ if (!sameItems.length) return null;
+ const c = view.compare;
+ return (
+ <section aria-label="compare" className="flex flex-col gap-2">
+ <nav aria-label="compare with" className="flex flex-wrap items-center gap-1.5">
+ <span className="micro">compare with</span>
+ {sameItems.map((r) => (
+ <Chip key={r.id} href={qs({ compare: r.id === current ? "" : r.id })} on={r.id === current} label={`${r.id} · prompt v${r.promptVersion}`} />
+ ))}
+ </nav>
+ {c && (
+ <div data-compare={c.with}>
+ <table className="border-collapse">
+ <thead>
+ <tr className="micro text-left">
+ <th className="pr-3">model</th>
+ <th className="pr-3">{c.with} (v{c.promptVersion})</th>
+ <th className="pr-3">this run (v{view.promptVersion})</th>
+ <th>changed</th>
+ </tr>
+ </thead>
+ <tbody>
+ {c.result.models.map((m) => (
+ <tr key={m.model} data-model={m.model}>
+ <td className="pr-3 font-mono">{m.model}</td>
+ <td className="pr-3" data-metric="agreement-a">
+ {pct(m.a.agreement)}
+ </td>
+ <td className="pr-3" data-metric="agreement-b">
+ {pct(m.b.agreement)}
+ </td>
+ <td data-metric="changed">
+ {m.changed.length} · {m.fixed} now agree · {m.broke} no longer
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {c.result.models.some((m) => m.changed.length) && (
+ <ul aria-label="changed answers" className="mt-1 flex flex-col gap-0.5">
+ {c.result.models.flatMap((m) =>
+ m.changed.map((x) => (
+ <li key={`${m.model} ${x.key}`} data-changed={x.key} data-model={m.model} className="font-mono">
+ {m.model} {x.key}: {x.a ?? "none"} → {x.b ?? "none"} (ruled {x.ruled})
+ </li>
+ )),
+ )}
+ </ul>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
+
function ModelTile({ m, baseline, pass }: { m: ModelScore; baseline: ModelScore | null; pass: { pass: boolean; misses: string[] } | null }) {
const vs = (v: number | null, b: number | null | undefined) => (baseline ? `${pct(v)} (baseline ${pct(b ?? null)})` : pct(v));
return (
diff --git a/umtool/components/bench/MarkButtons.tsx b/umtool/components/bench/MarkButtons.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+// THE OPERATOR'S MARK ON A DISAGREEMENT (release 29 V1): was the MODEL right,
+// where its answer is not the ruling? Right / Wrong (pressed when set; again
+// to unmark), POSTed to /api/bench/marks, then the page re-reads so the
+// marked precision beside the bar moves. R6's triage marks, on the bench.
+
+export default function MarkButtons({ run, model, item, initial }: { run: string; model: string; item: string; initial?: "right" | "wrong" }) {
+ const router = useRouter();
+ const [mark, setMark] = useState<"right" | "wrong" | undefined>(initial);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ async function send(next: "right" | "wrong") {
+ const verdict = mark === next ? null : next;
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await fetch("/api/bench/marks", { method: "POST", body: JSON.stringify({ run, model, key: item, verdict }) });
+ const body = await r.json();
+ if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`);
+ setMark(body.mark ?? undefined);
+ router.refresh();
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const cls = (on: boolean) => cn(buttonVariants({ variant: on ? "pressed" : "outline", size: "sm" }));
+ return (
+ <span className="mt-1 flex flex-wrap items-center gap-1" data-mark={mark ?? "none"}>
+ <button type="button" disabled={busy} aria-pressed={mark === "right"} className={cls(mark === "right")} onClick={() => void send("right")}>
+ Right
+ </button>
+ <button type="button" disabled={busy} aria-pressed={mark === "wrong"} className={cls(mark === "wrong")} onClick={() => void send("wrong")}>
+ Wrong
+ </button>
+ {error && (
+ <span role="alert" className="text-[var(--color-bad)]">
+ {error}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/e2e/fixtures/bench-fixture.mjs b/umtool/e2e/fixtures/bench-fixture.mjs
@@ -23,8 +23,10 @@ const said = {
[QWEN]: ["CORROBORATED", "CORROBORATED", "CORROBORATED", null],
};
-export function makeBenchRun(root) {
- const dir = path.join(root, BENCH_RUN);
+export function makeBenchRun(root, o = {}) {
+ const run = o.run ?? BENCH_RUN;
+ const answers = o.said ?? said;
+ const dir = path.join(root, run);
rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });
const items = claims.map(([id, text, verdict], i) => ({
@@ -37,7 +39,7 @@ export function makeBenchRun(root) {
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" }] }],
}));
const results = [];
- for (const [model, verdicts] of Object.entries(said)) {
+ for (const [model, verdicts] of Object.entries(answers)) {
items.forEach((it, i) => {
const v = verdicts[i];
results.push({
@@ -61,15 +63,16 @@ export function makeBenchRun(root) {
JSON.stringify({
format: "archilyzer-verdict-bench",
version: 1,
- id: BENCH_RUN,
- createdAt: "2026-10-13T12:00:00.000Z",
+ id: run,
+ createdAt: o.createdAt ?? "2026-10-13T12:00:00.000Z",
updatedAt: "2026-10-13T12:05:00.000Z",
status: "done",
- models: [SONNET, QWEN],
+ models: Object.keys(answers),
+ ...(o.promptVersion ? { promptVersion: o.promptVersion } : {}),
windowS: 60,
maxUsd: 5,
reports: [],
- spentUsd: 0.016,
+ spentUsd: Object.keys(answers).includes(SONNET) ? 0.016 : 0,
items: items.length,
skipped: [{ key: "synth-bench/c5", report: "synth-bench", claim: "c5", reason: "no citation" }],
score: {},
@@ -77,3 +80,16 @@ export function makeBenchRun(root) {
);
return dir;
}
+
+// Release 29 V1: a second run over the SAME items (prompt version 2, made
+// earlier so the page still opens the first by default), Sonnet alone: it now
+// calls c2 PARTLY (as ruled) and c3 PARTLY (ruled CONTRADICTED).
+export const BENCH_RUN_V2 = "vb-e2e-v2";
+export function makeBenchRunV2(root) {
+ return makeBenchRun(root, {
+ run: BENCH_RUN_V2,
+ said: { [SONNET]: ["CORROBORATED", "PARTLY", "PARTLY", "NOT_FOUND"] },
+ promptVersion: "2",
+ createdAt: "2026-10-13T11:00:00.000Z",
+ });
+}
diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts
@@ -3,7 +3,7 @@ import { readFileSync, rmSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { WARM_TIMEOUT, warm } from "./warm";
-import { BENCH_RUN, QWEN, SONNET, makeBenchRun } from "./fixtures/bench-fixture.mjs";
+import { BENCH_RUN, BENCH_RUN_V2, QWEN, SONNET, makeBenchRun, makeBenchRunV2 } from "./fixtures/bench-fixture.mjs";
// ---------------------------------------------------------------------------
// The verdict bench's page (release 28 M7) over a synthetic run in the
@@ -25,11 +25,13 @@ const stubAsked = (route: string) =>
test.beforeAll(async ({ playwright }) => {
test.setTimeout(WARM_TIMEOUT);
makeBenchRun(ROOT);
+ makeBenchRunV2(ROOT);
await warm(playwright, ["/bench", "/api/bench/bar"]);
});
test.afterAll(async ({ request }) => {
await request.post("/api/bench/bar", { data: { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] } });
rmSync(path.join(ROOT, BENCH_RUN), { recursive: true, force: true });
+ rmSync(path.join(ROOT, BENCH_RUN_V2), { recursive: true, force: true });
});
test("the run: each model's tile against the baseline, the matrix, the items with disagreements first, the filters", async ({ page }) => {
@@ -95,3 +97,56 @@ test("the bar: saved through the editor's settings action; a passing model ticke
await expect(page.getByRole("form", { name: "bar" }).getByRole("checkbox", { name: `use ${SONNET}` })).toBeChecked();
await expect(page.getByRole("form", { name: "bar" }).getByRole("spinbutton", { name: "minimum agreement" })).toHaveValue("50");
});
+
+test("V1: the run's prompt version and items hash; compare with a run over the same items", async ({ page }) => {
+ await page.goto(`/tools/bench?run=${BENCH_RUN_V2}`);
+ const status = page.locator(`[data-bench-run="${BENCH_RUN_V2}"]`).getByRole("status");
+ await expect(status.locator("[data-prompt-version]")).toHaveText("prompt v2");
+ const hash = await status.locator("[data-items-hash]").getAttribute("data-items-hash");
+ expect(hash).toMatch(/^[0-9a-f]{16}$/);
+ // The first run (made before V1: version 1) has the same items.
+ await page.goto(`/tools/bench?run=${BENCH_RUN}`);
+ await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`).getByRole("status").locator("[data-prompt-version]")).toHaveText("prompt v1");
+ await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`).getByRole("status").locator("[data-items-hash]")).toHaveAttribute("data-items-hash", hash!);
+ await page.goto(`/tools/bench?run=${BENCH_RUN_V2}`);
+ const compare = page.getByRole("region", { name: "compare" });
+ await compare.getByRole("navigation", { name: "compare with" }).getByRole("link", { name: `${BENCH_RUN} · prompt v1` }).click();
+ await expect(page).toHaveURL(new RegExp(`compare=${BENCH_RUN}`));
+ const row = compare.locator(`[data-compare="${BENCH_RUN}"] tr[data-model="${SONNET}"]`);
+ await expect(row.locator('[data-metric="agreement-a"]')).toHaveText("75%");
+ await expect(row.locator('[data-metric="agreement-b"]')).toHaveText("75%");
+ await expect(row.locator('[data-metric="changed"]')).toHaveText("2 · 1 now agree · 1 no longer");
+ // Only Sonnet was asked in both.
+ await expect(compare.locator(`tr[data-model="${QWEN}"]`)).toHaveCount(0);
+ const changed = compare.getByRole("list", { name: "changed answers" }).locator("li");
+ await expect(changed).toHaveCount(2);
+ await expect(changed.nth(0)).toHaveText(`${SONNET} synth-bench/c2: CORROBORATED → PARTLY (ruled PARTLY)`);
+ 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");
+});
+
+test("V1: a Right mark on a disagreement moves the marked precision; again unmarks", async ({ page }) => {
+ await page.goto(`/tools/bench?run=${BENCH_RUN}`);
+ const precision = page.getByRole("region", { name: "precision" }).locator(`tr[data-model="${SONNET}"]`);
+ await expect(precision.locator('[data-metric="precision"]')).toHaveText("100% / 66.7%");
+ await expect(precision.locator('[data-metric="marked-precision"]')).toHaveText("100% / 66.7%");
+ await expect(precision.locator('[data-metric="marks"]')).toHaveText("none yet");
+ // Sonnet called the PARTLY claim c2 CORROBORATED: the operator says the model was right.
+ const cell = page.getByRole("region", { name: "items" }).locator('tr[data-item="synth-bench/c2"]').locator(`[data-model="${SONNET}"]`);
+ // An agreeing answer has no mark buttons.
+ await expect(page.getByRole("region", { name: "items" }).locator('tr[data-item="synth-bench/c1"]').locator(`[data-model="${SONNET}"]`).getByRole("button")).toHaveCount(0);
+ await cell.getByRole("button", { name: "Right" }).click();
+ await expect(cell.getByRole("button", { name: "Right" })).toHaveAttribute("aria-pressed", "true");
+ await expect(precision.locator('[data-metric="marked-precision"]')).toHaveText("100% / 100%");
+ await expect(precision.locator('[data-metric="marks"]')).toHaveText("1 right · 0 wrong");
+ // The plain score is the ruling's, unmoved.
+ await expect(precision.locator('[data-metric="precision"]')).toHaveText("100% / 66.7%");
+ // Kept across a reload; again unmarks.
+ await page.reload();
+ await expect(cell.locator("[data-mark]")).toHaveAttribute("data-mark", "right");
+ await cell.getByRole("button", { name: "Right" }).click();
+ await expect(precision.locator('[data-metric="marks"]')).toHaveText("none yet");
+ await expect(cell.getByRole("button", { name: "Right" })).toHaveAttribute("aria-pressed", "false");
+});
diff --git a/umtool/lib/bench-marks.mjs b/umtool/lib/bench-marks.mjs
@@ -0,0 +1,123 @@
+// THE VERDICT BENCH'S MARKS (release 29 V1): the operator's Right / Wrong on
+// a disagreement — was the MODEL right, where its answer is not the ruling? —
+// kept beside the run, so the bar can be set from marked precision
+// (common's `markedScore`, tallied by triage's `markTally`).
+//
+// <bench root>/<run>/marks.json
+// { format: "archilyzer-bench-marks", version: 1, run,
+// marks: { "<model>": { "<report>/<claim>": { verdict: "right" | "wrong",
+// answer, at } } },
+// updatedAt }
+//
+// `answer` is the model's verdict the mark was made on: a resumed run that
+// asked again and got another answer leaves the mark stale (not applied).
+//
+// R6's discipline (lib/research/triage-marks.mjs): ONE writer (umtool),
+// serialised in-process; the whole file to a temp name and a rename; a file
+// that does not parse is never overwritten (a write refuses with 409). The
+// run's other files are the editor's job's; this one is never touched by it.
+//
+// Plain ESM: the unit test reads it the way the app does.
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+export const BENCH_MARKS_FORMAT = "archilyzer-bench-marks";
+export const BENCH_MARKS_VERSION = 1;
+const RUN_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
+const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\/[A-Za-z0-9._:-]{1,64}$/;
+const VERDICTS = ["CORROBORATED", "PARTLY", "CONTRADICTED", "NOT_FOUND", "UNTESTABLE"];
+
+export class BenchMarksError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+export const benchMarksFile = (root, run) => {
+ if (!RUN_RE.test(run)) throw new BenchMarksError(`not a run id: ${JSON.stringify(run)}`);
+ return path.join(root, run, "marks.json");
+};
+
+function clean(raw, run) {
+ const marks = {};
+ const given = raw?.marks && typeof raw.marks === "object" ? raw.marks : {};
+ for (const [model, byKey] of Object.entries(given)) {
+ if (!MODEL_RE.test(model) || !byKey || typeof byKey !== "object") continue;
+ for (const [key, m] of Object.entries(byKey)) {
+ if (!KEY_RE.test(key) || !m || (m.verdict !== "right" && m.verdict !== "wrong")) continue;
+ (marks[model] ??= {})[key] = {
+ verdict: m.verdict,
+ answer: VERDICTS.includes(m.answer) ? m.answer : null,
+ at: typeof m.at === "string" ? m.at.slice(0, 40) : "",
+ };
+ }
+ }
+ return { format: BENCH_MARKS_FORMAT, version: BENCH_MARKS_VERSION, run, marks, updatedAt: typeof raw?.updatedAt === "string" ? raw.updatedAt : "" };
+}
+
+/** A run's marks (none: an empty set). A file that does not read is a 409. */
+export async function readBenchMarksDoc(root, run) {
+ let text;
+ try {
+ text = await readFile(/* turbopackIgnore: true */ benchMarksFile(root, run), "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") return clean(null, run);
+ if (err instanceof BenchMarksError) throw err;
+ throw new BenchMarksError(`the marks of ${run} cannot be read: ${err?.message ?? err}`, 409);
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ throw new BenchMarksError(`${run}/marks.json is not JSON: ${err.message}`, 409);
+ }
+ if (raw?.format !== BENCH_MARKS_FORMAT) throw new BenchMarksError(`${run}/marks.json is not a ${BENCH_MARKS_FORMAT} file`, 409);
+ return clean(raw, run);
+}
+
+let chain = Promise.resolve();
+function serialised(fn) {
+ const run = chain.then(fn);
+ chain = run.catch(() => {});
+ return run;
+}
+
+/**
+ * Mark one disagreement right or wrong (`verdict` null: unmark), on the
+ * model's `answer`. Answers the marks as written.
+ *
+ * @param {string} root the bench runs' directory
+ * @param {string} run
+ * @param {{ model: string, key: string, verdict: "right" | "wrong" | null, answer: string | null, now?: Date }} m
+ */
+export function setBenchMark(root, run, m) {
+ return serialised(async () => {
+ if (!MODEL_RE.test(m.model ?? "")) throw new BenchMarksError(`not a model: ${JSON.stringify(m.model)}`);
+ if (!KEY_RE.test(m.key ?? "")) throw new BenchMarksError(`not an item: ${JSON.stringify(m.key)}`);
+ if (m.verdict !== null && m.verdict !== "right" && m.verdict !== "wrong") throw new BenchMarksError('"verdict" is "right", "wrong" or null');
+ const doc = await readBenchMarksDoc(root, run);
+ const at = (m.now ?? new Date()).toISOString();
+ if (m.verdict === null) {
+ if (doc.marks[m.model]) {
+ delete doc.marks[m.model][m.key];
+ if (!Object.keys(doc.marks[m.model]).length) delete doc.marks[m.model];
+ }
+ } else {
+ (doc.marks[m.model] ??= {})[m.key] = { verdict: m.verdict, answer: VERDICTS.includes(m.answer) ? m.answer : null, at };
+ }
+ doc.updatedAt = at;
+ const file = benchMarksFile(root, run);
+ await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch (err) {
+ await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {});
+ throw err;
+ }
+ return doc;
+ });
+}
diff --git a/umtool/lib/bench-marks.test.mjs b/umtool/lib/bench-marks.test.mjs
@@ -0,0 +1,35 @@
+// The verdict bench's marks (release 29 V1): set, unmark, per model and item,
+// the file shape common's reader takes; a broken file is never overwritten.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { BenchMarksError, benchMarksFile, readBenchMarksDoc, setBenchMark } from "./bench-marks.mjs";
+
+test("bench marks: right and wrong per model and item, on the answer marked; unmark; a broken file refuses", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "bench-marks-"));
+ try {
+ assert.deepEqual((await readBenchMarksDoc(root, "vb-x")).marks, {});
+ const now = new Date("2026-10-15T10:00:00Z");
+ await setBenchMark(root, "vb-x", { model: "qwen3:8b", key: "synth-ruled/r01", verdict: "right", answer: "PARTLY", now });
+ await setBenchMark(root, "vb-x", { model: "qwen3:8b", key: "synth-ruled/r02", verdict: "wrong", answer: "NOT_FOUND", now });
+ const doc = await setBenchMark(root, "vb-x", { model: "claude-sonnet-5-5", key: "synth-ruled/r01", verdict: "wrong", answer: "CONTRADICTED", now });
+ assert.deepEqual(doc.marks["qwen3:8b"]["synth-ruled/r01"], { verdict: "right", answer: "PARTLY", at: now.toISOString() });
+ assert.deepEqual(Object.keys(doc.marks).sort(), ["claude-sonnet-5-5", "qwen3:8b"]);
+ const after = await setBenchMark(root, "vb-x", { model: "claude-sonnet-5-5", key: "synth-ruled/r01", verdict: null, answer: null });
+ assert.deepEqual(Object.keys(after.marks), ["qwen3:8b"]);
+ const onDisk = JSON.parse(await readFile(benchMarksFile(root, "vb-x"), "utf8"));
+ assert.equal(onDisk.format, "archilyzer-bench-marks");
+ assert.equal(onDisk.run, "vb-x");
+ await assert.rejects(setBenchMark(root, "vb-x", { model: "q", key: "no-slash", verdict: "right", answer: null }), BenchMarksError);
+ await assert.rejects(setBenchMark(root, "Bad Run", { model: "q", key: "a/b", verdict: "right", answer: null }), /not a run id/);
+
+ await mkdir(path.join(root, "vb-broken"), { recursive: true });
+ await writeFile(benchMarksFile(root, "vb-broken"), "{ nope");
+ await assert.rejects(setBenchMark(root, "vb-broken", { model: "q", key: "a/b", verdict: "right", answer: null }), (e) => e.status === 409);
+ assert.equal(await readFile(benchMarksFile(root, "vb-broken"), "utf8"), "{ nope");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts
@@ -1,31 +1,49 @@
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import {
+ benchItemsHash,
benchRootOf,
+ compareBenchRuns,
listBenchRuns,
+ markedScore,
passesBar,
+ readBenchMarks,
readBenchRun,
scoreBench,
BASELINE_MODEL,
+ M7_PROMPT_VERSION,
type BenchItem,
+ type BenchMarks,
type BenchResult,
type BenchScore,
type BenchSummary,
+ type MarkedScore,
+ type RunCompare,
type VerdictBar,
} from "yt-dlp-transcript-common/lib/report/draft/bench/index";
-import { VERDICTS, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts";
+import { VERDICT_MEANINGS, VERDICT_TIE_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";
// THE VERDICT BENCH, AS UMTOOL SEES IT (release 28 M7): the runs `archilyzer
// reports bench-verdicts` wrote under the checkout's `.generation/bench/
-// verdicts/` (local-only; read here, never written), scored again from their
-// items and results so the page and the files cannot disagree, and the
-// operator's bar — settings.generation.verdicts — read from and written
-// through the editor's settings action, as the generation policy is.
+// verdicts/` (local-only; read here, never written — but for the operator's
+// marks, V1), scored again from their items and results so the page and the
+// files cannot disagree, and the operator's bar — settings.generation.verdicts
+// — read from and written through the editor's settings action, as the
+// generation policy is.
+//
+// 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
+// (marks.json beside the run, ./bench-marks.mjs) and the marked scores.
//
// SERVER-ONLY.
-export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd">;
+export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd"> & {
+ promptVersion: string;
+ itemsHash: string;
+};
export type BenchItemRow = {
key: string;
@@ -33,34 +51,53 @@ export type BenchItemRow = {
claim: string;
text: string;
verdict: Verdict;
- answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string }>;
+ answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string; mark?: "right" | "wrong" }>;
// A model whose answer is not the operator's (failures included).
disagree: string[];
};
export type BenchView = {
summary: BenchSummary;
+ promptVersion: string;
+ itemsHash: string;
score: BenchScore;
+ // Each model's score with the operator's marks applied.
+ marked: MarkedScore[];
items: BenchItemRow[];
+ // The other run, over the same items, this one is compared with.
+ compare?: { with: string; promptVersion: string; result: RunCompare };
};
export function benchRoot(): string {
return benchRootOf(getPaths());
}
+// A run's items hash: its summary's, else (a run before V1) computed from its items.
+async function hashOf(s: BenchSummary): Promise<string> {
+ if (s.itemsHash) return s.itemsHash;
+ const run = await readBenchRun(benchRoot(), s.id).catch(() => null);
+ return run ? benchItemsHash(run.items) : "";
+}
+
export async function readBenchRuns(): Promise<BenchRunRow[]> {
- return (await listBenchRuns(benchRoot())).map((s) => ({
- id: s.id,
- createdAt: s.createdAt,
- status: s.status,
- models: s.models,
- items: s.items,
- spentUsd: s.spentUsd,
- maxUsd: s.maxUsd,
- }));
+ const out: BenchRunRow[] = [];
+ for (const s of await listBenchRuns(benchRoot())) {
+ out.push({
+ id: s.id,
+ createdAt: s.createdAt,
+ status: s.status,
+ models: s.models,
+ items: s.items,
+ spentUsd: s.spentUsd,
+ maxUsd: s.maxUsd,
+ promptVersion: s.promptVersion ?? M7_PROMPT_VERSION,
+ itemsHash: await hashOf(s),
+ });
+ }
+ return out;
}
-function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[]): BenchItemRow[] {
+function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[], marks: BenchMarks = {}): BenchItemRow[] {
const by = new Map<string, BenchResult>();
for (const r of results) by.set(`${r.model}\u0000${r.key}`, r);
return items.map((it) => {
@@ -69,20 +106,78 @@ function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], mo
for (const m of models) {
const r = by.get(`${m}\u0000${it.key}`);
if (!r) continue;
- answers[m] = { verdict: r.verdict, ...(r.reason ? { reason: r.reason } : {}), ...(r.failure ? { failure: r.failure } : {}), ...(r.error ? { error: r.error } : {}) };
+ const mk = marks[m]?.[it.key];
+ const mark = mk && r.verdict !== it.verdict && mk.answer === r.verdict ? mk.verdict : undefined;
+ answers[m] = {
+ verdict: r.verdict,
+ ...(r.reason ? { reason: r.reason } : {}),
+ ...(r.failure ? { failure: r.failure } : {}),
+ ...(r.error ? { error: r.error } : {}),
+ ...(mark ? { mark } : {}),
+ };
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 };
});
}
-export async function readBenchView(id: string): Promise<BenchView | null> {
- const run = await readBenchRun(benchRoot(), id).catch(() => null);
+export async function readBenchView(id: string, compareWith?: string): Promise<BenchView | null> {
+ const root = benchRoot();
+ const run = await readBenchRun(root, id).catch(() => null);
if (!run) return null;
- const score = scoreBench(run.items, run.results, run.summary.models);
- return { summary: run.summary, score, items: rowsOf(run.items, run.results, run.summary.models) };
+ const models = run.summary.models;
+ const score = scoreBench(run.items, run.results, models);
+ const marks = await readBenchMarks(root, id);
+ const itemsHash = run.summary.itemsHash ?? benchItemsHash(run.items);
+ let compare: BenchView["compare"];
+ if (compareWith && compareWith !== id) {
+ const other = await readBenchRun(root, compareWith).catch(() => null);
+ // Only a run over the same items is compared.
+ if (other && (other.summary.itemsHash ?? benchItemsHash(other.items)) === itemsHash) {
+ compare = {
+ with: compareWith,
+ promptVersion: other.summary.promptVersion ?? M7_PROMPT_VERSION,
+ result: compareBenchRuns(
+ { items: other.items, results: other.results, models: other.summary.models },
+ { items: run.items, results: run.results, models },
+ ),
+ };
+ }
+ }
+ return {
+ summary: run.summary,
+ promptVersion: run.summary.promptVersion ?? M7_PROMPT_VERSION,
+ itemsHash,
+ score,
+ marked: models.map((m) => markedScore(run.items, run.results, m, marks)),
+ items: rowsOf(run.items, run.results, models, marks),
+ ...(compare ? { compare } : {}),
+ };
}
+/**
+ * Mark one disagreement: was the model right where its answer is not the
+ * operator's ruling? Only a disagreement with an answer is marked; the mark
+ * records the answer it was made on. Answers the item's row as it now is.
+ */
+export async function markBenchItem(run: string, model: string, key: string, verdict: "right" | "wrong" | null): Promise<{ mark: "right" | "wrong" | null }> {
+ const root = benchRoot();
+ const r = await readBenchRun(root, run).catch(() => null);
+ if (!r) throw new BenchMarksError(`no run ${run}`, 404);
+ const item = r.items.find((i) => i.key === key);
+ if (!item) throw new BenchMarksError(`no item ${key} in run ${run}`, 404);
+ let answer: BenchResult | undefined;
+ for (const x of r.results) if (x.model === model && x.key === key) answer = x;
+ if (!answer) throw new BenchMarksError(`${model} was not asked about ${key}`, 404);
+ if (verdict !== null && (!isVerdict(answer.verdict) || answer.verdict === item.verdict)) {
+ throw new BenchMarksError(`${model}'s answer on ${key} is not a disagreement to mark`, 400);
+ }
+ await setBenchMark(root, run, { model, key, verdict, answer: answer.verdict });
+ return { mark: verdict };
+}
+
+export { VERDICT_MEANINGS, VERDICT_TIE_RULE };
+
// The rows a filter keeps, disagreements first (then in item order).
export function filterBenchRows(rows: readonly BenchItemRow[], f: { model?: string; verdict?: string }): BenchItemRow[] {
const kept = rows.filter(