Archilyzer · Source

archilyzer

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

commit 15e109ea96cb7f0cdd092d9ee6ea6fd53782ba92
parent 6ac8db2142265f1f3ebd84dc0f812a313ee73b7f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 10:41:26 -0400

Merge r29/evidence review fixes (E1/E2) into r29/integration

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

Diffstat:
MCOMMANDS.md | 6+++---
Mcommon/controller/capturePosts.ts | 6+++++-
Mcommon/controller/checkPostAvailability.ts | 1+
Mcommon/controller/fetchWindows.test.ts | 15+++++++++++++++
Mcommon/controller/fetchWindows.ts | 17+++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 2++
Mcommon/jobs/jobKinds.ts | 10++++++++++
Acommon/lib/copyAttempts-server.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/copyAttempts.test.ts | 31+++++++++++++++++++++++++++++++
Mcommon/lib/waybackClient.test.ts | 19++++++++++++++++++-
Mcommon/lib/waybackClient.ts | 32++++++++++++++++++++++++++++++++
Mcommon/publish/citedPostCaptures.ts | 10++++++++++
Mcommon/publish/composeReports.test.ts | 50+++++++++++++++++++++++++++++++++++++-------------
Mcommon/publish/composeReports.ts | 52+++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/publish/findCopy.test.ts | 225+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mcommon/publish/findCopy.ts | 338++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Mcommon/publish/missingEvidenceWindows.test.ts | 21+++++++++++++++++++++
Mcommon/publish/reportMedia.test.ts | 6+++---
Mcommon/publish/reportMedia.ts | 39++++++++++++++++++++++++++++++++-------
Mcommon/social/blueskyFetcher.ts | 10+++++++++-
Mcommon/social/blueskyPostCapture.test.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/social/blueskyPostCapture.ts | 157++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
Mcommon/social/fetchers.ts | 7+++++++
Mcommon/testing/web/fakeWayback.d.mts | 3++-
Mcommon/testing/web/fakeWayback.mjs | 15+++++++++++++++
Meditor/CHANGELOG.md | 6++++--
Meditor/app/api/ops/archive-search/route.ts | 20+++++++++++---------
Meditor/app/api/ops/fetch-windows/route.ts | 14++++++++++++--
Meditor/app/api/ops/find-copy/route.ts | 48++++++++++++++++++++++++------------------------
Meditor/app/channels/[slug]/videos/fetchWindowsAction.test.ts | 11+++++++++++
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 11++++++-----
Meditor/app/channels/[slug]/videos/findCopyAction.ts | 86+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mplans/FACTS.md | 19+++++++++++++++----
Mplans/release-29.md | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 44++++++++++++++++++++++++++------------------
35 files changed, 1127 insertions(+), 385 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -129,7 +129,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. | | | `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. | `pnpm ops persist-videos --file list.json --wait` | -| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?}, ...\], "requestedBy", "manifest"?} fetches a list. "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | +| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | | `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` | | `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` | @@ -142,11 +142,11 @@ 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)} -&gt; {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)} -&gt; {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)} -&gt; {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 -&gt; {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-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {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 OF it (their identifier, a file name or their original URL names the id; a title or description that mentions it is not enough), each read for its files -&gt; {query, found, items: \[{identifier, title?, file, url, source, size?, seconds?, namedBy}\], 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"} -&gt; {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/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, 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) -&gt; {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". -&gt; {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` | +| `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, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from before is not picked again. 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". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. | `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", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` | | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | | `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "verdict", "at", "note"?} -&gt; {proposal}. "verdict" and "at" are the proposal you were shown (its verdicts.proposed.json entry): a compare-and-set, refused (409) when the proposal was replaced or reviewed since, its claim changed (the proposal is stale) or was ruled meanwhile. approve sets the claim's verdict to it (through the registry); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'` | diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -145,10 +145,12 @@ export async function capturePosts( links: string[]; url?: string; media?: { kind: string; url: string; name?: string }[]; + author?: string; }; let archived: Map<string, Archived> | undefined; const forum = fetcher.platform === "xenforo"; - if ((opts.articles !== false && fetcher.platform === "twitter") || forum) { + const bluesky = fetcher.platform === "bluesky"; + if ((opts.articles !== false && fetcher.platform === "twitter") || forum || bluesky) { const wanted = new Set(ids); archived = new Map(); for (const p of await readAllPosts(channelRoot)) { @@ -157,6 +159,8 @@ export async function capturePosts( text: p.text, links: p.links ?? [], ...(forum ? { url: p.url, ...(p.media ? { media: p.media } : {}) } : {}), + // Bluesky looks each post up under its own author (a repost's is the original's). + ...(bluesky ? { url: p.url, author: p.author } : {}), }); } } diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -164,6 +164,7 @@ export async function checkPostAvailability( observations = await fetcher.checkAvailability({ ids: batch, handle, + authors: new Map(posts.map((p) => [p.id, p.author])), signal: signal ?? controller.signal, onLog: log, }); diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -436,3 +436,18 @@ test("a window of a gone recording fetched from a copy (find-copy) records which assert.deepEqual(parseClipProvenance(sidecar)?.copy, copy); assert.equal(parseClipProvenance({ requestedBy: "x", copy: { from: "elsewhere", url: copy.url } })?.copy, undefined); }); + +test("a copy whose fetch failed is recorded beside the recording (find-copy will not pick it again); a rate limit is not", async () => { + const paths = await corpus(); + const recorded: [string, unknown][] = []; + const h = harness({ recordFailedCopy: async (dir, f) => void recorded.push([dir, f]) }); + const copy = { from: "archive.org" as const, url: "https://www.youtube.com/gone" }; + const r = await go(paths, [{ slug: "c", id: "v1", from: 10, to: 20, webpageUrl: copy.url, copy }], h); + assert.equal(r.failed.length, 1); + assert.equal(recorded.length, 1); + assert.equal(recorded[0]![0], path.join(paths.channelsDir, "c", "data", "v1")); + assert.deepEqual({ ...(recorded[0]![1] as object), at: undefined, error: undefined }, { ...copy, at: undefined, error: undefined }); + const limited = { ...copy, url: "https://www.youtube.com/429" }; + await go(paths, [{ slug: "c", id: "v2", from: 10, to: 20, webpageUrl: limited.url, copy: limited }], h); + assert.equal(recorded.length, 1, "a rate limit says nothing about the copy"); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -5,6 +5,7 @@ import type { SiteSettings } from "../lib/settings"; import { getSettings } from "../lib/settings"; import type { DownloadFailureClass } from "../lib/availability"; import type { ClipCopy } from "../lib/clipWindow"; +import { recordFailedCopy, type FailedCopy } from "../lib/copyAttempts-server"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { detectPlatform } from "../lib/platform"; @@ -131,6 +132,10 @@ export type FetchWindowsItem = { // The copy of a gone recording `webpageUrl` is (release 29 E2, find-copy): // recorded in the window's provenance. copy?: ClipCopy; + // Fetch from the recording's own page even though its availability says it + // is gone (a stale reading: made public again, a geo block read as removed). + // The editor's door refuses a gone recording's window without it. + force?: boolean; }; export type FetchWindowsFailureClass = @@ -207,6 +212,8 @@ export type FetchWindowsDeps = { // put the second one's first fetch right after the first one's last. gapRemainingMs: (key: string) => number; noteGap: (key: string, gapMs: number) => void; + // A find-copy copy whose fetch failed (lib/copyAttempts-server.ts). + recordFailedCopy: (videoDir: string, failed: FailedCopy) => Promise<void>; }; function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { @@ -243,6 +250,7 @@ const DEFAULT_DEPS: FetchWindowsDeps = { recordClean: (platform, paths) => recordPlatformClean(platform, paths), gapRemainingMs: (key) => platformGapRemainingMs(key), noteGap: (key, gapMs) => notePlatformGap(key, gapMs), + recordFailedCopy, }; export function fetchWindowsItemLabel(item: FetchWindowsItem): string { @@ -548,6 +556,15 @@ export async function fetchWindows({ const cls: FetchWindowsFailureClass = e instanceof FetchWindowError ? e.failureClass : "unknown"; fail(item, cls, message); + // A COPY THAT FAILED (find-copy's, release 29 review) is recorded beside + // the recording, so the next find-copy falls through to another copy. A + // rate limit says nothing about the copy, and neither does a cancel. + if (item.copy && cls !== "rate_limit" && !fetchSignal.aborted) { + await deps + .recordFailedCopy(videoDir, { ...item.copy, at: new Date().toISOString(), error: message }) + .catch(() => {}); + log(` ${label}: the ${item.copy.from} copy failed — find-copy will not pick it again.`); + } done += 1; progress(); if (cls === "rate_limit") { diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -101,6 +101,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = { "tts-file": { label: "Text to speech", drainable: false }, // The verdict bench (pnpm ops bench-verdicts, release 28 M7): one run. "bench-verdicts": { label: "Verdict bench", drainable: false }, + // find-copy (release 29 E2): the lookups, then one fetch-windows job. + "find-copy": { label: "Find copies", drainable: false }, }; test("added kinds carry their pinned label and drainability", () => { diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -962,6 +962,16 @@ const JOB_KINDS: Record<string, JobKindMeta> = { // the article registry and cues' text, and writes only under the checkout's // `.generation/bench/`; neither guard. Not replayable: a re-run of the same // run id resumes it. + // find-copy (release 29 E2): the Wayback and archive.org lookups for the + // gone recordings a report cites, then (unless a dry run) ONE fetch-windows + // job for the copies found. Its own queue; the clients pace the requests. + "find-copy": { + kind: "find-copy", + label: "Find copies", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + }, "bench-verdicts": { kind: "bench-verdicts", label: "Verdict bench", diff --git a/common/lib/copyAttempts-server.ts b/common/lib/copyAttempts-server.ts @@ -0,0 +1,43 @@ +// THE COPIES OF A GONE RECORDING THAT FAILED (release 29 review): a window +// find-copy sent to fetch-windows from a copy (a Wayback capture, an +// archive.org file) whose fetch failed. `data/<id>/copy-attempts.json`, so a +// later find-copy does not pick the same copy again and falls through to the +// next (Wayback → archive.org → the next mirror). Written by fetch-windows +// (controller/fetchWindows.ts) on an item's failure; read by find-copy. +// +// SERVER-ONLY (node:fs). + +import { coerceClipCopy, type ClipCopy } from "./clipWindow"; +import { sidecar, sidecarField } from "./sidecar-server"; + +export const COPY_ATTEMPTS_FILENAME = "copy-attempts.json"; + +export type FailedCopy = ClipCopy & { at: string; error: string }; +export type CopyAttempts = { failed: FailedCopy[] }; + +// The newest few, one per URL. +const KEEP = 20; + +export function coerceCopyAttempts(value: unknown): CopyAttempts | null { + const v = value as { failed?: unknown } | null; + if (!v || typeof v !== "object" || !Array.isArray(v.failed)) return null; + const failed: FailedCopy[] = []; + for (const f of v.failed) { + const copy = coerceClipCopy(f); + const r = f as { at?: unknown; error?: unknown }; + if (copy && typeof r.at === "string") failed.push({ ...copy, at: r.at, error: typeof r.error === "string" ? r.error : "" }); + } + return { failed }; +} + +export const copyAttemptsSidecar = sidecar(COPY_ATTEMPTS_FILENAME, sidecarField(coerceCopyAttempts)); + +export async function readFailedCopies(videoDir: string): Promise<FailedCopy[]> { + return (await copyAttemptsSidecar.load(videoDir).catch(() => null))?.failed ?? []; +} + +export async function recordFailedCopy(videoDir: string, failed: FailedCopy): Promise<void> { + const prev = await readFailedCopies(videoDir); + const next = [...prev.filter((f) => f.url !== failed.url), { ...failed, error: failed.error.slice(0, 400) }].slice(-KEEP); + await copyAttemptsSidecar.write(videoDir, { failed: next }); +} diff --git a/common/lib/copyAttempts.test.ts b/common/lib/copyAttempts.test.ts @@ -0,0 +1,31 @@ +// The failed copies of a gone recording (release 29 review): appended one per +// URL, the newest kept, read back for find-copy. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/copyAttempts.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { COPY_ATTEMPTS_FILENAME, readFailedCopies, recordFailedCopy } from "./copyAttempts-server"; + +test("recordFailedCopy appends one per URL, newest last; readFailedCopies reads them", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "copy-attempts-")); + try { + assert.deepEqual(await readFailedCopies(dir), []); + await recordFailedCopy(dir, { from: "wayback", url: "https://web.archive.org/web/x", at: "1", error: "404" }); + await recordFailedCopy(dir, { from: "archive.org", url: "https://archive.org/download/a/b.mp4", at: "2", error: "403" }); + await recordFailedCopy(dir, { from: "wayback", url: "https://web.archive.org/web/x", at: "3", error: "410" }); + assert.deepEqual( + (await readFailedCopies(dir)).map((f) => [f.from, f.at, f.error]), + [ + ["archive.org", "2", "403"], + ["wayback", "3", "410"], + ], + ); + assert.equal(COPY_ATTEMPTS_FILENAME, "copy-attempts.json"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/waybackClient.test.ts b/common/lib/waybackClient.test.ts @@ -7,7 +7,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { startFakeWayback } from "../testing/web/fakeWayback.mjs"; -import { parseCdxJson, waybackCdxUrl, WaybackClient, waybackReplayUrl } from "./waybackClient"; +import { parseCdxJson, waybackCdxUrl, WaybackClient, waybackReplayUrl, waybackYoutubeUrl } from "./waybackClient"; import { ArchiveOrgRequestError } from "./archiveOrgClient"; const BREAD = "https://video.example/watch?v=bread-day-01"; @@ -78,3 +78,20 @@ test("a 429 is waited out (Retry-After) and asked again; one that persists stops await busy.close(); } }); + +test("youtubeVideoArchived: yt-dlp's check — the video index's formats, not a capture of the page", async () => { + const wb = await startFakeWayback({ videos: ["waybackVid1"] }); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + assert.equal(await c.youtubeVideoArchived("waybackVid1"), true); + assert.equal(await c.youtubeVideoArchived("pageOnly001"), false); + assert.deepEqual(wb.requests.map((r) => r.path), [ + "/__wb/videoinfo?vtype=youtube&vid=waybackVid1", + "/__wb/videoinfo?vtype=youtube&vid=pageOnly001", + ]); + assert.equal(waybackYoutubeUrl("waybackVid1", "20200101000000"), "https://web.archive.org/web/20200101000000/https://www.youtube.com/watch?v=waybackVid1"); + assert.equal(waybackYoutubeUrl("waybackVid1"), "https://web.archive.org/web/https://www.youtube.com/watch?v=waybackVid1"); + } finally { + await wb.close(); + } +}); diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -86,6 +86,22 @@ export function parseCdxJson(body: string): WaybackCapture[] { return out; } +// What yt-dlp's YoutubeWebArchive extractor asks before it fetches anything +// (yt_dlp/extractor/archiveorg.py, `_real_extract`): the Wayback Machine's +// own index of the YouTube VIDEOS it holds. No formats there: "The requested +// video is not archived or indexed" — whatever captures of the watch page exist +// (YouTube serves "Video unavailable" with a 200, and most page captures hold +// no video). +export function waybackVideoInfoUrl(youtubeId: string): string { + return `${WAYBACK_ORIGIN}/__wb/videoinfo?${new URLSearchParams({ vtype: "youtube", vid: youtubeId }).toString()}`; +} + +// The replay URL yt-dlp's extractor takes for a YouTube video (its _VALID_URL: +// web.archive.org/web/<ts>/https://www.youtube.com/watch?v=<id>). +export function waybackYoutubeUrl(youtubeId: string, timestamp?: string): string { + return `${WAYBACK_ORIGIN}/web/${timestamp ?? ""}${timestamp ? "/" : ""}https://www.youtube.com/watch?v=${youtubeId}`; +} + export class WaybackClient { private readonly http: ArchiveOrgClient; @@ -98,6 +114,22 @@ export class WaybackClient { return this.http.requests; } + // Whether the Wayback Machine holds the YouTube VIDEO itself (formats in + // its videoinfo index — what yt-dlp asks), not only captures of its page. + async youtubeVideoArchived(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise<boolean> { + const body = await this.http.getText(waybackVideoInfoUrl(youtubeId), "application/json", o.signal); + let raw: unknown; + try { + raw = body.trim() ? JSON.parse(body) : {}; + } catch { + throw new ArchiveOrgRequestError(`the Wayback video index did not answer JSON for ${youtubeId}`, null, false); + } + const formats = (raw as { formats?: unknown } | null)?.formats; + if (Array.isArray(formats)) return formats.length > 0; + // A dmux answer keeps its formats by kind. + return !!formats && typeof formats === "object" && Object.values(formats as Record<string, unknown>).some((v) => Array.isArray(v) && v.length > 0); + } + // 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. diff --git a/common/publish/citedPostCaptures.ts b/common/publish/citedPostCaptures.ts @@ -79,6 +79,16 @@ export function citedCaptureSourceDir(channelsDir: string, channel: string, id: const isFile = async (p: string) => (await stat(p).catch(() => null))?.isFile() === true; +// Whether a cited post has its captured screenshot now (compose's check that +// a moment prepare called gone has not been captured since: release 29 E2). +export async function hasCapturedShot(channelsDir: string, channel: string, id: string): Promise<boolean> { + try { + return await isFile(path.join(citedCaptureSourceDir(channelsDir, channel, id), SHOT_FILENAME)); + } catch { + return false; + } +} + // Copy the cited posts' captures into `<destRoot>/posts/`, and remove every // capture there that is not cited. `channelsDir` is the corpus's // `channels/`. diff --git a/common/publish/composeReports.test.ts b/common/publish/composeReports.test.ts @@ -183,7 +183,7 @@ function seedSite(siteId: string, extra: Record<string, unknown> = {}, withRepor // What `archilyzer reports prepare` leaves: the manifest, the clips with // their sidecars, the cited capture. -function seedMedia(siteId: string, drop: string[] = []) { +function seedMedia(siteId: string, drop: string[] = [], extra: { warnings?: unknown[]; indexSiteId?: string } = {}) { const dir = reportMediaDir(paths, siteId); const clip = (hash: string, kind: "video" | "audio", span: { from: number; to: number }) => { const file = `${hash}${kind === "video" ? ".mp4" : ".m4a"}`; @@ -213,10 +213,11 @@ function seedMedia(siteId: string, drop: string[] = []) { writeJson(reportMediaIndexFile(paths, siteId), { format: REPORT_MEDIA_FORMAT, version: REPORT_MEDIA_VERSION, - siteId, + siteId: extra.indexSiteId ?? siteId, preparedAt: "2026-10-05T00:00:00.000Z", moments, problems: [], + ...(extra.warnings ? { warnings: extra.warnings } : {}), }); } @@ -512,16 +513,44 @@ 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 () => { +test("a gone source with no media is its words only ONLY on prepare's source-gone warning; compose never decides it alone", 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"); + const SPAN = `${VIDEOS}/abc123/10.00-20.00`; + const POST = `${SOCIAL}/3kabc`; + const warn = (moment: string, gone: string) => ({ kind: "source-gone", moment, citations: [], gone, message: "gone" }); + const refusedBoth = (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.map((p) => [p.kind, p.moment]), + [ + ["missing-media", SPAN], + ["missing-media", POST], + ], + ); + return true; + }; 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 { + // Gone on disk, but prepare said nothing (never ran, or failed it: unreachable, + // cut-failed, too-big are problems, not warnings): refused. + seedMedia("cited", [SPAN, POST]); + await assert.rejects(compose("cited"), refusedBoth); + // Another host's index warns: not this host's word. + seedMedia("cited", [SPAN, POST], { warnings: [warn(SPAN, "deleted"), warn(POST, "deleted")], indexSiteId: "full" }); + await assert.rejects(compose("cited"), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + const missing = e.problems.filter((p) => p.kind === "missing-media").map((p) => p.moment); + assert.ok(missing.includes(SPAN) && missing.includes(POST), JSON.stringify(missing)); + return true; + }); + + // Prepare's word: accepted, marked. + seedMedia("cited", [SPAN, POST], { warnings: [warn(SPAN, "deleted"), warn(POST, "deleted")] }); await compose("cited"); const span = readJson<Record<string, unknown>>(pub("m", VIDEOS, "abc123", "10.00-20.00", "moment.json")); assert.equal(span.sourceGone, "deleted"); @@ -537,21 +566,16 @@ test("a gone source with no prepared media is its words only, marked sourceGone; 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. + // Made private reads as gone too (the state is read now). 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"); + // Live again since prepare: its warning is stale — refused, prepare again. 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`], - ], - ); + refusedBoth(e); + assert.match((e as InstanceType<typeof ComposeReportsError>).problems[0].message, /not now — prepare again/); return true; }); } finally { diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -137,7 +137,8 @@ import { type ReportFeeds, type ReportPageView, } from "../lib/report/views"; -import { citedEvidenceSpan, isAudioOnlyPlatform, type EvidenceSpan } from "../lib/evidenceClip-server"; +import { citedEvidenceSpan, isAudioOnlyPlatform, resolveEvidenceSource, type EvidenceSpan } from "../lib/evidenceClip-server"; +import { hasCapturedShot } from "./citedPostCaptures"; import { citedMoments, loadHostReports, @@ -670,6 +671,23 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol 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>(); + // Whether a moment's media is on disk now: a span's window, saved container + // or audio (what prepare would cut from), a post's captured shot. + const momentMediaOnDisk = async (m: (typeof momentInfo extends Map<string, infer V> ? V : never)): Promise<boolean> => { + if (m.kind === "post") return hasCapturedShot(paths.channelsDir, m.moment.channel, m.moment.id); + if (m.moment.kind !== "span") return false; + const span = await citedEvidenceSpan(paths.channelsDir, m.moment.channel, m.moment.id, { start: m.moment.start, end: m.moment.end, pad: m.pad }); + const config = await configOf(m.moment.channel); + const source = await resolveEvidenceSource({ + channelsDir: paths.channelsDir, + slug: m.moment.channel, + id: m.moment.id, + span, + audio: m.kind === "audio" || isAudioOnlyPlatform(config?.platform), + ffprobeBin: paths.ffprobeBin, + }).catch(() => null); + return source !== null; + }; for (const key of Object.keys(citedIn)) { const m = momentInfo.get(key); if (!m || refusedChannel.has(m.moment.channel)) continue; @@ -678,19 +696,35 @@ 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 = + // A SOURCE GONE FROM ITS PLATFORM with no media (release 29 E2): accepted + // as a text-only moment, marked — but only on PREPARE's word: this host's + // index lists it as a `source-gone` warning, which prepare gives only after + // its reachability check and when it had no media to cut. Compose never + // decides it alone: no index, another host's, or a moment prepare failed + // for (unreachable, cut-failed, too-big) stays `missing-media`. And the + // word must still hold: the source still gone, and no media on disk since + // (a copy find-copy fetched after prepare) — else prepare again. + const warned = + media?.siteId === host.id + ? media.warnings?.find((w) => w.kind === "source-gone" && w.moment === key) + : undefined; + if (!warned) { + missing("missing-media", "no prepared media — run Prepare evidence media (archilyzer reports prepare)"); + continue; + } + const goneNow = 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); + if (!goneNow) { + missing("missing-media", "prepare found its source gone, and it is not now — prepare again"); + continue; + } + if (await momentMediaOnDisk(m)) { + missing("missing-media", "its media is on disk now (fetched or captured since prepare) — prepare again"); continue; } - missing("missing-media", "no prepared media — run Prepare evidence media (archilyzer reports prepare)"); + sourceGone.set(key, goneNow); continue; } const files = entry.kind === "post" ? [entry.file, ...entry.media.map((f) => f.file)] : [entry.file]; diff --git a/common/publish/findCopy.test.ts b/common/publish/findCopy.test.ts @@ -1,16 +1,21 @@ -// 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. +// find-copy (release 29 E2, and its review) over the fake Wayback and the fake +// archive.org on loopback, through the real polite clients: per gone YouTube +// recording, the Wayback Machine when it holds the VIDEO (yt-dlp's videoinfo +// check, not a page capture), else an archive.org mirror OF the upload (its +// identifier, a file name or its original URL names the id) whose file has the +// record's length; a copy that failed before is not picked again; a record +// whose page is not YouTube is not looked for; the fetch-windows items carry +// the copy's URL and the copy; a dry run and a cancelled run start 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 { startFakeArchiveOrg, type FakeArchiveOrgItem } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; import { ArchiveOrgClient } from "../lib/archiveOrgClient"; import { WaybackClient } from "../lib/waybackClient"; +import type { FailedCopy } from "../lib/copyAttempts-server"; import type { MissingEvidenceWindows, UnfetchableEvidenceWindow } from "./reportMedia"; import type { ReportHost } from "./reportHost"; import type { Paths } from "../lib/paths"; @@ -18,28 +23,34 @@ import type { FetchWindowsItem } from "../controller/fetchWindows"; import { findArchiveOrgMirrors, findCopies, + mirrorNamesId, pickMirrorFile, runFindCopy, youtubeIdOf, youtubeIdQuery, + type RecordFacts, } 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", - }, +const WB = "waybackVid1"; // its video in the Wayback Machine +const IA = "mirroredV01"; // a mirror on archive.org +const COMP = "compiledV01"; // only a compilation mentions it +const NONE = "nothing0001"; // no copy anywhere +const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`; + +const mirror = (id: string, seconds: string, extra: Partial<FakeArchiveOrgItem["metadata"]> = {}): FakeArchiveOrgItem => ({ + metadata: { identifier: `youtube-${id}`, title: `An upload ${id}`, mediatype: "movies", originalurl: watch(id), ...extra }, 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" }, + { name: `An upload-${id}.mkv`, source: "original", format: "Matroska", size: "4000", length: seconds }, + { name: `An upload-${id}.mp4`, source: "original", format: "MPEG4", size: "3000", length: seconds }, ], +}); +// A compilation that cites COMP in its description and holds one video: not a mirror of it. +const COMPILATION: FakeArchiveOrgItem = { + metadata: { identifier: "best-moments-2026", title: "Best moments", mediatype: "movies", description: `Clips from https://www.youtube.com/watch?v=${COMP} and others` }, + files: [{ name: "best-moments.mp4", source: "original", format: "MPEG4", size: "9000", length: "3600" }], }; +const ITEMS = [mirror(IA, "600.0"), mirror(WB, "300.0"), COMPILATION]; const gone = (id: string, from: number, clip: string): UnfetchableEvidenceWindow => ({ slug: CH, @@ -60,71 +71,92 @@ const NEED: MissingEvidenceWindows = { 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 }, + gone(WB, 0, "a#c1"), + gone(WB, 30, "a#c2"), + gone(IA, 5, "a#c3"), + gone(COMP, 5, "a#c4"), + gone(NONE, 5, "a#c5"), + gone("v5abcde", 5, "a#c6"), // a Rumble record + { ...gone("elsewhere001", 1, "a#c7"), 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 FACTS: Record<string, RecordFacts> = { + [WB]: { webpageUrl: watch(WB), duration: 300, videoDir: `/x/${WB}` }, + [IA]: { webpageUrl: watch(IA), duration: 598, videoDir: `/x/${IA}` }, + [COMP]: { webpageUrl: watch(COMP), duration: 3600, videoDir: `/x/${COMP}` }, + [NONE]: { webpageUrl: watch(NONE), duration: 100, videoDir: `/x/${NONE}` }, + v5abcde: { webpageUrl: "https://rumble.com/v5abcde-a-stream.html", duration: 100, videoDir: "/x/v5abcde" }, +}; + +async function fakes(o: { waybackBusy?: number; failed?: Record<string, FailedCopy[]>; need?: MissingEvidenceWindows } = {}) { + const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0, videos: [WB] }); + const ia = await startFakeArchiveOrg({ items: ITEMS }); 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), + missing: async () => o.need ?? NEED, + facts: async (_p: Paths, _slug: string, id: string) => FACTS[id]!, + failedCopies: async (dir: string) => o.failed?.[dir] ?? [], }; 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); +test("youtubeIdOf: a YouTube page's id only — never a Rumble or Twitch record's own id", () => { + assert.equal(youtubeIdOf("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), "dQw4w9WgXcQ"); + assert.equal(youtubeIdOf("https://youtu.be/dQw4w9WgXcQ?t=4"), "dQw4w9WgXcQ"); + assert.equal(youtubeIdOf("https://m.youtube.com/shorts/dQw4w9WgXcQ"), "dQw4w9WgXcQ"); + assert.equal(youtubeIdOf("https://rumble.com/v5abcde-a-stream.html"), null); + assert.equal(youtubeIdOf("https://www.twitch.tv/videos/12345678901"), null); + assert.equal(youtubeIdOf("https://video.example/watch?v=dQw4w9WgXcQ"), null); + assert.equal(youtubeIdOf(null), null); assert.match(youtubeIdQuery("dQw4w9WgXcQ"), /^identifier:\(youtube-dQw4w9WgXcQ\) OR originalurl:\(\*dQw4w9WgXcQ\*\)/); - assert.throws(() => youtubeIdQuery("no spaces allowed"), /not a YouTube id/); + assert.throws(() => youtubeIdQuery("not-eleven"), /not a YouTube id/); +}); + +test("a mirror is OF the upload by its identifier, a file name or its original URL — a description is not enough", () => { + assert.equal(mirrorNamesId(mirror(IA, "600"), IA), "its identifier"); + assert.equal(mirrorNamesId({ metadata: { identifier: "x" }, files: [{ name: `a-${IA}.mp4` }] }, IA), "a file's name"); + assert.equal(mirrorNamesId({ metadata: { identifier: "x", originalurl: watch(IA) } as never, files: [] }, IA), "its original URL"); + assert.equal(mirrorNamesId(COMPILATION, COMP), null); }); -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", +test("pickMirrorFile: a file naming the id, an original before a derivative, mp4 before webm; the record's length must agree", () => { + const f = (name: string, source: string, length?: string, original?: string) => ({ name, source, ...(length ? { length } : {}), ...(original ? { original } : {}) }); + assert.deepEqual(pickMirrorFile({ files: [f("x-ID123456789.webm", "original", "60"), f("x-ID123456789.mp4", "derivative")] }, "ID123456789"), { + file: "x-ID123456789.webm", source: "original", + seconds: 60, }); - 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); + assert.equal(pickMirrorFile({ files: [f("a.mp4", "original"), f("b.webm", "original")] }, "ID123456789"), null); + assert.equal(pickMirrorFile({ files: [f("only.mkv", "original", "100"), f("only.mp4", "derivative", undefined, "only.mkv")] }, "ID123456789")?.file, "only.mkv"); + // Within 5 s (or 2 %) of the record; a derivative takes its original's length. + assert.equal(pickMirrorFile({ files: [f("only.mkv", "original", "100")] }, "ID123456789", 104)?.file, "only.mkv"); + assert.equal(pickMirrorFile({ files: [f("only.mkv", "original", "100")] }, "ID123456789", 120), null, "another length: another video"); + assert.equal(pickMirrorFile({ files: [f("only.mkv", "original")] }, "ID123456789", 100), null, "a length that cannot be checked"); + assert.equal(pickMirrorFile({ files: [f("notes.txt", "original")] }, "ID123456789"), null); }); -test("archive-search by YouTube id: each mirror's direct file URL, an original preferred", async () => { +test("archive-search by YouTube id: the mirror's direct file URL; a compilation that mentions the id is rejected", 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, - }, + const r = await findArchiveOrgMirrors(IA, { client: deps.archive, duration: 598 }); + assert.deepEqual(r.mirrors.map((m) => [m.identifier, m.file, m.source, m.namedBy, m.seconds]), [ + [`youtube-${IA}`, `An upload-${IA}.mp4`, "original", "its identifier", 600], ]); - assert.deepEqual((await findArchiveOrgMirrors("nothing00001", { client: deps.archive })).mirrors, []); + assert.equal(r.mirrors[0]!.url, `https://archive.org/download/youtube-${IA}/An%20upload-${IA}.mp4`); + const comp = await findArchiveOrgMirrors(COMP, { client: deps.archive }); + assert.equal(comp.found, 1, "the search finds it"); + assert.deepEqual(comp.mirrors, []); + assert.match(comp.skipped[0]!.why, /mentions the id but is not of it/); } finally { await close(); } }); -test("find-copy: Wayback first, archive.org second, none → words only; one recording at a time", async () => { +test("find-copy: the Wayback video, else an archive.org mirror, else words only; a non-YouTube record is not looked for", async () => { const { wb, ia, deps, close } = await fakes(); try { const lines: string[] = []; @@ -132,43 +164,75 @@ test("find-copy: Wayback first, archive.org second, none → words only; one rec 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], + [WB, "fetch", "wayback", 2], + [IA, "fetch", "archive.org", 1], + [COMP, "text-only", null, 1], + [NONE, "text-only", null, 1], + ["v5abcde", "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: the URL yt-dlp's extractor takes; archive.org not asked once it had the video. + assert.equal(r.recordings[0]!.copy!.url, `https://web.archive.org/web/${watch(WB)}`); + assert.deepEqual(r.recordings[0]!.tried.map((t) => [t.from, t.found]), [["wayback", true]]); + // A page captured with no video is not a copy: IA's page has none, the video index says no. + assert.deepEqual(r.recordings[1]!.tried.map((t) => [t.from, t.found]), [ ["wayback", false], - ["archive.org", false], + ["archive.org", true], ]); - 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); + assert.equal(r.recordings[1]!.copy!.url, `https://archive.org/download/youtube-${IA}/An%20upload-${IA}.mp4`); + // The Rumble record: no request at all. + assert.match(r.recordings[4]!.tried[0]!.detail ?? "", /not a YouTube recording/); + const vids = wb.requests.filter((q) => q.path.startsWith("/__wb/videoinfo")).map((q) => new URL(q.path, "http://x").searchParams.get("vid")); + assert.deepEqual(vids, [WB, IA, COMP, NONE]); + assert.ok(!ia.requests.some((q) => q.includes(WB)), "no archive.org search for the one Wayback had"); + assert.ok(!ia.requests.some((q) => q.includes("v5abcde"))); - // 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"], + [WB, 0, 10, "a#c1", true, "wayback"], + [WB, 30, 40, "a#c2", true, "wayback"], + [IA, 5, 15, "a#c3", true, "archive.org"], ], ); - assert.ok(lines.some((l) => l.includes("nothing00001") && l.includes("its words only"))); + assert.ok(lines.some((l) => l.includes(COMP) && 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 () => { +test("a copy that failed before is not picked again: Wayback falls through to archive.org, a failed mirror to none", async () => { + // WB also has a mirror (ITEMS: youtube-WB, 300 s). + const failedWayback: FailedCopy = { from: "wayback", url: `https://web.archive.org/web/${watch(WB)}`, at: "2026-10-15T00:00:00Z", error: "HTTP 404" }; + const one = await fakes({ failed: { [`/x/${WB}`]: [failedWayback] }, need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 2) } }); + try { + const r = await findCopies(opts(one.deps)); + assert.equal(r.recordings[0]!.copy?.from, "archive.org"); + assert.deepEqual(r.recordings[0]!.tried.map((t) => [t.from, t.found]), [ + ["wayback", false], + ["archive.org", true], + ]); + assert.match(r.recordings[0]!.tried[0]!.detail ?? "", /failed before/); + assert.equal(one.wb.requests.length, 0, "the Wayback is not asked again"); + } finally { + await one.close(); + } + const mirrorUrl = `https://archive.org/download/youtube-${WB}/An%20upload-${WB}.mp4`; + const both = await fakes({ + failed: { [`/x/${WB}`]: [failedWayback, { from: "archive.org", url: mirrorUrl, at: "2026-10-15T01:00:00Z", error: "403" }] }, + need: { ...NEED, unfetchable: NEED.unfetchable.slice(0, 1) }, + }); + try { + const r = await findCopies(opts(both.deps)); + assert.equal(r.recordings[0]!.outcome, "text-only"); + assert.match(r.recordings[0]!.tried[1]!.detail ?? "", /1 mirror\(s\) failed before/); + assert.deepEqual(r.items, []); + } finally { + await both.close(); + } +}); + +test("runFindCopy: the found windows go to ONE fetch-windows call; a dry run, a cancelled run and a run that finds nothing start none", async () => { const { deps, close } = await fakes(); try { const calls: FetchWindowsItem[][] = []; @@ -183,8 +247,13 @@ test("runFindCopy: the found windows go to ONE fetch-windows call; a dry run and assert.equal(calls.length, 1); assert.equal(calls[0]!.length, 3); assert.deepEqual(run.fetch, { jobId: "J1" }); + const ctl = new AbortController(); + ctl.abort(); + const cancelled = await runFindCopy({ ...opts(deps), signal: ctl.signal, startFetch: start }); + assert.equal(calls.length, 1, "cancelled: no fetch"); + assert.match(cancelled.stopped ?? "", /cancelled/); const none = await runFindCopy({ - ...opts({ ...deps, missing: async () => ({ ...NEED, unfetchable: [NEED.unfetchable[3]] }) }), + ...opts({ ...deps, missing: async () => ({ ...NEED, unfetchable: [NEED.unfetchable[4]] }) }), startFetch: start, }); assert.equal(calls.length, 1); diff --git a/common/publish/findCopy.ts b/common/publish/findCopy.ts @@ -1,30 +1,45 @@ // 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 +// A report cites a moment of a YouTube 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>`. +// 1. THE WAYBACK MACHINE, when it holds the VIDEO — not merely a capture of +// the watch page (YouTube answers "Video unavailable" with a 200, and most +// page captures hold no video). The check is the one yt-dlp's +// YoutubeWebArchive extractor makes before it fetches anything +// (yt_dlp/extractor/archiveorg.py `_real_extract`: web.archive.org's +// `__wb/videoinfo?vtype=youtube&vid=<id>` has formats); the copy's URL is +// `https://web.archive.org/web/<ts>/https://www.youtube.com/watch?v=<id>`, +// the form that extractor takes (the newest 200 capture's timestamp, when +// the CDX names one); +// 2. ARCHIVE.ORG: a mirror that is OF the upload — its identifier, a file's +// name, or its `originalurl`/`source` names the YouTube id (a title or a +// description that mentions it is not enough: a compilation does that) — +// holding a video file whose length agrees with the record's duration; +// fetched by its direct URL `https://archive.org/download/<identifier>/<file>`. +// +// Only a record whose page is a YouTube URL is looked for: the id is the +// page's, never guessed from a Twitch or Rumble record's own id. +// +// A COPY THAT FAILED is not picked again: fetch-windows records a copy whose +// fetch failed beside the recording (lib/copyAttempts-server.ts), and the next +// run falls through — Wayback → archive.org → the next mirror. // // 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". +// marked "source deleted" (once prepare says so). // // 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. +// left for a later run. A cancelled run starts no fetch. 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"; @@ -32,11 +47,12 @@ 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 { readFailedCopies, type FailedCopy } from "../lib/copyAttempts-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 { isArchiveOrgVideoFileName, parseArchiveOrgLength, type ArchiveOrgItemMetadata } from "../lib/archiveOrg"; +import { waybackClient, waybackYoutubeUrl, type WaybackCapture } from "../lib/waybackClient"; import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { channelConfigPlatform } from "../lib/videoId"; import { readChannelConfig } from "../controller/channels"; @@ -45,80 +61,141 @@ import { missingEvidenceWindows, type EvidenceWindow, type MissingEvidenceWindow import type { ReportHost } from "./reportHost"; import type { FetchWindowsItem } from "../controller/fetchWindows"; -// ─── A recording's page and its YouTube id ─── +// ─── A recording: its page, its length, 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> { +export type RecordFacts = { + // The page it was served at: its metadata's `webpage_url`, else the one its + // availability check recorded, else the playlist's. + webpageUrl: string | null; + // Its length in seconds, from its metadata. + duration: number | null; + // Its data directory (where the failed copies are recorded). + videoDir: string; +}; + +export async function recordFacts(paths: Paths, slug: string, id: string): Promise<RecordFacts> { 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); + const videoDir = path.join(paths.channelsDir, slug, "data", dirId); + let webpageUrl: string | null = null; + let duration: number | null = null; 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; + const meta = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as { webpage_url?: unknown; duration?: unknown }; + if (typeof meta.webpage_url === "string" && /^https?:\/\//.test(meta.webpage_url)) webpageUrl = meta.webpage_url; + if (typeof meta.duration === "number" && Number.isFinite(meta.duration) && meta.duration > 0) duration = meta.duration; } 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; + if (!webpageUrl) { + const av = await loadAvailability(videoDir).catch(() => null); + if (av?.webpageUrl && /^https?:\/\//.test(av.webpageUrl)) webpageUrl = av.webpageUrl; + } + if (!webpageUrl && config) webpageUrl = await findVideoSourceUrl(paths, slug, dirId, config).catch(() => null); + return { webpageUrl, duration, videoDir }; } -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 - } +// The page alone (wayback-lookup's `{slug, id}`). +export async function recordWebpageUrl(paths: Paths, slug: string, id: string): Promise<string | null> { + return (await recordFacts(paths, slug, id)).webpageUrl; +} + +const YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/; +const YOUTUBE_HOST = /^(?:(?:www|m|music)\.)?youtube\.com$|^youtu\.be$/; + +// The YouTube id of a YouTube page (a watch URL's `v`, a youtu.be path, a +// /shorts/, /live/ or /embed/ path), or null — for any other page, whatever +// the record's own id looks like. +export function youtubeIdOf(pageUrl: string | null): string | null { + if (!pageUrl) return null; + let u: URL; + try { + u = new URL(pageUrl); + } catch { + return null; } - return YOUTUBE_ID.test(recordId) ? recordId : null; + const host = u.hostname.toLowerCase(); + if (!YOUTUBE_HOST.test(host)) return null; + const v = u.searchParams.get("v"); + if (v && YOUTUBE_ID.test(v)) return v; + const seg = u.pathname.split("/").filter(Boolean); + if (host === "youtu.be") return seg[0] && YOUTUBE_ID.test(seg[0]) ? seg[0] : null; + const k = seg.findIndex((s) => s === "shorts" || s === "live" || s === "embed"); + return k >= 0 && seg[k + 1] && YOUTUBE_ID.test(seg[k + 1]) ? seg[k + 1] : null; +} + +export function isYoutubeId(id: string): boolean { + return YOUTUBE_ID.test(id); } // ─── 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. +// archive.org's advanced search for CANDIDATE mirrors of one YouTube upload +// (each is then checked: findArchiveOrgMirrors). 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}")`; + return `identifier:(youtube-${id}) OR originalurl:(*${id}*) OR source:(*${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(); +const textOf = (v: unknown): string => + typeof v === "string" ? v : Array.isArray(v) ? v.filter((x) => typeof x === "string").join(" ") : ""; + +// Whether an item is OF the upload: its identifier, a file's name, or its +// `originalurl`/`source` names the id. A title or description that mentions +// it is not (a compilation or a reaction cites its sources there). +export function mirrorNamesId(item: Pick<ArchiveOrgItemMetadata, "metadata" | "files">, youtubeId: string): string | null { + const meta = item.metadata as Record<string, unknown>; + if (item.metadata.identifier.includes(youtubeId)) return "its identifier"; + if (item.files.some((f) => f.name.includes(youtubeId))) return "a file's name"; + if (textOf(meta.originalurl).includes(youtubeId)) return "its original URL"; + if (textOf(meta.source).includes(youtubeId)) return "its source"; + return null; +} + +// How far a mirror's file may run from the record's duration: 5 s, or 2 %. +export function mirrorLengthTolerance(seconds: number): number { + return Math.max(5, seconds * 0.02); +} // 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). +// an ORIGINAL before a derivative, then mp4, webm, mkv, … — and, when the +// record's duration is known, only a file whose length agrees with it (a +// derivative's length is its original's when it has none). Null when the item +// holds none that qualifies, 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 { + duration: number | null = null, +): { file: string; source: "original" | "derivative"; size?: number; seconds?: 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 : []; + let pool = named.length > 0 ? named : originals.length === 1 ? videos : []; + const lengthOf = (f: (typeof videos)[number]): number | undefined => + parseArchiveOrgLength(f.length) ?? parseArchiveOrgLength(item.files.find((o) => o.name === f.original)?.length); + if (duration !== null) { + pool = pool.filter((f) => { + const s = lengthOf(f); + return s !== undefined && Math.abs(s - duration) <= mirrorLengthTolerance(duration); + }); + } 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 } : {}) }; + const seconds = lengthOf(best); + return { + file: best.name, + source: best.source === "original" ? "original" : "derivative", + ...(size !== undefined ? { size } : {}), + ...(seconds !== undefined ? { seconds } : {}), + }; } export type ArchiveOrgMirror = { @@ -129,6 +206,9 @@ export type ArchiveOrgMirror = { url: string; source: "original" | "derivative"; size?: number; + seconds?: number; + // How the item names the upload. + namedBy: string; }; export type ArchiveOrgMirrorSearch = { @@ -140,39 +220,45 @@ export type ArchiveOrgMirrorSearch = { 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. +// item that is not OF the upload (mirrorNamesId), is restricted, or holds no +// video file of it (of the record's length, when `duration` is given) is +// skipped, with why. export async function findArchiveOrgMirrors( youtubeId: string, - o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number } = {}, + o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number; duration?: number | null } = {}, ): 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 }[] = []; + const duration = o.duration ?? null; for (const hit of hits.items) { + o.signal?.throwIfAborted(); 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" }); + const namedBy = mirrorNamesId(item, youtubeId); + if (!namedBy) { + skipped.push({ identifier: hit.identifier, why: "it mentions the id but is not of it (no identifier, file name or original URL names it)" }); continue; } if (archiveOrgRestriction(item).item) { skipped.push({ identifier: hit.identifier, why: "archive.org restricts it" }); continue; } - const pick = pickMirrorFile(item, youtubeId); + const pick = pickMirrorFile(item, youtubeId, duration); if (!pick) { - skipped.push({ identifier: hit.identifier, why: "no video file of the upload can be told in it" }); + skipped.push({ + identifier: hit.identifier, + why: + duration !== null + ? `no video file of the upload with its length (${Math.round(duration)} s) can be told in it` + : "no video file of the upload can be told in it", + }); continue; } + const meta = item.metadata as Record<string, unknown>; const title = textOf(meta.title) || hit.title; mirrors.push({ identifier: item.metadata.identifier, @@ -181,6 +267,8 @@ export async function findArchiveOrgMirrors( url: archiveOrgDownloadUrl(item.metadata.identifier, pick.file), source: pick.source, ...(pick.size !== undefined ? { size: pick.size } : {}), + ...(pick.seconds !== undefined ? { seconds: pick.seconds } : {}), + namedBy, }); } // Originals first, then the search's order. @@ -196,7 +284,7 @@ export type WaybackLookup = { url: string; captures: WaybackCapture[] }; // 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 } = {}, + o: { client?: Pick<typeof waybackClient, "captures">; okOnly?: boolean; limit?: number; signal?: AbortSignal } = {}, ): Promise<WaybackLookup> { const client = o.client ?? waybackClient; const captures = await client.captures(url, { @@ -226,6 +314,8 @@ export type FindCopyRecording = { youtubeId: string | null; // The cited windows of the recording. windows: EvidenceWindow[]; + // Copies an earlier fetch failed from (not picked again). + failedBefore: ClipCopy[]; tried: FindCopyAttempt[]; copy?: ClipCopy; // fetch a copy found: its windows go to fetch-windows @@ -245,19 +335,24 @@ export type FindCopyResult = { }; export type FindCopyDeps = { - wayback: { captures: typeof waybackClient.captures }; + wayback: Pick<typeof waybackClient, "captures" | "youtubeVideoArchived">; archive: ArchiveOrgClient; missing: (paths: Paths, host: ReportHost) => Promise<MissingEvidenceWindows>; - webpageUrl: (paths: Paths, slug: string, id: string) => Promise<string | null>; + facts: (paths: Paths, slug: string, id: string) => Promise<RecordFacts>; + failedCopies: (videoDir: string) => Promise<FailedCopy[]>; }; const DEFAULT_DEPS: FindCopyDeps = { wayback: waybackClient, archive: archiveOrgClient, missing: (paths, host) => missingEvidenceWindows(paths, host), - webpageUrl: recordWebpageUrl, + facts: recordFacts, + failedCopies: readFailedCopies, }; +const describeAttempt = (t: FindCopyAttempt) => + `${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`; + // 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). @@ -270,6 +365,8 @@ export async function findCopies(opts: { }): Promise<FindCopyResult> { const deps: FindCopyDeps = { ...DEFAULT_DEPS, ...opts.deps }; const log = (line: string) => opts.onLog?.(line); + const signal = opts.signal; + const sig = signal ? { signal } : {}; 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) { @@ -283,61 +380,79 @@ export async function findCopies(opts: { 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" }; + if (signal?.aborted) break; + const facts = await deps.facts(opts.paths, r.slug, r.id); + const youtubeId = youtubeIdOf(facts.webpageUrl); + const failedBefore = (await deps.failedCopies(facts.videoDir).catch(() => [] as FailedCopy[])).map(({ from, url }) => ({ from, url })); + const failedUrls = new Set(failedBefore.map((f) => f.url)); + const rec: FindCopyRecording = { ...r, watchUrl: facts.webpageUrl, youtubeId, failedBefore, tried: [], outcome: "text-only" }; result.recordings.push(rec); let refused: string | undefined; + const lookupFailed = (from: ClipCopy["from"], e: unknown) => { + if (signal?.aborted) return; + rec.tried.push({ from, found: false, error: (e as Error).message }); + if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message; + }; - // 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" }); + if (!youtubeId) { + rec.tried.push({ from: "wayback", found: false, detail: "not a YouTube recording: no copy is looked for" }); + } else { + // 1. The Wayback Machine — when it holds the video, and no fetch from it failed before. + if (failedBefore.some((f) => f.from === "wayback")) { + rec.tried.push({ from: "wayback", found: false, detail: "a fetch from its Wayback copy failed before" }); + } else { + try { + if (await deps.wayback.youtubeVideoArchived(youtubeId, sig)) { + // The newest capture of the page that recorded a 200 dates the copy. + const { captures } = await waybackLookup(`https://www.youtube.com/watch?v=${youtubeId}`, { + client: deps.wayback, + okOnly: true, + ...sig, + }); + const newest = captures.filter((c) => c.status === "200").at(-1); + const url = waybackYoutubeUrl(youtubeId, newest?.timestamp); + rec.copy = { from: "wayback", url }; + rec.tried.push({ from: "wayback", found: true, url, detail: `the video is archived${newest ? `; its page captured ${newest.timestamp}` : ""}` }); + } else { + rec.tried.push({ from: "wayback", found: false, detail: "the video is not archived (its page may be)" }); + } + } catch (e) { + lookupFailed("wayback", e); } - } 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) { + // 2. archive.org: a mirror OF the upload, of its length, not failed before. + if (!rec.copy && !refused && !signal?.aborted) { try { - const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, ...(opts.signal ? { signal: opts.signal } : {}) }); - const m = found.mirrors[0]; + const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, duration: facts.duration, ...sig }); + const m = found.mirrors.find((x) => !failedUrls.has(x.url)); 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})` }); + rec.tried.push({ + from: "archive.org", + found: true, + url: m.url, + detail: `${m.identifier}: ${m.file} (${m.source}; ${m.namedBy} names the id${m.seconds !== undefined ? `; ${Math.round(m.seconds)} s` : ""})`, + }); } else { + const failed = found.mirrors.length; 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", + detail: [ + found.found ? `${found.found} item(s), none a usable mirror` : "no item names the id", + ...(failed ? [`${failed} mirror(s) failed before`] : []), + ...found.skipped.map((s) => `${s.identifier}: ${s.why}`), + ].join("; "), }); } } 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; + lookupFailed("archive.org", e); } - } else { - rec.tried.push({ from: "archive.org", found: false, detail: "no YouTube id to search for" }); } } + if (signal?.aborted) break; if (rec.copy) { rec.outcome = "fetch"; for (const w of r.windows) { @@ -357,8 +472,8 @@ export async function findCopies(opts: { } 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"}`, + rec.tried.map(describeAttempt).join("; ") + + ` → ${rec.outcome === "fetch" ? `fetch from the ${rec.copy!.from === "wayback" ? "Wayback copy" : "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`; @@ -366,12 +481,19 @@ export async function findCopies(opts: { break; } } + if (signal?.aborted) { + result.stopped = "cancelled; the rest are left for a later run"; + log(`find-copy: ${result.stopped}.`); + } 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. +// The line a find-copy job's log ends with, then its result as JSON. +export const FIND_COPY_RESULT_MARKER = "@@find-copy "; + +// find-copy, whole: the lookups, then (unless `dryRun`, or the run was +// cancelled) 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; @@ -382,6 +504,6 @@ export async function runFindCopy<T>(opts: { startFetch: (items: FetchWindowsItem[]) => Promise<T>; }): Promise<FindCopyResult & { fetch?: T }> { const found = await findCopies(opts); - if (opts.dryRun || found.items.length === 0) return found; + if (opts.dryRun || opts.signal?.aborted || 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 @@ -150,6 +150,27 @@ test("a cited-only channel (citedChannels) is citable: its window is one to fetc ); }); +// Release 29 review: members-only is not gone. With no cookies to send it is +// "unfetchable: members-only"; with a cookie source it is a window to fetch. +test("a members-only video: unfetchable with no cookies, a window to fetch with a cookie source — never gone", async () => { + const SITE2 = "demo-members"; + writeJson(path.join(videoDir(CH, "member1"), "availability.json"), { checkedAt: "2026-10-01T00:00:00.000Z", availability: "members_only" }); + writeJson(path.join(paths.sitesDir, SITE2, "site.json"), { title: "Members", channels: [{ slug: CH }], reports: ["r4"] }); + writeJson( + path.join(paths.sitesDir, SITE2, "reports", "r4", "report.json"), + report("r4", { m01: { kind: "video", channel: CH, id: "member1", start: 5, end: 6, quote: "members only" } }), + ); + const none = await missingEvidenceWindows(paths, SITE2, { settings: {} }); + assert.deepEqual(none.unfetchable.map((u) => [u.id, u.why, u.gone]), [["member1", "members-only", undefined]]); + assert.deepEqual(none.missing, []); + const withCookies = await missingEvidenceWindows(paths, SITE2, { settings: { cookiesFromBrowser: "firefox" } }); + assert.deepEqual(withCookies.unfetchable, []); + assert.deepEqual(withCookies.missing.map((m) => m.id), ["member1"]); + // A deferred cookie mode sends none: still unfetchable. + const deferred = await missingEvidenceWindows(paths, SITE2, { settings: { cookiesFromBrowser: "firefox", cookieMode: "defer" } }); + assert.deepEqual(deferred.unfetchable.map((u) => u.why), ["members-only"]); +}); + test("a site that does not exist is an error", async () => { await assert.rejects(missingEvidenceWindows(paths, "no-such-site"), /no site "no-such-site"/); }); diff --git a/common/publish/reportMedia.test.ts b/common/publish/reportMedia.test.ts @@ -303,10 +303,10 @@ test("a gone recording or a deleted, never-captured post with no media is a warn 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]), + (index.warnings ?? []).map((w) => [w.kind, w.moment, w.citations, w.gone]), [ - ["source-gone", `${CH}/gone2/1.00-2.00`, ["g1#g01"]], - ["source-gone", `${X}/333`, ["g1#g02"]], + ["source-gone", `${CH}/gone2/1.00-2.00`, ["g1#g01"], "deleted"], + ["source-gone", `${X}/333`, ["g1#g02"], "deleted"], ], ); assert.match(index.warnings![0].message, /deleted.*words only.*Source deleted/); diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts @@ -68,6 +68,8 @@ import { isReportId, type Report } from "../lib/report/schema"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { SOURCE_GONE_LABELS, type GoneState } from "../lib/sourceGone"; import { postGoneState, sourceGoneState } from "../lib/sourceGone-server"; +import { resolveEffectiveAvailability } from "../lib/availability-server"; +import { authRetryCookies, resolveCookiePolicy, type CookiePolicyInputs } from "../lib/cookiePolicy"; import { MAX_CLIP_WINDOW_SECONDS } from "../lib/clipWindow"; import { citedEvidenceSpan, @@ -174,6 +176,8 @@ export type ReportMediaProblem = { moment?: string; // A JSON path in the report (an invalid report's problems). path?: string; + // A `source-gone` warning: what the source said when prepare looked. + gone?: GoneState; }; export type ReportMediaIndex = { @@ -300,8 +304,8 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi 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 }); + const warnGone = (m: CitedMoment, gone: GoneState, message: string) => { + warnings.push({ kind: "source-gone", moment: m.key, citations: m.citedBy, gone, message }); log(` ! ${m.key}: ${message}`); }; @@ -353,7 +357,7 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi } 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)`); + warnGone(m, gone, `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`); @@ -378,7 +382,7 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi const m = postMoment.get(`${miss.channel}/${miss.id}`); 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}"`); + warnGone(m, "deleted", `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); @@ -470,6 +474,9 @@ export async function readStoreMediaIndex(store: Pick<ReportStore, "stagingDir"> // 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 +// members-only the source says members-only, and the channel has no +// cookies to fetch it with (with a cookie source it is a +// window to fetch: the auth retry sends them). Never gone // 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 @@ -491,7 +498,7 @@ export type EvidenceWindow = { reason?: string; }; -export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "audio-only" | "too-long"; +export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "members-only" | "audio-only" | "too-long"; export type UnfetchableEvidenceWindow = EvidenceWindow & { why: UnfetchableReason; @@ -515,7 +522,12 @@ export type MissingEvidenceWindows = { const floor2 = (n: number) => Math.floor(n * 100 + 1e-6) / 100; const ceil2 = (n: number) => Math.ceil(n * 100 - 1e-6) / 100; -export async function missingEvidenceWindows(paths: Paths, siteOrHost: string | ReportHost): Promise<MissingEvidenceWindows> { +export async function missingEvidenceWindows( + paths: Paths, + siteOrHost: string | ReportHost, + o: { settings?: CookiePolicyInputs } = {}, +): Promise<MissingEvidenceWindows> { + const settings = o.settings ?? getSettings(); const host = typeof siteOrHost === "string" ? siteHostFor(paths, siteOrHost) : siteOrHost; const { reports, problems } = await loadHostReports(host); const quotes = new Map<string, string>(); @@ -574,11 +586,24 @@ export async function missingEvidenceWindows(paths: Paths, siteOrHost: string | unfetchable("unreachable", `the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`); continue; } - const gone = await sourceGoneState(await resolveVideoDir(paths.channelsDir, slug, id)); + const videoDir = await resolveVideoDir(paths.channelsDir, slug, id); + const gone = await sourceGoneState(videoDir); if (gone) { out.unfetchable.push({ ...window, why: "gone", gone, message: `the source says the video is ${gone}` }); continue; } + // MEMBERS-ONLY is not gone: a member's cookies fetch it (the auth retry). + // With none to send, no fetch can fill it. + if ( + (await resolveEffectiveAvailability(videoDir).catch(() => null)) === "members_only" && + !authRetryCookies(resolveCookiePolicy(settings, config)) + ) { + unfetchable( + "members-only", + "the source says the video is members-only, and this channel has no cookies to fetch it with (a cookie source on the channel or in Settings)", + ); + continue; + } if (audioOnly) { unfetchable("audio-only", "a feed record's media is its audio download, not a window"); continue; diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts @@ -495,8 +495,16 @@ function handleFromUrl(url: string): string | null { // Bluesky can afford to check an entire channel routinely. const GET_POSTS_BATCH = 25; -blueskyFetcher.checkAvailability = async ({ ids, handle, signal, onLog }) => { +blueskyFetcher.checkAvailability = async ({ ids: asked, handle, authors, signal, onLog }) => { const out = new Map<string, PostAvailability>(); + // A repost is archived under the original's author and rkey: looked up + // under this account it would be absent and read as deleted. Such posts + // are left as they were (release 29 review). + const own = (a: string | undefined) => !a || a.replace(/^@/, "").toLowerCase() === handle.replace(/^@/, "").toLowerCase(); + const ids = asked.filter((id) => own(authors?.get(id))); + if (ids.length < asked.length) { + onLog?.(`${asked.length - ids.length} post(s) by another account (reposts) left as they were.`); + } if (ids.length === 0) return out; // The AT-URI needs the account's DID, not its handle. diff --git a/common/social/blueskyPostCapture.test.ts b/common/social/blueskyPostCapture.test.ts @@ -11,7 +11,7 @@ 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 { ACCOUNTS, PNG as FAKE_PNG, startFakeBluesky } from "../testing/social/fakeBluesky.mjs"; import { blueskyEndpoints, onBlueskyEndpoints, BLUESKY_ENDPOINTS } from "./blueskyEndpoints"; import { blueskyPageGapMs, @@ -67,16 +67,20 @@ async function setup(opts: { busyTimes?: number } = {}) { }, pageGapMs: () => 3_500, imageGapMs: () => 1_200, + apiGapMs: () => 800, pause: async (ms) => { pauses.push(ms); }, now: () => new Date("2026-10-15T12:00:00.000Z"), }; + // What capturePosts hands over for a Bluesky channel: each id's archived author. + const archived = (ids: string[], author = HANDLE) => new Map(ids.map((id) => [id, { text: "", author }])); const input = (ids: string[], extra: Partial<PostCaptureInput> = {}): PostCaptureInput => ({ ids, handle: HANDLE, outDir, signal: new AbortController().signal, + archived: archived(ids), ...extra, }); return { @@ -181,7 +185,7 @@ test("a capture: the image post (shot, 2 images, record), the text post, the del `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"); + assert.deepEqual(s.pauses, [800, 1_200, 3_500], "the AppView gap (handle → getPosts), 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); @@ -212,6 +216,7 @@ test("a 429 from the AppView is waited out (its Retry-After) and asked again", a 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.pauses[1], 800, "then the gap before getPosts"); assert.equal(s.bsky.requests.filter((r) => r.includes("resolveHandle")).length, 2); } finally { await s.close(); @@ -223,7 +228,7 @@ test("a 429 that persists stops the run with nothing recorded about the posts", 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.match(res.stoppedEarly ?? "", /429/); assert.equal(s.pauses.length, 2, "two waits between three attempts"); } finally { await s.close(); @@ -238,7 +243,7 @@ test("a cancelled run stops between posts; the rest are left", async () => { ...s.deps, pause: async (ms) => { s.pauses.push(ms); - ctl.abort(); + if (ms === 3_500) ctl.abort(); // during the gap before the second page }, }; const res = await captureBlueskyPosts(s.input([TEXT_POST, IMAGE_POST], { signal: ctl.signal, media: false }), deps); @@ -267,6 +272,79 @@ test("a page that does not show the post is an error; the AppView's liveness sta } }); +test("a repost is looked up under its original author, never read as deleted under the channel's account", async () => { + const FAN = { handle: "synthfan.bsky.social", did: "did:plc:synthfan00000000000000000", displayName: "Synth Fan" }; + const bsky = await startFakeBluesky({ accounts: [...ACCOUNTS, FAN] }); + const s = await setup(); + try { + const deps: BlueskyCaptureDeps = { ...s.deps, fetch: (url, init) => bsky.fetch(url, init) }; + // The fan's channel archived the baker's post (a repost): its rkey, its author. + const res = await captureBlueskyPosts( + { ...s.input([TEXT_POST], { media: false }), handle: FAN.handle, archived: new Map([[TEXT_POST, { text: "", author: HANDLE }]]) }, + deps, + ); + assert.deepEqual(res.outcomes.map((o) => [o.state, o.availability]), [["captured", "available"]]); + assert.ok(bsky.requests.some((r) => r.includes(encodeURIComponent(`at://${ACCOUNTS[0].did}/app.bsky.feed.post/${TEXT_POST}`)))); + assert.ok(!bsky.requests.some((r) => r.includes(encodeURIComponent(FAN.did))), "never asked under the channel's DID"); + // An author the archive does not name: nothing learned, never `deleted`. + const unknown = await captureBlueskyPosts( + { ...s.input([DELETED_POST], { media: false, force: true }), archived: new Map() }, + deps, + ); + assert.deepEqual(unknown.outcomes.map((o) => [o.state, o.availability]), [["error", undefined]]); + + // The deleted-post sweep leaves a repost as it was rather than read its + // absence under the channel's account as a deletion. + const before = bsky.requests.length; + const swept = await blueskyFetcher.checkAvailability!({ + ids: [TEXT_POST], + handle: FAN.handle, + authors: new Map([[TEXT_POST, HANDLE]]), + signal: new AbortController().signal, + }); + assert.equal(swept.size, 0); + assert.equal(bsky.requests.length, before, "nothing asked"); + } finally { + await bsky.close(); + await s.close(); + } +}); + +test("the post on a self-thread page: its own link, else its whole text; ambiguous is an error, never the wrong shot", 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 dir = await mkdtemp(path.join(os.tmpdir(), "bsky-thread-")); + const item = (text: string, link?: string) => + `<div data-testid="postThreadItem-by-${HANDLE}" style="padding:10px;border:1px solid #ccc;width:500px"><p>${text}</p>${link ? `<a href="${link}">2h</a>` : ""}</div>`; + const page = (body: string) => `data:text/html,${encodeURIComponent(`<!doctype html><body>${body}</body>`)}`; + const shoot = (html: string, text: string, rkey = "3lreply") => + shootBlueskyPost(opened!.page, { url: page(html), canonicalUrl: "x", handle: HANDLE, rkey, text, dir, signal: new AbortController().signal, postTimeoutMs: 2_000 }); + const marked = () => opened!.page.evaluate(`document.querySelector("[data-archilyzer-capture] p").innerText`); + try { + // A short reply under parents that contain its words: the exact text wins. + const thread = item("lol that is so true, lol", "https://bsky.app/profile/x/post/3lparent1") + item("lol") + item("lol no", "https://bsky.app/profile/x/post/3lchild"); + assert.equal((await shoot(thread, "lol")).state, "captured"); + assert.equal(await marked(), "lol"); + // An item linking to the post's own permalink wins over text. + const linked = item("same words") + item("same words", `https://bsky.app/profile/${HANDLE}/post/3lreply`); + assert.equal((await shoot(linked, "same words")).state, "captured"); + assert.equal(await opened.page.evaluate(`!!document.querySelector("[data-archilyzer-capture] a")`), true); + // Two items with the post's whole text and no link: ambiguous, no shot. + const twins = item("lol") + item("lol"); + const r = await shoot(twins, "lol", "3lother"); + assert.equal(r.state, "error"); + assert.match(r.error ?? "", /match this one; none shot/); + } finally { + await opened.close(); + await rm(dir, { recursive: true, force: true }); + } +}); + // ─── 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) => { @@ -284,6 +362,7 @@ test("a real headless Chromium shoots the post, cropped to it, over the fake pag url: bsky.pageUrl(HANDLE, IMAGE_POST), canonicalUrl: `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`, handle: HANDLE, + rkey: IMAGE_POST, text: "The second shop opens in the spring. Small place, big oven.", dir, signal: new AbortController().signal, @@ -299,6 +378,7 @@ test("a real headless Chromium shoots the post, cropped to it, over the fake pag url: bsky.pageUrl(HANDLE, DELETED_POST), canonicalUrl: "x", handle: HANDLE, + rkey: DELETED_POST, text: "", dir: path.join(dir, "gone"), signal: new AbortController().signal, diff --git a/common/social/blueskyPostCapture.ts b/common/social/blueskyPostCapture.ts @@ -100,8 +100,10 @@ export type BlueskyCaptureDeps = { // 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. + // The gap before each page after the first, before each AppView request + // after the first (a handle's DID, a getPosts batch), and between two images. pageGapMs: () => number; + apiGapMs: () => number; imageGapMs: () => number; pause: (ms: number, signal: AbortSignal) => Promise<void>; now?: () => Date; @@ -161,6 +163,7 @@ export function liveBlueskyCaptureDeps(input: Pick<PostCaptureInput, "pagePauseM openPage: openFreshBlueskyPage, pageGapMs: () => blueskyPageGapMs(Math.random, input.pagePauseMs), imageGapMs: () => 1_000 + Math.round(Math.random() * 1_000), + apiGapMs: () => 1_000 + Math.round(Math.random() * 1_000), pause: sleepUnlessAborted, }; } @@ -209,21 +212,37 @@ async function politeGet( // ─── 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) => `(() => { +// The post on its page. A self-thread's parents and replies by the same +// author share the anchor's test id, and a short reply ("lol") is a substring +// of many a parent, so the post is found by what is its own and nothing else's: +// 1. the item holding a link to its own permalink (…/post/<rkey>); +// 2. else the item holding an element whose whole text IS the post's text; +// 3. else the only item by the author on the page. +// Two items matching the same rule are ambiguous: no shot (an error), never a +// shot of the wrong post. Marked for the shot; its box in document coordinates. +export const SNAPSHOT_SCRIPT = (handle: string, text: string, rkey: string) => `(() => { const sel = ${JSON.stringify(`[data-testid="postThreadItem-by-${handle}"]`)}; + const rkey = ${JSON.stringify(rkey)}; const norm = (s) => (s || "").replace(/\\s+/g, " ").trim().toLowerCase(); - const want = norm(${JSON.stringify(text)}).slice(0, 80); + const want = norm(${JSON.stringify(text)}); 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; + const ownLink = (el) => Array.from(el.querySelectorAll("a[href]")).some((a) => { + try { return new URL(a.getAttribute("href"), location.href).pathname.replace(/\\/+$/, "").endsWith("/post/" + rkey); } catch { return false; } + }); + const exactText = (el) => want !== "" && Array.from(el.querySelectorAll("*")).some((d) => norm(d.innerText) === want); + let own = null; + let ambiguous = 0; + for (const rule of [ownLink, exactText]) { + const hits = all.filter(rule); + if (hits.length === 1) { own = hits[0]; break; } + if (hits.length > 1) { ambiguous = hits.length; break; } + } + if (!own && !ambiguous && all.length === 1) own = all[0]; 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) }; + if (!own) return { count: all.length, ambiguous, 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: "" }; + return { count: all.length, ambiguous: 0, 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 @@ -238,7 +257,7 @@ const IMAGES_LOADED_SCRIPT = `(() => { }))).then(() => imgs.length); })()`; -type Snapshot = { count: number; rect: { x: number; y: number; width: number; height: number } | null; text: string }; +type Snapshot = { count: number; ambiguous?: number; rect: { x: number; y: number; width: number; height: number } | null; text: string }; export type BlueskyShotResult = { state: PostCaptureState; @@ -275,6 +294,8 @@ export async function shootBlueskyPost( url: string; canonicalUrl: string; handle: string; + // The post's rkey: an item holding a link to it is the post. + rkey: string; text: string; dir: string; signal: AbortSignal; @@ -303,7 +324,7 @@ export async function shootBlueskyPost( ).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 snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text, o.rkey)).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." }; @@ -311,13 +332,18 @@ export async function shootBlueskyPost( 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; + let snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text, o.rkey))) 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.` }; + return { + state: "error", + error: snap.ambiguous + ? `${snap.ambiguous} posts by @${o.handle} on the page match this one; none shot rather than the wrong one.` + : `${snap.count} posts by @${o.handle} on the page, none of them this one (by its link or its whole 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; + snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text, o.rkey))) 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." }; @@ -397,48 +423,72 @@ export async function captureBlueskyPosts( } if (owed.length === 0) return { outcomes }; - // The account's DID: getPosts takes AT-URIs. + // EACH POST UNDER ITS OWN AUTHOR. A repost is archived under the original's + // rkey and author (normalizeBlueskyItem), so the channel's own DID would not + // find it, and its absence would read as a deletion. Each owed post is looked + // up as at://<its author's DID>/…/<rkey> (the author from the archive; a + // handle resolved once). An absence is a deletion only from a batch asked + // under the post's own author; a post whose author is not known, or whose + // author did not resolve, learns nothing (never `deleted`). 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>(); + let calls = 0; + const apiCall = async (url: string): Promise<Got> => { + if (calls++ > 0) await deps.pause(deps.apiGapMs(), signal); + if (signal.aborted) return { ok: false, error: "cancelled" }; + return politeGet(deps, url, "application/json", signal, onLog); + }; + const authorOf = (id: string): string | null => input.archived?.get(id)?.author?.trim().replace(/^@/, "") || null; + const byAuthor = new Map<string, typeof owed>(); 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}`); + for (const o of owed) { + const author = authorOf(o.id); + if (!author) { + unanswered.set(o.id, "the archive names no author for this post; nothing learned"); 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; + const list = byAuthor.get(author) ?? []; + list.push(o); + byAuthor.set(author, list); + } + const views = new Map<string, BlueskyPostView>(); + for (const [author, posts] of byAuthor) { + let did = author; + if (!did.startsWith("did:")) { + const got = await apiCall(`${appview}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(author)}`); + if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); + if (!got.ok && got.rateLimited) return stopped(`${got.error}; stopping — the posts are left for a later run.`); + const body = got.ok ? ((await got.res.json().catch(() => null)) as { did?: string } | null) : null; + if (!body?.did) { + // The account itself did not answer: no evidence about its posts. + const why = `could not resolve @${author}: ${got.ok ? "no DID in the answer" : got.error}`; + onLog?.(`${why} — ${posts.length} post(s) left as they were.`); + for (const o of posts) unanswered.set(o.id, why); + continue; + } + did = body.did; } - for (const v of body.posts) { - const rkey = rkeyOf(v.uri); - if (rkey) views.set(rkey, v); + // Liveness and images, 25 posts a request, a gap between requests. + for (let i = 0; i < posts.length; i += GET_POSTS_BATCH) { + const batch = posts.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 apiCall(`${appview}/xrpc/app.bsky.feed.getPosts?${params.toString()}`); + 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); + // Only the answer for the post asked: its own author's record. + if (rkey && v.uri === `at://${did}/app.bsky.feed.post/${rkey}`) views.set(rkey, v); + } } } @@ -453,7 +503,7 @@ export async function captureBlueskyPosts( onLog?.(`[${i + 1}/${owed.length}] ${id}`); const view = views.get(id); const failedLookup = unanswered.get(id); - const author = view?.author?.handle || input.handle; + const author = view?.author?.handle || authorOf(id) || input.handle; const canonicalUrl = postPermalink("bluesky", author, id); let state: PostCaptureState; @@ -484,6 +534,7 @@ export async function captureBlueskyPosts( url: onBlueskyEndpoints(`https://bsky.app/profile/${author}/post/${id}`, deps.endpoints), canonicalUrl, handle: author, + rkey: id, text: view.record?.text ?? "", dir, signal, diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -176,6 +176,10 @@ export type SocialFetcherFields = { export type PostAvailabilityInput = { ids: ReadonlyArray<string>; handle: string; + // Each id's author as archived, where it is not the channel's own account + // (a repost). A fetcher that looks posts up under the channel's account + // must not read such a post's absence as a deletion. + authors?: ReadonlyMap<string, string>; signal: AbortSignal; onLog?: (line: string) => void; }; @@ -214,6 +218,9 @@ export type PostCaptureInput = Pick< // posts: the capture opens the URL and downloads the media). url?: string; media?: ReadonlyArray<{ kind: string; url: string; name?: string }>; + // The post's author as archived (Bluesky: a repost is archived under the + // original's author, which its lookup must name). + author?: string; } >; // A soft stop: no new post is started once it fires, and the one in hand diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -1,6 +1,7 @@ export type FakeWaybackCapture = { original: string; timestamp: string; statuscode: string; mimetype?: string }; export const CAPTURES: FakeWaybackCapture[]; +export const VIDEOS: string[]; export type FakeWayback = { base: string; @@ -9,4 +10,4 @@ export type FakeWayback = { close(): Promise<void>; }; -export function startFakeWayback(opts?: { captures?: FakeWaybackCapture[]; busyTimes?: number; downTimes?: number }): Promise<FakeWayback>; +export function startFakeWayback(opts?: { captures?: FakeWaybackCapture[]; videos?: string[]; busyTimes?: number; downTimes?: number }): Promise<FakeWayback>; diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -14,6 +14,10 @@ // then one row per capture of <u> (oldest first); no captures: `[]` (the real API's empty answer) // without output=json: the same rows space-separated, one per line // GET /web/<timestamp>[id_|if_]/<original> the capture (text/html), 404 for an unknown one +// GET /__wb/videoinfo?vtype=youtube&vid=<id> (release 29 review) what yt-dlp's +// YoutubeWebArchive extractor asks: `{formats: [...]}` for an id in +// opts.videos (default VIDEOS), `{}` for any other — the video itself +// archived, not only its watch page // opts.busyTimes: the first N CDX requests answer 429 (Retry-After: 1); opts.downTimes: then 503s. import http from "node:http"; @@ -37,8 +41,12 @@ const urlkey = (u) => { } }; +// YouTube ids whose video (not only its page) the fake archive holds. +export const VIDEOS = ["gone-video-05"]; + export async function startFakeWayback(opts = {}) { const captures = opts.captures ?? CAPTURES; + const videos = opts.videos ?? VIDEOS; const requests = []; let busy = opts.busyTimes ?? 0; let down = opts.downTimes ?? 0; @@ -71,6 +79,13 @@ export async function startFakeWayback(opts = {}) { if (u.searchParams.get("output") === "json") return send(200, "application/json", JSON.stringify(rows.length ? [HEADER, ...rows] : [])); return send(200, "text/plain", rows.map((r) => r.join(" ")).join("\n") + (rows.length ? "\n" : "")); } + if (u.pathname === "/__wb/videoinfo") { + const vid = u.searchParams.get("vid") ?? ""; + const body = videos.includes(vid) + ? { formats: [{ url: `https://rr1---sn-fake.googlevideo.com/videoplayback?itag=18&id=${vid}`, ext: "mp4" }] } + : {}; + return send(200, "application/json", JSON.stringify(body)); + } const m = /^\/web\/(\d{14})(?:id_|if_)?\/(.+)$/.exec(u.pathname + u.search); if (m) { const c = captures.find((x) => x.timestamp === m[1] && x.original === m[2]); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -13,9 +13,11 @@ - **`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 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 starts a job that takes each cited YouTube recording that is deleted or private and looks for a copy: the Wayback Machine, when it holds the video itself (not just a saved copy of its page), then an archive.org upload of that same video — one whose name, file names or original link name the video, and whose length matches. It 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. A copy that fails to fetch is noted, and the next run tries the next one. 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. +- **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. If the video is back, check its availability again (the channel page's Diagnostics), or send the item with `"force": true`. +- **A members-only video's window is listed as "members-only"** among the windows no fetch can fill, unless the channel has browser cookies set to fetch it with. +- **Capture posts on Bluesky looks a repost up under its original author**, so a repost is never recorded as deleted, and the deleted-post check leaves reposts alone. On a page showing a thread, the screenshot is of the post itself, never of another post in the thread. - **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. diff --git a/editor/app/api/ops/archive-search/route.ts b/editor/app/api/ops/archive-search/route.ts @@ -4,7 +4,7 @@ import { ARCHIVE_ORG_SEARCH_MAX_ROWS, searchArchiveOrgItems, } from "yt-dlp-transcript-common/controller/archiveOrgImport"; -import { findArchiveOrgMirrors } from "yt-dlp-transcript-common/publish/findCopy"; +import { findArchiveOrgMirrors, isYoutubeId } from "yt-dlp-transcript-common/publish/findCopy"; import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqString } from "../_lib"; export const dynamic = "force-dynamic"; @@ -20,13 +20,15 @@ export const dynamic = "force-dynamic"; // `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. +// `youtubeId` (release 29 E2) looks for MIRRORS of one YouTube upload +// (publish/findCopy.ts): the search finds items mentioning the id, each is +// read for its files (one request each), and only an item OF the upload — its +// identifier, a file's name or its `originalurl`/`source` names the id, not +// merely its title or description — is a mirror, answered with its direct +// video file URL (`https://archive.org/download/<identifier>/<file>`, an +// original preferred). Anything else is `skipped`, with why. `limit` +// defaults to 10 here. (find-copy also checks the file's length against the +// recording's.) const ARCHIVE_SEARCH_DEFAULT_LIMIT = 50; const MIRROR_DEFAULT_LIMIT = 10; @@ -37,7 +39,7 @@ export async function POST(request: Request) { 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`); + if (!isYoutubeId(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 { diff --git a/editor/app/api/ops/fetch-windows/route.ts b/editor/app/api/ops/fetch-windows/route.ts @@ -26,7 +26,7 @@ import { export const dynamic = "force-dynamic"; // POST { siteId, maxHeight?, dryRun? } -// | { items: [{ slug, id, from, to, clipId?, reason?, pad?, webpageUrl? }, …], +// | { items: [{ slug, id, from, to, clipId?, reason?, pad?, webpageUrl?, force? }, …], // requestedBy, manifest?, maxHeight?, dryRun? } // dryRun -> { ok, dryRun: true, groups: [{ platform, queueKey, items }], // cached, inFlight, unresolved[, onDisk, unfetchable] } @@ -44,9 +44,13 @@ export const dynamic = "force-dynamic"; // down or held is `refused` for its group, and the other groups still start. // Re-running the same body is the resume: fetched windows are cached. // +// A window of a recording its availability says is deleted or private is +// refused (unresolved) unless the item names a `webpageUrl` (a copy: find-copy) +// or `"force": true` (the reading is stale — or check its availability again). +// // A big list goes in a file: `pnpm ops fetch-windows --file list.json`. -const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl"]; +const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force"]; function optItemString(e: OpsBody, key: string, where: string): string | undefined { const v = e[key]; @@ -55,6 +59,11 @@ function optItemString(e: OpsBody, key: string, where: string): string | undefin return v.trim() || undefined; } +function reqItemForce(v: unknown, where: string): boolean { + if (typeof v !== "boolean") throw new OpsInputError(`"${where}.force" must be a boolean`); + return v; +} + function reqSeconds(e: OpsBody, key: string, where: string): number { const v = e[key]; if (typeof v !== "number" || !Number.isFinite(v) || v < 0) { @@ -106,6 +115,7 @@ function reqWindowItems(body: OpsBody): FetchWindowsItem[] { reason: optItemString(e, "reason", where)?.slice(0, 400), ...(typeof pad === "number" ? { pad } : {}), webpageUrl: optItemString(e, "webpageUrl", where), + ...(e.force !== undefined ? { force: reqItemForce(e.force, where) } : {}), }; }); } diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts @@ -1,26 +1,26 @@ -import { NextResponse } from "next/server"; import { findCopyAction } from "../../../channels/[slug]/videos/findCopyAction"; -import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib"; +import { OpsInputError, jobResponse, ops, 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? } +// POST { article } | { siteId } | { articles: true }, dryRun? -> { ok, 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. +// publish/findCopy.ts), as a `find-copy` job: 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 YouTube recording, one at a time: the Wayback Machine when it holds the +// video (the check yt-dlp makes), then archive.org (a mirror of the upload — +// its identifier, a file name or its original URL names the id — whose file +// has the recording's length). A copy a fetch failed from before is not picked +// again. 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` looks and starts no fetch. The job's log ends with +// `@@find-copy {recordings: [{slug, id, gone, watchUrl, youtubeId, windows, +// failedBefore, tried, copy?, outcome}], items, stopped?, fetchJobId?, +// refused?}`; `--wait` follows it. export async function POST(request: Request) { return ops(request, ["article", "siteId", "articles", "dryRun"], async (body) => { const article = optString(body, "article")?.trim(); @@ -29,12 +29,12 @@ export async function POST(request: Request) { 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); + return jobResponse( + await findCopyAction({ + ...(article ? { article } : {}), + ...(siteId ? { siteId } : {}), + dryRun: optBool(body, "dryRun") === true, + }), + ); }); } diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts @@ -178,4 +178,15 @@ test("a gone recording's window is refused at the door unless the item names a c if (!viaCopy.ok) return; assert.deepEqual(viaCopy.unresolved, []); assert.deepEqual(viaCopy.groups.flatMap((g) => g.items.map((i) => i.webpageUrl)), [copy]); + // A stale reading: "force" fetches from the recording's own page; the refusal named the re-check. + assert.match(plain.unresolved[0].error, /Check availability.*"force": true/); + const forced = await fetchWindowsAction({ + items: [{ slug: SLUG, id: "deleted1", from: 1, to: 3, force: true }], + requestedBy: "test", + dryRun: true, + }); + assert.ok(forced.ok); + if (!forced.ok) return; + assert.deepEqual(forced.unresolved, []); + assert.deepEqual(forced.groups.flatMap((g) => g.items.map((i) => i.webpageUrl)), ["https://www.youtube.com/watch?v=deleted1"]); }); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -225,17 +225,18 @@ async function planFetchWindows( } // 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()) { + // names a copy's URL (`webpageUrl`: find-copy's Wayback or archive.org copy, + // release 29 E2) or says `force` (a stale reading). The refusal names the + // re-check that clears a stale one. + if (!item.webpageUrl?.trim() && !item.force) { 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.", + "If it is back, check its availability again (the channel page's Diagnostics → Check availability) " + + 'or send the item with "force": true; pnpm ops find-copy looks for a copy (Wayback, archive.org).', }); continue; } diff --git a/editor/app/channels/[slug]/videos/findCopyAction.ts b/editor/app/channels/[slug]/videos/findCopyAction.ts @@ -5,30 +5,25 @@ import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/li 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 { FIND_COPY_RESULT_MARKER, runFindCopy } from "yt-dlp-transcript-common/publish/findCopy"; +import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; 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; - }); +// from it (release 29 E2; the lookups are publish/findCopy.ts) — AS A JOB +// (`find-copy`, its own queue): the lookups take seconds per recording, paced, +// and a request must not hold them (nor start a fetch after its caller gave +// up). A cancelled job starts no fetch. The windows of every copy found go to +// ONE fetch-windows job on the archive.org clip queue — Wayback copies and +// archive.org files are both archive.org's — so they are fetched one at a +// time, paced, one stream. The job's log ends with +// `@@find-copy {recordings, items, stopped?, fetchJobId?, refused?}`. +const FIND_COPY_QUEUE = "find-copy"; // The archive.org clip queue: every copy's windows, one job, one stream. -const FIND_COPY_QUEUE = clipWindowQueueKey(platformQueueKey("archiveorg")); +const FETCH_QUEUE = clipWindowQueueKey(platformQueueKey("archiveorg")); -export async function findCopyAction(req: { article?: string; siteId?: string; dryRun?: boolean }): Promise<FindCopyActionResult> { +export async function findCopyAction(req: { article?: string; siteId?: string; dryRun?: boolean }): Promise<StreamActionResult> { const paths = getPaths(); let host: ReportHost; try { @@ -44,28 +39,41 @@ export async function findCopyAction(req: { article?: string; siteId?: string; d } catch (e) { return { ok: false, error: (e as Error).message }; } - let refused: string | undefined; - const r = await runFindCopy({ + return runManagedFunction({ + kind: "find-copy", + queueKey: FIND_COPY_QUEUE, 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; + fn: async (onLog, signal) => { + let refused: string | undefined; + const r = await runFindCopy({ + paths, + host, + dryRun: req.dryRun, + signal, + onLog, + startFetch: async (items) => { + const res = await fetchWindowsJobAction({ items, requestedBy: "find-copy", manifest: host.id, queueKey: FETCH_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(() => {}); + onLog(`find-copy: fetch-windows job ${res.jobId} fetches ${items.length} window(s) from the copies found.`); + return res.jobId; + }, + }); + const { fetch: fetchJobId, ...found } = r; + onLog( + `${FIND_COPY_RESULT_MARKER}${JSON.stringify({ + ...found, + dryRun: req.dryRun === true, + ...(typeof fetchJobId === "string" ? { fetchJobId } : {}), + ...(refused ? { refused } : {}), + })}`, + ); + if (refused) throw new Error(`the fetch was refused: ${refused}`); + if (signal.aborted) throw new Error("cancelled"); }, }); - const { fetch: jobId, ...found } = r; - return { - ok: true, - dryRun: req.dryRun === true, - ...found, - ...(typeof jobId === "string" ? { jobId } : {}), - ...(refused ? { refused } : {}), - }; } diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9503,7 +9503,10 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `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 + `media-<n>.<ext>` beside it; the record is postCapture.ts's (`url` the canonical bsky.app permalink). Each post + is looked up under its ARCHIVED author's DID (`archived.author` from capturePosts; a repost's is the original's), + and the shot is the item linking to its own `/post/<rkey>`, else the one whose element text is the post's whole + text, else the only one (ambiguous → error). 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. @@ -9511,10 +9514,12 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **"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. + `missingEvidenceWindows` (its `gone` field), fetch-windows' door and find-copy all read it. Members-only is + "unfetchable: members-only" there unless the channel has cookies to send (then a window to fetch). - **`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 + carry `sourceGone: "deleted" | "private"` when compose accepted the moment with no media — which it does ONLY when + the host's report-media index lists the moment as a `source-gone` warning (prepare's word), the source is still + gone and no media is on disk since; 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 @@ -9523,6 +9528,12 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri 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. +- **find-copy's copies** (`publish/findCopy.ts`, a `find-copy` job): YouTube pages only; Wayback when + `__wb/videoinfo?vtype=youtube&vid=<id>` has formats (yt-dlp's own check), URL + `https://web.archive.org/web/<ts>/https://www.youtube.com/watch?v=<id>`; else an archive.org item whose + identifier, a file name or `originalurl`/`source` names the id, its file within 5 s / 2 % of the record's + `duration`. A copy whose fetch failed is in `data/<id>/copy-attempts.json` (`lib/copyAttempts-server.ts`, written by + fetch-windows) and is not picked again. ## Release 29 M8: verdict proposals (verified 2026-10-15, branch `r29/verdicts`) diff --git a/plans/release-29.md b/plans/release-29.md @@ -637,6 +637,56 @@ run 1 4 passed, 1 failed (the bar's window line rendered without its space — ` **4/4**; `verdict-proposed.spec` **1/1** in run 1 (the stale proposal counted, the rewrite between view and click refused, then rejected on reload). +### E1/E2 review fixes (2026-10-15, lane A, `r29/evidence`) + +The read-only review of E1/E2 (`$T/r29ra-review.md`) found eight defects; each fixed as the orchestrator ruled: +1. **Compose decides "gone" on prepare's word only.** A moment with no media is accepted as words only when this + host's index lists it as a `source-gone` warning (prepare gives one after its reachability check, with no media to + cut; the warning now names the state), the source is still gone, and no media is on disk since (a window or a + capture fetched after prepare). No index, another host's, or a moment prepare failed for (unreachable, cut-failed, + too-big) stays `missing-media`. +2. **Bluesky looks each post up under its own author.** capturePosts hands each id's archived author to the capture + (`archived.author`); each author's DID is resolved once and getPosts asked under it; an absence is `deleted` only + from a batch asked under the post's own author (an unknown or unresolved author: nothing learned). A 1–2 s gap + before every AppView request after the first (`apiGapMs`). The deleted-post sweep (`checkAvailability`) leaves + another account's posts (reposts) as they were (`PostAvailabilityInput.authors`). +3. **Wayback counts only when it holds the video.** The installed yt-dlp's YoutubeWebArchive extractor + (`yt_dlp/extractor/archiveorg.py` `_real_extract`) asks `web.archive.org/__wb/videoinfo?vtype=youtube&vid=<id>` + and stops when it has no formats; find-copy asks the same (`WaybackClient.youtubeVideoArchived`), and the copy's URL + is the form the extractor takes (`waybackYoutubeUrl`). A copy whose fetch failed is recorded by fetch-windows beside + the recording (`data/<id>/copy-attempts.json`, `lib/copyAttempts-server.ts`; not on a rate limit or a cancel), and + the next find-copy falls through: Wayback → archive.org → the next mirror. +4. **A mirror must be OF the upload.** Its identifier, a file's name or its `originalurl`/`source` names the id (a + title or description is not enough — a compilation does that); its file's length agrees with the record's + `duration` (± 5 s or 2 %; a file with no length is not taken when the duration is known); only a record whose page + is a YouTube URL is looked for (`youtubeIdOf` reads YouTube hosts only; no fallback to the record's own id). +5. **The Bluesky shot is the post's own item**: the one linking to `/post/<rkey>`, else the one holding an element + whose whole text is the post's, else the only item by the author; two matches are an error, never a wrong shot. +6. **The fetch-windows door** names the availability re-check (Diagnostics → Check availability) and takes an item's + `"force": true` (documented in the ops help). +7. **find-copy is a job** (`find-copy` kind, its own queue; its log ends with `@@find-copy {…, fetchJobId?}`); a + cancelled run starts no fetch. +8. **Members-only** is "unfetchable: members-only" in `missingEvidenceWindows` unless the channel has cookies to send + (`authRetryCookies` of its cookie policy: then a window to fetch); compose never reads it as gone. + +| Commit | What | +| --- | --- | +| `4939d74e` | compose: gone only on prepare's `source-gone` warning (1) | +| `478938ee` | Bluesky: each post under its own author, the API gap, the sweep's reposts; the self-thread shot (2, 5) | +| `739c6b87` | find-copy: the Wayback video check, the mirror match and length, YouTube pages only, failed copies (3, 4) | +| `a224715e` | find-copy as a job; the door's re-check and `force`; members-only (6, 7, 8) | +| `40979b5e` | the find-copy result marker out of the "use server" file (the e2e build refused it) | +| (this commit) | this paragraph, FACTS, CHANGELOG | + +Gates: tsc clean at every commit; common 4218 → 4226/4226; editor 308/308; mcp 370/370; `test:scripts` 1010 + 3 +skipped; export 117/117; homepage 25/25; `docs env|files|cli --check`, `settings example --check` clean; editor e2e +`capture-posts.spec.ts` 1/1 (43 s; its start-mode build 178 s, through the heavy slot). New tests: a repost looked up +under its author and the sweep leaving it; a self-thread page in a real Chromium (a short reply under parents holding +its words, the own-link rule, two twins → error); compose refusing gone-on-disk without prepare's warning and another +host's warning; the Wayback order and its fall-through; a compilation mentioning the id rejected; a length mismatch; +a Rumble record not looked for; a failed copy recorded and not on a 429; members-only with and without cookies; the +door's `force`. + ## 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 @@ -1156,7 +1156,11 @@ export function usage() { ' (YouTube and Rumble side by side): {"siteId"} fetches every window the', ' site\'s published reports cite and the disk does not hold; {"items":', ' [{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?,', - ' "webpageUrl"?}, ...], "requestedBy", "manifest"?} fetches a list.', + ' "webpageUrl"?, "force"?}, ...], "requestedBy", "manifest"?} fetches a list.', + ' A window of a recording whose availability says deleted or private is', + ' refused (unresolved) unless the item names a "webpageUrl" (a copy:', + ' find-copy) or "force": true (a stale reading; or check its availability', + " again on the channel page's Diagnostics).", ' "maxHeight" caps the source height (default 720). "dryRun": true lists', ' the windows per platform, the ones already on disk ("cached") and the', ' ones no fetch can fill ("unfetchable": deleted, off the site) and starts', @@ -1242,10 +1246,12 @@ export function usage() { " 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.', + ' instead: items OF it (their identifier, a file name or their original', + ' URL names the id; a title or description that mentions it is not', + ' enough), each read for its files -> {query, found, items: [{identifier,', + ' title?, file, url, source, size?, seconds?, namedBy}], 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?,', @@ -1263,19 +1269,21 @@ export function usage() { " 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.", + ' report cites, and fetches the cited windows from it, as a find-copy job:', + ' {"article"} | {"articles": true} | {"siteId"}, "dryRun"? -> {jobId}. Per', + ' YouTube recording, one at a time: the Wayback Machine when it holds the', + ' video (the check yt-dlp makes, not a capture of the page), then', + ' archive.org (a mirror of the upload: its identifier, a file name or its', + ' original URL names the id, and the file has the recording\'s length). A', + ' copy a fetch failed from before is not picked again. 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". The log ends with @@find-copy', + " {recordings: [{slug, id, gone, watchUrl, youtubeId, windows, failedBefore,", + " tried, copy?, outcome}], items, stopped?, fetchJobId?, refused?}. dryRun", + " looks and starts no fetch; a cancelled job starts none.", "", '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',