Archilyzer · Source

archilyzer

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

commit 8240f10440058a7f10f30f199af026a26f7e06a8
parent 32ea4b5cfa22c9fe4582746733a2b838df25221d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 02:12:03 -0400

Merge branch 'main' into r31/mirrors

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/archiveOrgRefresh.test.ts | 17+++++++++++++++++
Mcommon/controller/archiveOrgRefresh.ts | 23++++++++++++++++++-----
Acommon/controller/fetchCopies.test.ts | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/fetchCopies.ts | 359+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 2++
Mcommon/jobs/jobKinds.ts | 17+++++++++++++++++
Mcommon/lib/copyAttempts-server.ts | 124++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/copyAttempts.test.ts | 58+++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/publish/findCopy.ts | 506++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Acommon/publish/findCopyScope.test.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/fetchCopyManaged.test.ts | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/fetchCopyManaged.ts | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/_research.test.ts | 30++++++++++++++++++++++++++++++
Meditor/app/api/ops/find-copy/route.ts | 46+++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 44++++++++++++++++++++++++++++++++++++++++++--
Meditor/app/channels/[slug]/videos/findCopyAction.ts | 138++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aeditor/e2e/find-copy-whole.spec.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/FACTS.md | 35+++++++++++++++++++++++++++++++++++
Aplans/release-31/find-copy-all.md | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 22+++++++++++++++++++++-
22 files changed, 2227 insertions(+), 92 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -147,7 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `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, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -&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 at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). 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`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --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"?, "retryFailed"? -&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 at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). 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. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --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/archiveOrgRefresh.test.ts b/common/controller/archiveOrgRefresh.test.ts @@ -165,3 +165,20 @@ test("refresh: an unknown channel is refused", async () => { await assert.rejects(refreshArchiveOrgRecords({ paths, slug: "no-such-channel" }), /not found/); }); }); + +// Release 31 (lane C): a gone YouTube video whose AUDIO came from an +// archive.org mirror carries the mirror's archiveorg.json — but it is the +// original's record, and its title and date are never the mirror's. +test("refresh: a record that is not archive.org's own (its audio from an archive.org copy) is left alone", async () => { + await withCorpus(async (paths, dataDir) => { + const id = "Pqr678stu_4"; + await mkdir(path.join(dataDir, id), { recursive: true }); + await writeFile(path.join(dataDir, id, "archiveorg.json"), JSON.stringify(oldProvenance(RAW))); + const info = JSON.stringify({ id, extractor_key: "Youtube", title: "The original's own title", upload_date: "20200101", webpage_url: `https://www.youtube.com/watch?v=${id}` }); + await writeFile(path.join(dataDir, id, "metadata.info.json"), info); + const r = await refreshArchiveOrgRecords({ paths, slug: SLUG }); + assert.equal(r.fileRecords, 3, "the three archive.org file records, not the YouTube one"); + assert.ok(!r.changed.some((c) => c.id === id)); + assert.equal(await readFile(path.join(dataDir, id, "metadata.info.json"), "utf8"), info); + }); +}); diff --git a/common/controller/archiveOrgRefresh.ts b/common/controller/archiveOrgRefresh.ts @@ -23,6 +23,7 @@ import path from "node:path"; import { getPaths, type Paths } from "../lib/paths"; import { readJsonFile } from "../lib/jsonFile-server"; import { assertChannelTextReadable } from "../lib/channelMedia"; +import { detectPlatform } from "../lib/platform"; import { archiveOrgMetadataPatch, withFileNameFields } from "../lib/archiveOrg"; import { loadArchiveOrgProvenance, writeArchiveOrgProvenance } from "../lib/archiveOrg-server"; import { patchMetadataInfo } from "../lib/metadataHistory-server"; @@ -46,6 +47,14 @@ export type ArchiveOrgRefreshResult = { failed: { id: string; error: string }[]; }; +// archive.org's own record: yt-dlp's (or the import's) extractor is +// `ArchiveOrg`, or its page is an archive.org page. +export function isArchiveOrgRecordInfo(info: Record<string, unknown>): boolean { + const key = String(info.extractor_key ?? info.extractor ?? ""); + if (/^archive\.?org$/i.test(key)) return true; + return typeof info.webpage_url === "string" && detectPlatform(info.webpage_url) === "archiveorg"; +} + export async function refreshArchiveOrgRecords(opts: { slug: string; paths?: Paths; @@ -65,6 +74,15 @@ export async function refreshArchiveOrgRecords(opts: { const videoDir = path.join(dataDir, id); const prov = await loadArchiveOrgProvenance(videoDir); if (!prov?.file) continue; + const read = await readJsonFile(path.join(videoDir, "metadata.info.json")); + const info = + read.ok && read.value && typeof read.value === "object" && !Array.isArray(read.value) + ? (read.value as Record<string, unknown>) + : null; + // A record that is not archive.org's own — a gone YouTube video whose + // AUDIO came from an archive.org copy (release 31, fetch-copies) — keeps + // its original's metadata: nothing here is about it. + if (info && !isArchiveOrgRecordInfo(info)) continue; result.fileRecords++; try { const next = withFileNameFields(prov); @@ -72,11 +90,6 @@ export async function refreshArchiveOrgRecords(opts: { result.sidecars++; if (!opts.dryRun) await writeArchiveOrgProvenance(videoDir, next); } - const read = await readJsonFile(path.join(videoDir, "metadata.info.json")); - const info = - read.ok && read.value && typeof read.value === "object" && !Array.isArray(read.value) - ? (read.value as Record<string, unknown>) - : null; if (!info) continue; const full = archiveOrgMetadataPatch(next, info); const patch: Record<string, unknown> = {}; diff --git a/common/controller/fetchCopies.test.ts b/common/controller/fetchCopies.test.ts @@ -0,0 +1,223 @@ +// fetch-copies (release 31, lane C): each gone video's whole audio from the +// copy find-copy found, into its own record — the copy's provenance and a +// `fetched` attempt written, a source-side failure recorded (never ours), a +// rate limit stopping the run with the backoff recorded, a video that holds +// media by its turn skipped, the gap between fetches — and the transcription +// lane then sees the audio: the snapshot moves the video from noTranscript +// (where a gone video's download never comes) to downloadedNoTranscript. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchCopies.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { ClipCopy } from "../lib/clipWindow"; +import { loadCopyAttempts } from "../lib/copyAttempts-server"; +import { loadArchiveOrgProvenance } from "../lib/archiveOrg-server"; +import { ArchiveOrgClient } from "../lib/archiveOrgClient"; +import { GONE_AVAILABILITY } from "../testing/draft/corpus.mjs"; +import { startFakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; +import { FetchWindowError } from "../ytdlp/fetchWindowManaged"; +import type { FetchCopyOpts } from "../ytdlp/fetchCopyManaged"; +import { copyAttemptFields, fetchCopies, writeCopyProvenance, type FetchCopiesDeps, type FetchCopyItem } from "./fetchCopies"; +import { generateChannelSnapshot } from "./channelSnapshot"; + +const SLUG = "alpha"; +const GONE_A = "goneAAAAAA1"; +const GONE_B = "goneBBBBBB2"; +const GONE_C = "goneCCCCCC3"; +const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`; +const wayback = (id: string): ClipCopy => ({ from: "wayback", url: `https://web.archive.org/web/20240102030405/${watch(id)}` }); +const mirror = (id: string): ClipCopy => ({ from: "archive.org", url: `https://archive.org/download/youtube-${id}/An%20upload-${id}.mp4` }); + +async function corpus() { + const dir = await mkdtemp(path.join(os.tmpdir(), "fetch-copies-")); + const paths = { + channelsDir: path.join(dir, "channels"), + transcriptsDir: dir, + savedVideosDir: path.join(dir, "saved-videos"), + ytdlpBin: "/nonexistent/yt-dlp", + } as Paths; + const channelDir = path.join(paths.channelsDir, SLUG); + await mkdir(path.join(channelDir, "data"), { recursive: true }); + await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube", url: "https://www.youtube.com/@alpha/videos", audioFormat: "mp3" })); + await writeFile(path.join(channelDir, "playlist"), [GONE_A, GONE_B, GONE_C].map(watch).join("\n")); + for (const id of [GONE_A, GONE_B, GONE_C]) { + const v = path.join(channelDir, "data", id); + await mkdir(v, { recursive: true }); + await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, title: `Original ${id}`, webpage_url: watch(id), duration: 300, extractor_key: "Youtube" })); + await writeFile(path.join(v, "availability.json"), JSON.stringify({ ...GONE_AVAILABILITY, webpageUrl: watch(id) })); + } + return { dir, paths, dataDir: path.join(channelDir, "data"), close: () => rm(dir, { recursive: true, force: true }) }; +} + +// A fetch that writes the audio (as fetchCopyManaged would), or fails as told. +function fakeFetch(fail: Record<string, Error> = {}) { + const calls: FetchCopyOpts[] = []; + return { + calls, + fetchCopy: async (o: FetchCopyOpts) => { + calls.push(o); + const e = fail[o.videoId]; + if (e) throw e; + await writeFile(path.join(o.videoDir, "audio.mp3"), "audio"); + return { audioFile: "audio.mp3", bytes: 5, args: [] }; + }, + }; +} + +function deps(over: Partial<FetchCopiesDeps> = {}) { + const events: string[] = []; + const d: Partial<FetchCopiesDeps> = { + assertMediaReachable: async () => undefined, + sleep: async (ms) => void events.push(`sleep ${ms}`), + cooldownRemainingMs: async () => 0, + heldRefusal: async () => null, + recordBackoff: async (p, _paths, cls) => void events.push(`backoff ${p} ${cls}`), + recordClean: async () => null, + // Wayback's sidecar is built from the URL alone (no request); archive.org's + // would ask the item — the test's own fake is given where it is needed. + writeProvenance: async (dir, copy, o) => (copy.from === "wayback" ? writeCopyProvenance(dir, copy, o) : undefined), + now: () => new Date("2026-10-16T00:00:00.000Z"), + ...over, + }; + return { d, events }; +} + +test("each copy's audio into its own record: wayback.json, a fetched attempt, the original's metadata kept; the gap between fetches", async () => { + const c = await corpus(); + try { + const f = fakeFetch(); + const { d, events } = deps({ fetchCopy: f.fetchCopy }); + const items: FetchCopyItem[] = [ + { slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }, + { slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }, + { slug: SLUG, id: GONE_A, copy: mirror(GONE_A) }, // the same recording again: dropped + ]; + const r = await fetchCopies({ paths: c.paths, items, gapMs: 1234, deps: d }); + assert.deepEqual(r.fetched.map((x) => x.id), [GONE_A, GONE_B]); + assert.deepEqual(events, ["sleep 1234"], "one gap, between the two fetches"); + const dirA = path.join(c.dataDir, GONE_A); + assert.equal(f.calls[0]!.videoDir, dirA, "the ORIGINAL record's dir"); + const wb = JSON.parse(await readFile(path.join(dirA, "wayback.json"), "utf8")); + assert.equal(wb.originalUrl, watch(GONE_A)); + assert.equal(wb.captureTs, "20240102030405"); + const attempts = (await loadCopyAttempts(dirA))?.attempts ?? []; + assert.deepEqual(attempts.map((a) => [a.outcome, a.source, a.captureTs, a.audioFile]), [["fetched", "wayback", "20240102030405", "audio.mp3"]]); + assert.equal(JSON.parse(await readFile(path.join(dirA, "metadata.info.json"), "utf8")).title, `Original ${GONE_A}`); + } finally { + await c.close(); + } +}); + +test("archive.org copy: archiveorg.json from the item (the fake), the attempt names its identifier and file", async () => { + const c = await corpus(); + const ia = await startFakeArchiveOrg({ + items: [ + { + metadata: { identifier: `youtube-${GONE_C}`, title: `An upload ${GONE_C}`, mediatype: "movies", originalurl: watch(GONE_C) }, + files: [{ name: `An upload-${GONE_C}.mp4`, source: "original", format: "MPEG4", size: "3000", length: "300" }], + }, + ], + }); + try { + const client = new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }); + const f = fakeFetch(); + const { d } = deps({ fetchCopy: f.fetchCopy, writeProvenance: (dir, copy, o) => writeCopyProvenance(dir, copy, { ...o, client }) }); + const r = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_C, copy: mirror(GONE_C) }], deps: d }); + assert.equal(r.fetched.length, 1); + const dir = path.join(c.dataDir, GONE_C); + const prov = await loadArchiveOrgProvenance(dir); + assert.equal(prov?.identifier, `youtube-${GONE_C}`); + assert.equal(prov?.file, `An upload-${GONE_C}.mp4`); + const a = (await loadCopyAttempts(dir))?.attempts?.[0]; + assert.deepEqual([a?.outcome, a?.source, a?.identifier, a?.file], ["fetched", "archive.org", `youtube-${GONE_C}`, `An upload-${GONE_C}.mp4`]); + assert.equal(JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")).title, `Original ${GONE_C}`, "the metadata is not the mirror's"); + } finally { + await ia.close(); + await c.close(); + } +}); + +test("a copy that failed at its source is recorded (failed + attempt); our own failure is not; a 429 stops the run and backs archive.org off", async () => { + const c = await corpus(); + try { + const f = fakeFetch({ + [GONE_A]: new FetchWindowError("ERROR: HTTP Error 404: Not Found", "unknown", "error"), + [GONE_B]: new FetchWindowError("ERROR: ffmpeg exited with code 1", "unknown", "error"), + [GONE_C]: new FetchWindowError("ERROR: HTTP Error 429: Too Many Requests", "rate_limit", "error"), + }); + const { d, events } = deps({ fetchCopy: f.fetchCopy }); + const items = [GONE_A, GONE_B, GONE_C].map((id) => ({ slug: SLUG, id, copy: wayback(id) })); + const r = await fetchCopies({ paths: c.paths, items: [...items, { slug: SLUG, id: "afterStop01", copy: wayback("afterStop01") }], gapMs: 0, deps: d }); + assert.deepEqual(r.failed.map((x) => [x.item.id, x.class]), [[GONE_A, "unknown"], [GONE_B, "unknown"], [GONE_C, "rate_limit"]]); + assert.equal(r.stopped, "rate-limit"); + assert.deepEqual(r.notAttempted.map((x) => x.id), ["afterStop01"]); + assert.ok(events.includes("backoff archiveorg rate_limit")); + const a = await loadCopyAttempts(path.join(c.dataDir, GONE_A)); + assert.deepEqual(a?.failed.map((x) => x.url), [wayback(GONE_A).url]); + assert.deepEqual(a?.attempts?.map((x) => x.outcome), ["failed"]); + assert.equal(await loadCopyAttempts(path.join(c.dataDir, GONE_B)), null, "ffmpeg is ours: nothing held against the copy"); + assert.equal(await loadCopyAttempts(path.join(c.dataDir, GONE_C)), null, "a rate limit says nothing about the copy"); + } finally { + await c.close(); + } +}); + +test("a video holding media by its turn is skipped; an unreachable channel fails its items; a cooldown stops before any request", async () => { + const c = await corpus(); + try { + await writeFile(path.join(c.dataDir, GONE_A, "source-media.mp4"), "x"); + const f = fakeFetch(); + const r1 = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }], deps: deps({ fetchCopy: f.fetchCopy }).d }); + assert.deepEqual(r1.skipped.map((s) => s.id), [GONE_A]); + const r2 = await fetchCopies({ + paths: c.paths, + items: [{ slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }], + deps: deps({ fetchCopy: f.fetchCopy, assertMediaReachable: async () => Promise.reject(new Error("the drive is not mounted")) }).d, + }); + assert.deepEqual(r2.failed.map((x) => x.class), ["unreachable"]); + const r3 = await fetchCopies({ + paths: c.paths, + items: [{ slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }], + deps: deps({ fetchCopy: f.fetchCopy, cooldownRemainingMs: async () => 60_000 }).d, + }); + assert.equal(r3.stopped, "cooldown"); + assert.equal(f.calls.length, 0, "nothing was fetched"); + } finally { + await c.close(); + } +}); + +test("copyAttemptFields: an archive.org copy's item and file, a Wayback copy's capture", () => { + assert.deepEqual(copyAttemptFields(mirror("x0000000001")), { + source: "archive.org", + url: mirror("x0000000001").url, + identifier: "youtube-x0000000001", + file: "An upload-x0000000001.mp4", + }); + assert.equal(copyAttemptFields(wayback("x0000000001")).captureTs, "20240102030405"); + assert.equal(copyAttemptFields({ from: "wayback", url: `https://web.archive.org/web/${watch("x")}` }).captureTs, undefined); +}); + +test("the transcription lane picks the audio up: the snapshot moves a gone video from noTranscript to downloadedNoTranscript", async () => { + const c = await corpus(); + try { + const before = await generateChannelSnapshot(c.paths, SLUG); + assert.ok(before.buckets.noTranscript.includes(GONE_A)); + assert.ok(before.excludedFromDownload?.deleted.includes(GONE_A), "gone: out of the download lane"); + assert.ok(!before.undownloadedIds.includes(GONE_A)); + const f = fakeFetch(); + await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }], deps: deps({ fetchCopy: f.fetchCopy }).d }); + const after = await generateChannelSnapshot(c.paths, SLUG); + assert.ok(!after.buckets.noTranscript.includes(GONE_A)); + assert.ok(after.buckets.downloadedNoTranscript.includes(GONE_A), "the transcription lane's first bucket"); + assert.ok(after.backfill?.transcription?.ids.includes(GONE_A), "and its work list"); + assert.ok(after.excludedFromDownload?.deleted.includes(GONE_A), "still gone on its platform"); + } finally { + await c.close(); + } +}); diff --git a/common/controller/fetchCopies.ts b/common/controller/fetchCopies.ts @@ -0,0 +1,359 @@ +// FETCH THE WHOLE AUDIO OF GONE VIDEOS FROM THEIR COPIES, AS ONE PACED JOB +// (release 31, lane C; the `fetch-copies` kind). +// +// find-copy's scope mode (publish/findCopy.ts findWholeCopies) found a copy of +// each gone video — the Wayback Machine holding it, or an archive.org mirror +// of it — and hands the list here. Each item goes through fetchCopyManaged +// (ytdlp/fetchCopyManaged.ts) into its ORIGINAL record's `audio.<fmt>`, one at +// a time, and then: +// +// wayback.json / archiveorg.json the copy's provenance, through the +// existing writers (lib/wayback-server.ts ensureWaybackProvenance — from +// the URL alone; lib/archiveOrg-server.ts +// ensureArchiveOrgProvenanceSidecar — the item's metadata, cached). +// metadata.info.json is NOT touched: the record stays the original's. +// copy-attempts.json a `fetched` attempt (what the video page's "Audio +// from a copy" line reads), or a `failed` one when the copy failed at its +// source (lib/copyAttempts-server.ts isSourceSideCopyFailure; also in +// `failed`, so no find-copy picks that copy again). +// +// PACED: archive.org serves both kinds of copy, so the run is paced as the +// `archiveorg` platform — its hold and cooldown asked before every fetch, a 429 +// recorded against it and the run stopped, a success recorded clean — and +// WHOLE_COPY_MIN_GAP_SECONDS lies between two fetches. A whole file is one +// long request, never a burst. +// +// A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's media guard has +// no channel to ask; each channel's media reachability (it WRITES audio) is +// asked here, once, before its first item. + +import path from "node:path"; +import { readdir } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { ClipCopy } from "../lib/clipWindow"; +import type { JobProgress } from "../jobs/registry"; +import { parseArchiveOrgUrl } from "../lib/archiveOrgId"; +import { parseWaybackUrl } from "../lib/wayback"; +import { ensureWaybackProvenance } from "../lib/wayback-server"; +import { ensureArchiveOrgProvenanceSidecar } from "../lib/archiveOrg-server"; +import type { ArchiveOrgClient } from "../lib/archiveOrgClient"; +import { assertChannelMediaReachable } from "../lib/channelMedia"; +import { + isSourceSideCopyFailure, + recordCopyAttempt, + recordFailedCopy, + type CopyAttempt, + type FailedCopy, +} from "../lib/copyAttempts-server"; +import { channelConfigPlatform } from "../lib/videoId"; +import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; +import { + heldPlatformRefusal, + platformCooldownRemainingMs, + recordDownloadBackoff, + recordPlatformClean, +} from "../jobs/downloadBackoff"; +import { FetchWindowError } from "../ytdlp/fetchWindowManaged"; +import { fetchCopyManaged, holdsMedia, type FetchCopyOpts, type FetchCopyResult } from "../ytdlp/fetchCopyManaged"; +import { readChannelConfig } from "./channels"; + +// The least time between two whole-copy fetches. +export const WHOLE_COPY_MIN_GAP_SECONDS = 30; + +// The platform a copy's fetch is paced and backed off as. +export const COPY_PLATFORM = "archiveorg"; + +export type FetchCopyItem = { + slug: string; + id: string; + copy: ClipCopy; +}; + +export type FetchCopiesFailure = { item: FetchCopyItem; class: string; message: string }; + +export type FetchCopiesResult = { + fetched: (FetchCopyItem & { audioFile: string; bytes: number })[]; + // Already holding audio or video when its turn came: nothing fetched. + skipped: (FetchCopyItem & { why: string })[]; + failed: FetchCopiesFailure[]; + notAttempted: FetchCopyItem[]; + stopped?: "rate-limit" | "cooldown" | "held" | "drain" | "cancel"; +}; + +export type FetchCopiesDeps = { + fetchCopy: (opts: FetchCopyOpts) => Promise<FetchCopyResult>; + readChannelConfig: (paths: Paths, slug: string) => Promise<ChannelConfig | null>; + assertMediaReachable: (paths: Paths, slug: string) => Promise<unknown>; + sleep: (ms: number, signal?: AbortSignal) => Promise<void>; + cooldownRemainingMs: (platform: string, paths: Paths) => Promise<number>; + heldRefusal: (platform: string, paths: Paths) => Promise<string | null>; + recordBackoff: (platform: string, paths: Paths, failureClass: "rate_limit" | "network") => Promise<void>; + recordClean: (platform: string, paths: Paths) => Promise<string | null>; + recordFailedCopy: (videoDir: string, failed: FailedCopy) => Promise<void>; + recordCopyAttempt: (videoDir: string, attempt: CopyAttempt) => Promise<void>; + // The copy's provenance sidecar (wayback.json / archiveorg.json). + writeProvenance: (videoDir: string, copy: ClipCopy, o: { onLog: (s: string) => void; signal: AbortSignal }) => Promise<void>; + now: () => Date; +}; + +function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { + if (ms <= 0 || signal?.aborted) return Promise.resolve(); + return new Promise((resolve) => { + const onAbort = () => { + clearTimeout(t); + resolve(); + }; + const t = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +// wayback.json from the capture URL (none when the URL names no capture +// timestamp); archiveorg.json from the item (cached by the client). +export async function writeCopyProvenance( + videoDir: string, + copy: ClipCopy, + o: { onLog: (s: string) => void; signal: AbortSignal; client?: ArchiveOrgClient }, +): Promise<void> { + if (copy.from === "wayback") { + await ensureWaybackProvenance(videoDir, copy.url, { onLog: o.onLog }); + return; + } + const ref = parseArchiveOrgUrl(copy.url); + if (ref) { + await ensureArchiveOrgProvenanceSidecar(videoDir, ref, { + onLog: o.onLog, + signal: o.signal, + ...(o.client ? { client: o.client } : {}), + }); + } +} + +const DEFAULT_DEPS: FetchCopiesDeps = { + fetchCopy: fetchCopyManaged, + readChannelConfig, + assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug), + sleep: abortableSleep, + cooldownRemainingMs: (platform, paths) => platformCooldownRemainingMs(platform, paths), + heldRefusal: (platform, paths) => heldPlatformRefusal(platform, "This batch", paths), + recordBackoff: (platform, paths, cls) => recordDownloadBackoff(platform, paths, cls), + recordClean: (platform, paths) => recordPlatformClean(platform, paths), + recordFailedCopy, + recordCopyAttempt, + writeProvenance: writeCopyProvenance, + now: () => new Date(), +}; + +// What a copy attempt names of its copy: the archive.org item and file, the +// Wayback capture's timestamp. +export function copyAttemptFields(copy: ClipCopy): Pick<CopyAttempt, "source" | "url" | "identifier" | "file" | "captureTs"> { + const out: Pick<CopyAttempt, "source" | "url" | "identifier" | "file" | "captureTs"> = { source: copy.from, url: copy.url }; + if (copy.from === "archive.org") { + const ref = parseArchiveOrgUrl(copy.url); + if (ref?.identifier) out.identifier = ref.identifier; + if (ref?.file) out.file = ref.file; + } else { + const ts = parseWaybackUrl(copy.url)?.captureTs; + if (ts) out.captureTs = ts; + } + return out; +} + +export const fetchCopyItemLabel = (item: FetchCopyItem) => `${item.slug}/${item.id} (${item.copy.from})`; + +export async function fetchCopies({ + paths, + items, + gapMs, + onLog, + signal, + drainSignal, + setProgress, + deps: depsOverride, +}: { + paths: Paths; + items: FetchCopyItem[]; + // The pause between two fetches; absent = WHOLE_COPY_MIN_GAP_SECONDS. + gapMs?: number; + onLog?: (line: string) => void; + signal?: AbortSignal; + drainSignal?: AbortSignal; + setProgress?: (snap: JobProgress) => void; + deps?: Partial<FetchCopiesDeps>; +}): Promise<FetchCopiesResult> { + const deps: FetchCopiesDeps = { ...DEFAULT_DEPS, ...depsOverride }; + const log = (line: string) => onLog?.(line.endsWith("\n") ? line : `${line}\n`); + const fetchLog = (line: string) => onLog?.(line); + const fetchSignal = signal ?? new AbortController().signal; + const gap = gapMs ?? WHOLE_COPY_MIN_GAP_SECONDS * 1000; + // One item per recording: the first ask wins. + const seen = new Set<string>(); + const work = items.filter((i) => { + const k = `${i.slug}\0${i.id}`; + if (seen.has(k)) return false; + seen.add(k); + return true; + }); + const result: FetchCopiesResult = { fetched: [], skipped: [], failed: [], notAttempted: [] }; + log(`Fetch copies: ${work.length} gone video(s), each one's whole audio from its copy.`); + let done = 0; + const progress = () => setProgress?.({ metric: "downloads", initial: 0, target: work.length, current: done }); + progress(); + + const configs = new Map<string, ChannelConfig | null>(); + const reachable = new Map<string, string | null>(); + const fail = (item: FetchCopyItem, cls: string, message: string) => { + result.failed.push({ item, class: cls, message }); + log(` ✗ ${fetchCopyItemLabel(item)}: ${cls} — ${message}`); + }; + const interrupted = (): FetchCopiesResult["stopped"] | null => + signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null; + const stop = (why: NonNullable<FetchCopiesResult["stopped"]>, from: number) => { + result.stopped = why; + result.notAttempted.push(...work.slice(from)); + }; + let networkAttempts = 0; + + for (let i = 0; i < work.length; i++) { + const item = work[i]!; + const why = interrupted(); + if (why) { + stop(why, i); + break; + } + const label = fetchCopyItemLabel(item); + if (!configs.has(item.slug)) configs.set(item.slug, await deps.readChannelConfig(paths, item.slug).catch(() => null)); + const config = configs.get(item.slug) ?? null; + if (!config) { + fail(item, "unknown-channel", `no channel "${item.slug}"`); + done++; + progress(); + continue; + } + if (!reachable.has(item.slug)) { + reachable.set( + item.slug, + await deps.assertMediaReachable(paths, item.slug).then( + () => null, + (e: unknown) => (e as Error).message, + ), + ); + } + const unreachable = reachable.get(item.slug); + if (unreachable) { + fail(item, "unreachable", unreachable); + done++; + progress(); + continue; + } + const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { platform: channelConfigPlatform(config) }); + const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId); + const entries = await readdir(videoDir).catch(() => null); + if (!entries) { + fail(item, "no-record", `no directory for ${item.id}`); + done++; + progress(); + continue; + } + if (holdsMedia(entries)) { + result.skipped.push({ ...item, why: "it already holds audio or video" }); + log(` = ${label}: already holds audio or video; nothing fetched.`); + done++; + progress(); + continue; + } + + if (networkAttempts > 0 && gap > 0) { + log(`Sleeping ${Math.round(gap / 1000)}s before the next copy...`); + await deps.sleep(gap, signal); + const after = interrupted(); + if (after) { + stop(after, i); + break; + } + } + const held = await deps.heldRefusal(COPY_PLATFORM, paths); + if (held) { + log(` ${label}: ${held} — stopping; the rest are left for a later run.`); + stop("held", i); + break; + } + const cooldownMs = await deps.cooldownRemainingMs(COPY_PLATFORM, paths); + if (cooldownMs > 0) { + log( + ` ${label}: archive.org is in a rate-limit cooldown (${Math.ceil(cooldownMs / 1000)}s remaining) — ` + + `stopping; the rest are left for a later run.`, + ); + stop("cooldown", i); + break; + } + + log(` ${label}: fetching ${item.copy.url}…`); + networkAttempts++; + try { + const r = await deps.fetchCopy({ + paths, + channelConfig: config, + videoDir, + videoId: dirId, + copy: item.copy, + onLog: fetchLog, + signal: fetchSignal, + }); + try { + await deps.writeProvenance(videoDir, item.copy, { onLog: fetchLog, signal: fetchSignal }); + } catch (e) { + log(` ${label}: the copy's provenance was not written (${(e as Error).message}).`); + } + await deps + .recordCopyAttempt(videoDir, { + at: deps.now().toISOString(), + outcome: "fetched", + ...copyAttemptFields(item.copy), + audioFile: r.audioFile, + }) + .catch((e: unknown) => log(` ${label}: copy-attempts.json not written (${(e as Error).message}).`)); + result.fetched.push({ ...item, audioFile: r.audioFile, bytes: r.bytes }); + const clean = await deps.recordClean(COPY_PLATFORM, paths).catch(() => null); + if (clean) log(clean); + } catch (e) { + const message = (e as Error).message; + const cls = e instanceof FetchWindowError ? e.failureClass : "unknown"; + fail(item, cls, message); + if (cls === "rate_limit") { + await deps.recordBackoff(COPY_PLATFORM, paths, "rate_limit").catch(() => {}); + log(` archive.org rate-limited this run — stopping; the rest are left for a later run.`); + done++; + progress(); + stop("rate-limit", i + 1); + break; + } + // A COPY THAT FAILED AT ITS SOURCE is recorded, as fetch-windows records + // a window's: never picked again by find-copy (`failed`), and a terminal + // attempt for the scope mode. Our own side (the extraction, a disk) is + // not held against the copy. + if (!fetchSignal.aborted && isSourceSideCopyFailure(cls, message)) { + const at = deps.now().toISOString(); + await deps.recordFailedCopy(videoDir, { ...item.copy, at, error: message }).catch(() => {}); + await deps + .recordCopyAttempt(videoDir, { at, outcome: "failed", ...copyAttemptFields(item.copy), error: message }) + .catch(() => {}); + log(` ${label}: the ${item.copy.from} copy failed at its source — find-copy will not pick it again.`); + } + } + done++; + progress(); + } + + log( + `Fetch copies: ${result.fetched.length} fetched, ${result.skipped.length} already held media, ` + + `${result.failed.length} failed` + + (result.notAttempted.length ? `, ${result.notAttempted.length} not attempted (stopped: ${result.stopped})` : "") + + ".", + ); + return result; +} diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -103,6 +103,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = { "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 }, + // fetch-copies (release 31): gone videos' whole audio from their copies. + "fetch-copies": { label: "Fetch copies", drainable: true }, }; test("added kinds carry their pinned label and drainability", () => { diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -972,6 +972,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: false, queueKeyStrategy: "custom", }, + // fetch-copies (release 31, lane C): the WHOLE audio of gone videos from the + // copies find-copy's scope mode found (controller/fetchCopies.ts), each into + // its own record's audio.<fmt>, one at a time on archive.org's download + // queue. It writes audio (needsMedia); a list spanning channels starts with + // no channelSlug and the controller asks each channel's media guard. + // Drainable: it stops between videos, and a re-run skips any that hold + // media by then. + "fetch-copies": { + kind: "fetch-copies", + label: "Fetch copies", + drainable: true, + replayable: false, + queueKeyStrategy: "custom", + needsMedia: true, + }, "bench-verdicts": { kind: "bench-verdicts", label: "Verdict bench", @@ -1182,6 +1197,8 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([ "check-maybe-missing", "attach-media", "prepare-playable", + // A gone video's audio from a copy, and the copy's provenance (release 31). + "fetch-copies", ]); export function isIngestKind(kind: string | undefined): boolean { diff --git a/common/lib/copyAttempts-server.ts b/common/lib/copyAttempts-server.ts @@ -5,29 +5,90 @@ // next (Wayback → archive.org → the next mirror). Written by fetch-windows // (controller/fetchWindows.ts) on an item's failure; read by find-copy. // +// AND EVERY WHOLE-COPY ATTEMPT (release 31, lane C): find-copy's scope mode +// (`{slug | siteId, gone}`) looks for a copy of a gone video's WHOLE audio and +// fetch-copies brings it home into the record. Each run's answer for the video +// is appended to `attempts`: `fetched` (the audio is the copy's — the video +// page's "Audio from a copy" line reads it), `none-found` (neither Wayback nor +// archive.org holds it) or `failed` (the copy's fetch failed at its source). +// The last two are TERMINAL: the scope mode skips a video whose newest +// terminal attempt is younger than COPY_ATTEMPT_RETRY_DAYS, unless +// `retryFailed`. A lookup that errored (a rate limit, archive.org down) is not +// an attempt and is never recorded. +// // SERVER-ONLY (node:fs). -import { coerceClipCopy, type ClipCopy } from "./clipWindow"; +import { CLIP_COPY_SOURCES, coerceClipCopy, type ClipCopy } from "./clipWindow"; +import { withJsonFileLock } from "./jsonFile-server"; 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. +export const COPY_ATTEMPT_OUTCOMES = ["fetched", "none-found", "failed"] as const; +export type CopyAttemptOutcome = (typeof COPY_ATTEMPT_OUTCOMES)[number]; + +// One whole-copy attempt (release 31). `source`/`url` name the copy (absent +// for none-found: every source was asked); an archive.org copy names its item +// and file, a Wayback copy its capture's timestamp when the URL carries one. +export type CopyAttempt = { + at: string; + outcome: CopyAttemptOutcome; + source?: ClipCopy["from"]; + url?: string; + identifier?: string; + file?: string; + captureTs?: string; + // The audio file a fetch wrote (`audio.<fmt>`). + audioFile?: string; + // What was asked and found, in a phrase (none-found). + detail?: string; + error?: string; +}; + +export type CopyAttempts = { failed: FailedCopy[]; attempts?: CopyAttempt[] }; + +// How long a terminal whole-copy attempt (none-found, failed) keeps a video +// out of find-copy's scope mode: archives fill in slowly, and asking archive.org +// about the same id every night is the scraper shape the clients exist to avoid. +export const COPY_ATTEMPT_RETRY_DAYS = 30; + +// The newest few, one per URL; the newest few attempts. const KEEP = 20; +const optStr = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined); + +function coerceCopyAttempt(v: unknown): CopyAttempt | null { + if (!v || typeof v !== "object" || Array.isArray(v)) return null; + const r = v as Record<string, unknown>; + if (typeof r.at !== "string" || !(COPY_ATTEMPT_OUTCOMES as readonly unknown[]).includes(r.outcome)) return null; + const out: CopyAttempt = { at: r.at, outcome: r.outcome as CopyAttemptOutcome }; + if ((CLIP_COPY_SOURCES as readonly unknown[]).includes(r.source)) out.source = r.source as ClipCopy["from"]; + const url = optStr(r.url); + if (url && /^https?:\/\//.test(url)) out.url = url; + for (const k of ["identifier", "file", "captureTs", "audioFile", "detail", "error"] as const) { + const x = optStr(r[k]); + if (x) out[k] = x; + } + return out; +} + 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 v = value as { failed?: unknown; attempts?: unknown } | null; + if (!v || typeof v !== "object") return null; + if (!Array.isArray(v.failed) && !Array.isArray(v.attempts)) return null; const failed: FailedCopy[] = []; - for (const f of v.failed) { + for (const f of Array.isArray(v.failed) ? 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 }; + const out: CopyAttempts = { failed }; + if (Array.isArray(v.attempts)) { + out.attempts = v.attempts.map(coerceCopyAttempt).filter((a): a is CopyAttempt => a !== null); + } + return out; } export const copyAttemptsSidecar = sidecar(COPY_ATTEMPTS_FILENAME, sidecarField(coerceCopyAttempts)); @@ -47,12 +108,53 @@ export function isSourceSideCopyFailure(failureClass: string | undefined, messag ); } +export async function loadCopyAttempts(videoDir: string): Promise<CopyAttempts | null> { + return copyAttemptsSidecar.load(videoDir).catch(() => null); +} + export async function readFailedCopies(videoDir: string): Promise<FailedCopy[]> { - return (await copyAttemptsSidecar.load(videoDir).catch(() => null))?.failed ?? []; + return (await loadCopyAttempts(videoDir))?.failed ?? []; +} + +// Both writers read, change and write the file under its lock (fetch-windows +// and fetch-copies may finish on one recording at once), and each keeps what +// the other wrote. +async function updateCopyAttempts(videoDir: string, fn: (prev: CopyAttempts) => CopyAttempts): Promise<void> { + await withJsonFileLock(copyAttemptsSidecar.path(videoDir), async () => { + const prev = (await loadCopyAttempts(videoDir)) ?? { failed: [] }; + await copyAttemptsSidecar.write(videoDir, fn(prev)); + }); } 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 }); + await updateCopyAttempts(videoDir, (prev) => ({ + ...prev, + failed: [...prev.failed.filter((f) => f.url !== failed.url), { ...failed, error: failed.error.slice(0, 400) }].slice(-KEEP), + })); +} + +// Append one whole-copy attempt (release 31), the newest KEEP kept. +export async function recordCopyAttempt(videoDir: string, attempt: CopyAttempt): Promise<void> { + const a: CopyAttempt = { ...attempt, ...(attempt.error ? { error: attempt.error.slice(0, 400) } : {}), ...(attempt.detail ? { detail: attempt.detail.slice(0, 400) } : {}) }; + await updateCopyAttempts(videoDir, (prev) => ({ ...prev, attempts: [...(prev.attempts ?? []), a].slice(-KEEP) })); +} + +// The newest attempt that brought the copy's audio home, or null. +export function latestFetchedCopy(c: CopyAttempts | null | undefined): CopyAttempt | null { + return [...(c?.attempts ?? [])].reverse().find((a) => a.outcome === "fetched") ?? null; +} + +// The newest attempt when it is TERMINAL (none-found, failed) and younger +// than `days`, else null — what keeps a video out of find-copy's scope mode +// for a while. +export function recentTerminalAttempt( + c: CopyAttempts | null | undefined, + now: number = Date.now(), + days: number = COPY_ATTEMPT_RETRY_DAYS, +): CopyAttempt | null { + const last = c?.attempts?.at(-1); + if (!last || last.outcome === "fetched") return null; + const at = Date.parse(last.at); + if (!Number.isFinite(at)) return null; + return now - at < days * 86_400_000 ? last : null; } diff --git a/common/lib/copyAttempts.test.ts b/common/lib/copyAttempts.test.ts @@ -8,7 +8,19 @@ 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, isSourceSideCopyFailure, readFailedCopies, recordFailedCopy } from "./copyAttempts-server"; +import { readFile, writeFile } from "node:fs/promises"; +import { + COPY_ATTEMPTS_FILENAME, + COPY_ATTEMPT_RETRY_DAYS, + coerceCopyAttempts, + isSourceSideCopyFailure, + latestFetchedCopy, + loadCopyAttempts, + readFailedCopies, + recentTerminalAttempt, + recordCopyAttempt, + 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-")); @@ -41,3 +53,47 @@ test("isSourceSideCopyFailure: the copy's 404/410/403 or unreachability, never o assert.equal(isSourceSideCopyFailure("unknown", "ERROR: ffmpeg exited with code 1"), false); assert.equal(isSourceSideCopyFailure("unknown", "No space left on device"), false); }); + +// Release 31 (lane C): the whole-copy attempts beside the failed copies. +test("recordCopyAttempt and recordFailedCopy keep each other's entries; a file of the older shape still reads", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "copy-attempts-")); + try { + await writeFile(path.join(dir, COPY_ATTEMPTS_FILENAME), JSON.stringify({ failed: [{ from: "wayback", url: "https://web.archive.org/web/1/x", at: "1", error: "404" }] })); + assert.equal((await loadCopyAttempts(dir))?.attempts, undefined, "release 29's file: no attempts"); + await recordCopyAttempt(dir, { at: "2026-10-01T00:00:00.000Z", outcome: "none-found", detail: "wayback none; archive.org none" }); + await recordFailedCopy(dir, { from: "archive.org", url: "https://archive.org/download/a/b.mp4", at: "3", error: "403" }); + await recordCopyAttempt(dir, { + at: "2026-10-02T00:00:00.000Z", + outcome: "fetched", + source: "archive.org", + url: "https://archive.org/download/a/c.mp4", + identifier: "a", + file: "c.mp4", + audioFile: "audio.mp3", + }); + const c = await loadCopyAttempts(dir); + assert.deepEqual(c?.failed.map((f) => f.at), ["1", "3"]); + assert.deepEqual(c?.attempts?.map((a) => a.outcome), ["none-found", "fetched"]); + assert.equal(latestFetchedCopy(c)?.identifier, "a"); + assert.equal(recentTerminalAttempt(c), null, "the newest attempt fetched: not terminal"); + const raw = JSON.parse(await readFile(path.join(dir, COPY_ATTEMPTS_FILENAME), "utf8")); + assert.equal(raw.attempts.length, 2); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("recentTerminalAttempt: the newest attempt when none-found or failed and younger than the retry window", () => { + const now = Date.parse("2026-10-16T00:00:00.000Z"); + const day = 86_400_000; + const at = (daysAgo: number) => new Date(now - daysAgo * day).toISOString(); + const c = (outcome: "fetched" | "none-found" | "failed", daysAgo: number) => + coerceCopyAttempts({ attempts: [{ at: at(daysAgo), outcome }] }); + assert.equal(recentTerminalAttempt(c("none-found", 3), now)?.outcome, "none-found"); + assert.equal(recentTerminalAttempt(c("failed", COPY_ATTEMPT_RETRY_DAYS - 1), now)?.outcome, "failed"); + assert.equal(recentTerminalAttempt(c("none-found", COPY_ATTEMPT_RETRY_DAYS + 1), now), null, "old enough to ask again"); + assert.equal(recentTerminalAttempt(c("fetched", 1), now), null); + assert.equal(recentTerminalAttempt(null, now), null); + assert.equal(coerceCopyAttempts({ attempts: [{ at: "x", outcome: "maybe" }] })?.attempts?.length, 0, "an unknown outcome is dropped"); + assert.equal(coerceCopyAttempts({ nothing: true }), null); +}); diff --git a/common/publish/findCopy.ts b/common/publish/findCopy.ts @@ -48,7 +48,23 @@ 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 { + COPY_ATTEMPT_RETRY_DAYS, + loadCopyAttempts, + readFailedCopies, + recentTerminalAttempt, + recordCopyAttempt, + type CopyAttempt, + type CopyAttempts, + type FailedCopy, +} from "../lib/copyAttempts-server"; +import { sourceGoneState } from "../lib/sourceGone-server"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import { isVideoTranscribed, readVideoFiles } from "../lib/videoStatus"; +import { getSite } from "../lib/site"; +import { listChannelVideoIds } from "../controller/keptVideos"; +import { holdsMedia } from "../ytdlp/fetchCopyManaged"; +import type { FetchCopyItem } from "../controller/fetchCopies"; import { archiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClient } from "../lib/archiveOrgClient"; import { archiveOrgDownloadUrl } from "../lib/archiveOrgId"; import { archiveOrgRestriction, searchArchiveOrgItems } from "../controller/archiveOrgImport"; @@ -354,6 +370,100 @@ const DEFAULT_DEPS: FindCopyDeps = { const describeAttempt = (t: FindCopyAttempt) => `${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`; +// ONE RECORDING'S LOOKUP, shared by the article mode and the scope mode: +// Wayback when it holds the video (and no fetch from it failed before), then +// an archive.org mirror of the upload, of its length, not failed before. A +// lookup archive.org kept refusing sets `refused` (the caller stops its run). +// No YouTube id: nothing is asked. +export type CopyLookup = { + tried: FindCopyAttempt[]; + copy?: ClipCopy; + // The archive.org mirror the copy is (its item and file). + mirror?: ArchiveOrgMirror; + // The capture timestamp a Wayback copy is dated by. + captureTs?: string; + refused?: string; +}; + +export async function lookForCopy(o: { + youtubeId: string | null; + duration: number | null; + failedBefore: ClipCopy[]; + retryFailed?: boolean; + deps: Pick<FindCopyDeps, "wayback" | "archive">; + signal?: AbortSignal; +}): Promise<CopyLookup> { + const { youtubeId, deps, signal } = o; + const sig = signal ? { signal } : {}; + const out: CopyLookup = { tried: [] }; + const failedUrls = new Set(o.retryFailed ? [] : o.failedBefore.map((f) => f.url)); + const lookupFailed = (from: ClipCopy["from"], e: unknown) => { + if (signal?.aborted) return; + out.tried.push({ from, found: false, error: (e as Error).message }); + if (e instanceof ArchiveOrgRequestError && e.rateLimited) out.refused = (e as Error).message; + }; + if (!youtubeId) { + out.tried.push({ from: "wayback", found: false, detail: "not a YouTube recording: no copy is looked for" }); + return out; + } + // 1. The Wayback Machine — when it holds the video, and no fetch from it failed before. + if (!o.retryFailed && o.failedBefore.some((f) => f.from === "wayback")) { + out.tried.push({ from: "wayback", found: false, detail: "a fetch from its Wayback copy failed before" }); + } else { + try { + if (await deps.wayback.youtubeVideoArchived(youtubeId, sig)) { + // 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); + out.copy = { from: "wayback", url }; + if (newest) out.captureTs = newest.timestamp; + out.tried.push({ from: "wayback", found: true, url, detail: `the video is archived${newest ? `; its page captured ${newest.timestamp}` : ""}` }); + } else { + out.tried.push({ from: "wayback", found: false, detail: "the video is not archived (its page may be)" }); + } + } catch (e) { + lookupFailed("wayback", e); + } + } + + // 2. archive.org: a mirror OF the upload, of its length, not failed before. + if (!out.copy && !out.refused && !signal?.aborted) { + try { + const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, duration: o.duration, ...sig }); + const m = found.mirrors.find((x) => !failedUrls.has(x.url)); + if (m) { + out.copy = { from: "archive.org", url: m.url }; + out.mirror = m; + out.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; + out.tried.push({ + from: "archive.org", + found: false, + 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) { + lookupFailed("archive.org", e); + } + } + return out; +} + // 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). @@ -370,7 +480,6 @@ export async function findCopies(opts: { 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) { @@ -388,73 +497,12 @@ export async function findCopies(opts: { 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(opts.retryFailed ? [] : 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; - }; - - 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 (!opts.retryFailed && 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); - } - } - - // 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, 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}; ${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 usable mirror` : "no item names the id", - ...(failed ? [`${failed} mirror(s) failed before`] : []), - ...found.skipped.map((s) => `${s.identifier}: ${s.why}`), - ].join("; "), - }); - } - } catch (e) { - lookupFailed("archive.org", e); - } - } - } + const look = await lookForCopy({ youtubeId, duration: facts.duration, failedBefore, retryFailed: opts.retryFailed, deps, signal }); + rec.tried.push(...look.tried); + if (look.copy) rec.copy = look.copy; + const refused = look.refused; if (signal?.aborted) break; if (rec.copy) { @@ -512,3 +560,327 @@ export async function runFindCopy<T>(opts: { if (opts.dryRun || opts.signal?.aborted || found.items.length === 0) return found; return { ...found, fetch: await opts.startFetch(found.items) }; } + +// ─── find-copy, scope mode: every gone video of a channel or a site (release 31) ─── +// +// The article mode above fetches the cited WINDOWS of gone recordings. This +// mode brings a gone video's WHOLE audio home into its own record, so the +// transcription lane transcribes it like any other: `{slug | siteId, gone: +// "no-transcript" | "all", dryRun?, max?, retryFailed?}`. +// +// THE CANDIDATES: every video dir of the channel (or of every channel in the +// site's pool, `site.json` `channels`, in its order) that is gone by THE one +// reading (lib/sourceGone-server.ts sourceGoneState: deleted or private), that +// holds no audio or video yet (ytdlp/fetchCopyManaged.ts holdsMedia), and — for +// "no-transcript" — no transcript (lib/videoStatus.ts isVideoTranscribed); +// "all" takes the transcribed ones too, after every untranscribed one. A video +// whose newest copy attempt is terminal (none-found, failed) and younger than +// COPY_ATTEMPT_RETRY_DAYS is left out, unless `retryFailed`. A channel whose +// text cannot be read is named and skipped (an unmounted drive is not an empty +// channel). The cheap checks (one readdir) come first; the availability is read +// only for what passes them. +// +// THE LOOKUPS are the article mode's (lookForCopy), one video at a time, at +// most `max` of them per run (a non-YouTube video costs none and is listed); +// archive.org refusing stops the run. Not a dry run: a video neither source +// holds is recorded `none-found` in its copy-attempts.json, and the copies +// found go to ONE fetch-copies job (controller/fetchCopies.ts) — through +// `startFetch`, the editor's. A dry run asks the same questions and records +// and fetches nothing. + +export const GONE_SCOPES = ["no-transcript", "all"] as const; +export type GoneScope = (typeof GONE_SCOPES)[number]; + +// Lookups per run: a small default, and a ceiling. +export const FIND_COPY_DEFAULT_MAX = 10; +export const FIND_COPY_MAX_LIMIT = 200; + +export type WholeCopyScope = { slug: string } | { siteId: string }; + +export type GoneCandidate = { + slug: string; + id: string; + videoDir: string; + gone: GoneState; + noTranscript: boolean; +}; + +export type GoneEnumeration = { + channels: string[]; + candidates: GoneCandidate[]; + skipped: { + // Gone or not, already holding audio or video (not asked whether gone). + media: number; + // Holding a transcript, in "no-transcript" mode (not asked whether gone). + transcript: number; + // Gone, with a recent terminal copy attempt. + recent: { slug: string; id: string; at: string; outcome: string }[]; + // Channels whose text cannot be read. + unreadable: { slug: string; error: string }[]; + }; +}; + +export type GoneEnumerationDeps = { + listIds: (paths: Paths, slug: string) => Promise<string[]>; + assertTextReadable: (paths: Paths, slug: string) => Promise<unknown>; + goneState: (videoDir: string) => Promise<GoneState | null>; + copyAttempts: (videoDir: string) => Promise<CopyAttempts | null>; +}; + +const DEFAULT_ENUM_DEPS: GoneEnumerationDeps = { + listIds: listChannelVideoIds, + assertTextReadable: (paths, slug) => assertChannelTextReadable(paths, slug), + goneState: sourceGoneState, + copyAttempts: loadCopyAttempts, +}; + +export async function enumerateGoneVideos(opts: { + paths: Paths; + slugs: string[]; + gone: GoneScope; + retryFailed?: boolean; + now?: number; + signal?: AbortSignal; + deps?: Partial<GoneEnumerationDeps>; +}): Promise<GoneEnumeration> { + const deps: GoneEnumerationDeps = { ...DEFAULT_ENUM_DEPS, ...opts.deps }; + const now = opts.now ?? Date.now(); + const out: GoneEnumeration = { + channels: [...opts.slugs], + candidates: [], + skipped: { media: 0, transcript: 0, recent: [], unreadable: [] }, + }; + const untranscribed: GoneCandidate[] = []; + const transcribed: GoneCandidate[] = []; + for (const slug of opts.slugs) { + if (opts.signal?.aborted) break; + try { + await deps.assertTextReadable(opts.paths, slug); + } catch (e) { + out.skipped.unreadable.push({ slug, error: (e as Error).message }); + continue; + } + const ids = (await deps.listIds(opts.paths, slug)).sort(); + for (const id of ids) { + if (opts.signal?.aborted) break; + const videoDir = path.join(opts.paths.channelsDir, slug, "data", id); + const files = await readVideoFiles(videoDir); + if (holdsMedia(files.entries)) { + out.skipped.media++; + continue; + } + const noTranscript = !isVideoTranscribed(files); + if (!noTranscript && opts.gone === "no-transcript") { + out.skipped.transcript++; + continue; + } + const gone = await deps.goneState(videoDir).catch(() => null); + if (!gone) continue; + if (!opts.retryFailed) { + const recent = recentTerminalAttempt(await deps.copyAttempts(videoDir).catch(() => null), now); + if (recent) { + out.skipped.recent.push({ slug, id, at: recent.at, outcome: recent.outcome }); + continue; + } + } + (noTranscript ? untranscribed : transcribed).push({ slug, id, videoDir, gone, noTranscript }); + } + } + out.candidates = [...untranscribed, ...transcribed]; + return out; +} + +export type WholeCopyCandidate = { + slug: string; + id: string; + gone: GoneState; + noTranscript: boolean; + watchUrl: string | null; + youtubeId: string | null; + failedBefore: ClipCopy[]; + tried: FindCopyAttempt[]; + copy?: ClipCopy; + // What the copy is, in a phrase: the archive.org item and file, or the + // Wayback capture. + via?: string; + // fetch a copy found: its whole audio goes to fetch-copies + // none-found neither source holds it (recorded, not a dry run) + // not-youtube not a YouTube recording: nothing is looked for + // error a lookup failed: a later run asks again + outcome: "fetch" | "none-found" | "not-youtube" | "error"; +}; + +export type FindWholeCopiesResult = { + scope: WholeCopyScope; + gone: GoneScope; + dryRun: boolean; + max: number; + channels: string[]; + // Gone videos that qualified (before `max`). + eligible: number; + skipped: GoneEnumeration["skipped"]; + looked: WholeCopyCandidate[]; + // Qualifying YouTube videos left for a later run by `max`. + left: number; + items: FetchCopyItem[]; + stopped?: string; +}; + +export type FindWholeCopiesDeps = Pick<FindCopyDeps, "wayback" | "archive" | "facts" | "failedCopies"> & { + enumerate: GoneEnumerationDeps; + recordAttempt: (videoDir: string, attempt: CopyAttempt) => Promise<void>; + siteChannels: (paths: Paths, siteId: string) => string[]; + now: () => Date; +}; + +const DEFAULT_WHOLE_DEPS: FindWholeCopiesDeps = { + wayback: waybackClient, + archive: archiveOrgClient, + facts: recordFacts, + failedCopies: readFailedCopies, + enumerate: DEFAULT_ENUM_DEPS, + recordAttempt: recordCopyAttempt, + siteChannels: (paths, siteId) => getSite(siteId, paths).channels.map((c) => c.slug), + now: () => new Date(), +}; + +export function wholeCopyScopeLabel(scope: WholeCopyScope): string { + return "slug" in scope ? `channel ${scope.slug}` : `site ${scope.siteId}`; +} + +export async function findWholeCopies(opts: { + paths: Paths; + scope: WholeCopyScope; + gone: GoneScope; + dryRun?: boolean; + max?: number; + retryFailed?: boolean; + signal?: AbortSignal; + onLog?: (line: string) => void; + deps?: Partial<Omit<FindWholeCopiesDeps, "enumerate">> & { enumerate?: Partial<GoneEnumerationDeps> }; +}): Promise<FindWholeCopiesResult> { + const deps: FindWholeCopiesDeps = { + ...DEFAULT_WHOLE_DEPS, + ...opts.deps, + enumerate: { ...DEFAULT_ENUM_DEPS, ...opts.deps?.enumerate }, + }; + const log = (line: string) => opts.onLog?.(line); + const signal = opts.signal; + const dryRun = opts.dryRun === true; + const max = Math.min(FIND_COPY_MAX_LIMIT, Math.max(1, Math.floor(opts.max ?? FIND_COPY_DEFAULT_MAX))); + const slugs = "slug" in opts.scope ? [opts.scope.slug] : deps.siteChannels(opts.paths, opts.scope.siteId); + const found = await enumerateGoneVideos({ + paths: opts.paths, + slugs, + gone: opts.gone, + retryFailed: opts.retryFailed, + now: deps.now().getTime(), + ...(signal ? { signal } : {}), + deps: deps.enumerate, + }); + const result: FindWholeCopiesResult = { + scope: opts.scope, + gone: opts.gone, + dryRun, + max, + channels: found.channels, + eligible: found.candidates.length, + skipped: found.skipped, + looked: [], + left: 0, + items: [], + }; + log( + `find-copy ${wholeCopyScopeLabel(opts.scope)} (gone: ${opts.gone}${dryRun ? ", dry run" : ""}): ` + + `${found.candidates.length} gone video(s) with no media` + + `${opts.gone === "no-transcript" ? " and no transcript" : ""} in ${found.channels.length} channel(s); ` + + `at most ${max} looked up.` + + (found.skipped.recent.length ? ` ${found.skipped.recent.length} left out: a copy attempt in the last ${COPY_ATTEMPT_RETRY_DAYS} days found none or failed.` : ""), + ); + for (const u of found.skipped.unreadable) log(` ${u.slug}: skipped — ${u.error}`); + + let lookups = 0; + for (let i = 0; i < found.candidates.length; i++) { + const c = found.candidates[i]!; + if (signal?.aborted) break; + const facts = await deps.facts(opts.paths, c.slug, c.id); + const youtubeId = youtubeIdOf(facts.webpageUrl); + if (youtubeId && lookups >= max) { + result.left++; + continue; + } + const failedBefore = (await deps.failedCopies(facts.videoDir).catch(() => [] as FailedCopy[])).map(({ from, url }) => ({ from, url })); + const rec: WholeCopyCandidate = { + slug: c.slug, + id: c.id, + gone: c.gone, + noTranscript: c.noTranscript, + watchUrl: facts.webpageUrl, + youtubeId, + failedBefore, + tried: [], + outcome: youtubeId ? "none-found" : "not-youtube", + }; + if (youtubeId) lookups++; + const look = await lookForCopy({ youtubeId, duration: facts.duration, failedBefore, retryFailed: opts.retryFailed, deps, signal }); + rec.tried = look.tried; + if (signal?.aborted) break; + result.looked.push(rec); + if (look.copy) { + rec.copy = look.copy; + rec.outcome = "fetch"; + rec.via = look.mirror + ? `archive.org ${look.mirror.identifier} / ${look.mirror.file}` + : `the Wayback Machine${look.captureTs ? `, captured ${look.captureTs}` : ""}`; + result.items.push({ slug: c.slug, id: c.id, copy: look.copy }); + } else if (look.tried.some((t) => t.error)) { + rec.outcome = "error"; + } else if (youtubeId && !dryRun) { + await deps + .recordAttempt(facts.videoDir, { + at: deps.now().toISOString(), + outcome: "none-found", + detail: look.tried.map(describeAttempt).join("; "), + }) + .catch((e: unknown) => log(` ${c.slug}/${c.id}: copy-attempts.json not written (${(e as Error).message}).`)); + } + log( + ` ${c.slug}/${c.id} (${c.gone}${c.noTranscript ? ", no transcript" : ""}): ` + + rec.tried.map(describeAttempt).join("; ") + + ` → ${ + rec.outcome === "fetch" + ? `${dryRun ? "would fetch" : "fetch"} its audio from ${rec.via}` + : rec.outcome === "none-found" + ? `none found${dryRun ? "" : " (recorded)"}` + : rec.outcome === "not-youtube" + ? "not looked for" + : "try again later" + }`, + ); + if (look.refused) { + result.stopped = `archive.org kept refusing (${look.refused}); the rest are left for a later run`; + log(`find-copy: ${result.stopped}.`); + break; + } + } + if (signal?.aborted) { + result.stopped = "cancelled; the rest are left for a later run"; + log(`find-copy: ${result.stopped}.`); + } + if (result.left > 0) log(`find-copy: ${result.left} more gone video(s) are left for a later run (max ${max}).`); + log( + `find-copy: ${result.items.length} cop${result.items.length === 1 ? "y" : "ies"} found` + + `${dryRun ? " (dry run: nothing fetched or recorded)" : ""}.`, + ); + return result; +} + +// The scope mode, whole: the lookups, then (unless `dryRun`, or the run was +// cancelled) ONE fetch-copies of every copy found through `startFetch`. +export async function runFindWholeCopies<T>( + opts: Parameters<typeof findWholeCopies>[0] & { startFetch: (items: FetchCopyItem[]) => Promise<T> }, +): Promise<FindWholeCopiesResult & { fetch?: T }> { + const found = await findWholeCopies(opts); + 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/findCopyScope.test.ts b/common/publish/findCopyScope.test.ts @@ -0,0 +1,209 @@ +// find-copy's scope mode (release 31, lane C) over a synthetic corpus on disk, +// the fake Wayback and the fake archive.org: every gone video of a channel or +// a site with no media (and, for "no-transcript", no transcript) — gone by the +// one reading — untranscribed first; a recent terminal attempt keeps one out +// unless `retryFailed`; `max` caps the lookups; a dry run records and fetches +// nothing; a run records `none-found` and hands every copy found to ONE fetch. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopyScope.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { startFakeWayback } from "../testing/web/fakeWayback.mjs"; +import { startFakeArchiveOrg, type FakeArchiveOrgItem } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; +import { GONE_AVAILABILITY } from "../testing/draft/corpus.mjs"; +import { ArchiveOrgClient } from "../lib/archiveOrgClient"; +import { WaybackClient } from "../lib/waybackClient"; +import { loadCopyAttempts, recordCopyAttempt } from "../lib/copyAttempts-server"; +import type { Paths } from "../lib/paths"; +import type { FetchCopyItem } from "../controller/fetchCopies"; +import { enumerateGoneVideos, findWholeCopies, runFindWholeCopies } from "./findCopy"; + +const NOW = new Date("2026-10-16T00:00:00.000Z"); +const WB = "wbArchived1"; // the Wayback Machine holds the video +const IA = "iaMirrored1"; // an archive.org mirror of it +const NONE = "noCopyAny01"; // no copy anywhere +const TRANS = "transcribd1"; // gone, transcribed; the Wayback Machine holds it +const MEDIA = "hasAudio001"; // gone, audio already on disk +const LIVE = "stillLive01"; // not gone +const RECENT = "triedBefor1"; // gone, none found two days ago +const BETA = "betaGone001"; // gone, on the second channel; nothing holds it +const RUMBLE = "v5rumble"; // gone, a Rumble record +const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`; + +const MIRROR: FakeArchiveOrgItem = { + metadata: { identifier: `youtube-${IA}`, title: `An upload ${IA}`, mediatype: "movies", originalurl: watch(IA) }, + files: [{ name: `An upload-${IA}.mp4`, source: "original", format: "MPEG4", size: "3000", length: "300.0" }], +}; + +async function writeVideo(channelDir: string, id: string, o: { gone?: boolean; files?: Record<string, string>; page?: string } = {}) { + const v = path.join(channelDir, "data", id); + await mkdir(v, { recursive: true }); + const page = o.page ?? watch(id); + await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, title: `Original ${id}`, webpage_url: page, duration: 300 })); + if (o.gone !== false) await writeFile(path.join(v, "availability.json"), JSON.stringify({ ...GONE_AVAILABILITY, webpageUrl: page })); + for (const [name, body] of Object.entries(o.files ?? {})) await writeFile(path.join(v, name), body); + return v; +} + +async function corpus() { + const dir = await mkdtemp(path.join(os.tmpdir(), "find-copy-scope-")); + const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, sitesDir: path.join(dir, "sites") } as Paths; + const alpha = path.join(paths.channelsDir, "alpha"); + const beta = path.join(paths.channelsDir, "beta"); + for (const ch of [alpha, beta]) { + await mkdir(path.join(ch, "data"), { recursive: true }); + await writeFile(path.join(ch, "config.json"), JSON.stringify({ handling: "youtube", url: "https://www.youtube.com/@x/videos" })); + } + for (const id of [WB, IA, NONE]) await writeVideo(alpha, id); + await writeVideo(alpha, TRANS, { files: { "transcript.en.vtt": "WEBVTT\n\n00:00.000 --> 00:01.000\nhello\n" } }); + await writeVideo(alpha, MEDIA, { files: { "audio.mp3": "x" } }); + await writeVideo(alpha, LIVE, { gone: false }); + const recentDir = await writeVideo(alpha, RECENT); + await recordCopyAttempt(recentDir, { at: new Date(NOW.getTime() - 2 * 86_400_000).toISOString(), outcome: "none-found" }); + await writeVideo(alpha, RUMBLE, { page: "https://rumble.com/v5rumble-a-stream.html" }); + await writeVideo(beta, BETA); + return { dir, paths, alpha, beta, close: () => rm(dir, { recursive: true, force: true }) }; +} + +async function fakes() { + const wb = await startFakeWayback({ videos: [WB, TRANS] }); + const ia = await startFakeArchiveOrg({ items: [MIRROR] }); + const deps = { + wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }), + archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }), + siteChannels: () => ["beta", "alpha"], + now: () => NOW, + }; + return { wb, ia, deps, close: async () => Promise.all([wb.close(), ia.close()]) }; +} + +test("the candidates: gone by the one reading, no media, no transcript (or, for all, transcribed ones after), a recent attempt left out", async () => { + const c = await corpus(); + try { + const nt = await enumerateGoneVideos({ paths: c.paths, slugs: ["beta", "alpha"], gone: "no-transcript", now: NOW.getTime() }); + assert.deepEqual(nt.candidates.map((x) => x.id), [BETA, IA, NONE, RUMBLE, WB]); + assert.equal(nt.skipped.media, 1); + assert.equal(nt.skipped.transcript, 1); + assert.deepEqual(nt.skipped.recent.map((r) => [r.id, r.outcome]), [[RECENT, "none-found"]]); + const all = await enumerateGoneVideos({ paths: c.paths, slugs: ["alpha"], gone: "all", now: NOW.getTime(), retryFailed: true }); + assert.deepEqual(all.candidates.map((x) => [x.id, x.noTranscript]), [ + [IA, true], + [NONE, true], + [RECENT, true], + [RUMBLE, true], + [WB, true], + [TRANS, false], + ]); + // An unreadable channel is named and skipped, never read as empty. + const unreadable = await enumerateGoneVideos({ + paths: c.paths, + slugs: ["alpha"], + gone: "all", + deps: { assertTextReadable: async () => Promise.reject(new Error("its data/ is not readable")) }, + }); + assert.deepEqual(unreadable.skipped.unreadable, [{ slug: "alpha", error: "its data/ is not readable" }]); + assert.equal(unreadable.candidates.length, 0); + } finally { + await c.close(); + } +}); + +test("a dry run of a site: the source each would use, nothing recorded, nothing fetched", async () => { + const c = await corpus(); + const f = await fakes(); + try { + const r = await findWholeCopies({ paths: c.paths, scope: { siteId: "jx" }, gone: "no-transcript", dryRun: true, deps: f.deps }); + assert.deepEqual(r.looked.map((x) => [x.id, x.outcome]), [ + [BETA, "none-found"], + [IA, "fetch"], + [NONE, "none-found"], + [RUMBLE, "not-youtube"], + [WB, "fetch"], + ]); + assert.equal(r.looked.find((x) => x.id === IA)?.via, `archive.org youtube-${IA} / An upload-${IA}.mp4`); + assert.match(r.looked.find((x) => x.id === WB)?.via ?? "", /^the Wayback Machine/); + assert.deepEqual(r.items.map((i) => [i.id, i.copy.from]), [[IA, "archive.org"], [WB, "wayback"]]); + assert.equal(await loadCopyAttempts(path.join(c.alpha, "data", NONE)), null, "a dry run records nothing"); + let started = 0; + const run = await runFindWholeCopies({ + paths: c.paths, + scope: { siteId: "jx" }, + gone: "no-transcript", + dryRun: true, + deps: f.deps, + startFetch: async () => void started++, + }); + assert.equal(run.items.length, 2); + assert.equal(started, 0, "a dry run starts no fetch"); + } finally { + await f.close(); + await c.close(); + } +}); + +test("a run: none-found recorded (and then left out), ONE fetch of every copy found; max caps the lookups, not the non-YouTube ones", async () => { + const c = await corpus(); + const f = await fakes(); + try { + const fetches: FetchCopyItem[][] = []; + const r = await runFindWholeCopies({ + paths: c.paths, + scope: { slug: "alpha" }, + gone: "no-transcript", + max: 2, + deps: f.deps, + startFetch: async (items) => { + fetches.push(items); + return "job-1"; + }, + }); + // Alpha's untranscribed, in id order: IA, NONE (two lookups), then RUMBLE + // (no lookup), then WB left by max. + assert.deepEqual(r.looked.map((x) => [x.id, x.outcome]), [[IA, "fetch"], [NONE, "none-found"], [RUMBLE, "not-youtube"]]); + assert.equal(r.left, 1); + assert.equal(r.fetch, "job-1"); + assert.deepEqual(fetches.map((items) => items.map((i) => i.id)), [[IA]]); + const none = await loadCopyAttempts(path.join(c.alpha, "data", NONE)); + assert.equal(none?.attempts?.[0]?.outcome, "none-found"); + assert.match(none?.attempts?.[0]?.detail ?? "", /wayback none/); + // The next run leaves NONE out (a recent terminal attempt) and reaches WB. + const again = await findWholeCopies({ paths: c.paths, scope: { slug: "alpha" }, gone: "no-transcript", max: 5, deps: f.deps }); + assert.ok(!again.looked.some((x) => x.id === NONE)); + assert.ok(again.skipped.recent.some((x) => x.id === NONE)); + assert.ok(again.looked.some((x) => x.id === WB && x.outcome === "fetch")); + } finally { + await f.close(); + await c.close(); + } +}); + +test("archive.org refusing stops the run there; a cancelled run starts no fetch", async () => { + const c = await corpus(); + const wb = await startFakeWayback({ videos: [] }); + const ia = await startFakeArchiveOrg({ items: [MIRROR], busyTimes: 50 }); + try { + const deps = { + wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }), + archive: new ArchiveOrgClient({ fetch: ia.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }), + now: () => NOW, + }; + const r = await findWholeCopies({ paths: c.paths, scope: { slug: "alpha" }, gone: "no-transcript", deps }); + assert.equal(r.looked.length, 1); + assert.equal(r.looked[0]!.outcome, "error"); + assert.match(r.stopped ?? "", /archive.org kept refusing/); + assert.equal(await loadCopyAttempts(path.join(c.alpha, "data", IA)), null, "an error is not an attempt"); + const ctl = new AbortController(); + ctl.abort(); + let started = 0; + await runFindWholeCopies({ paths: c.paths, scope: { slug: "alpha" }, gone: "no-transcript", signal: ctl.signal, deps, startFetch: async () => void started++ }); + assert.equal(started, 0); + } finally { + await wb.close(); + await ia.close(); + await c.close(); + } +}); diff --git a/common/ytdlp/fetchCopyManaged.test.ts b/common/ytdlp/fetchCopyManaged.test.ts @@ -0,0 +1,121 @@ +// fetchCopyManaged (release 31, lane C) against a fake yt-dlp: a gone video's +// whole audio from a copy lands in its OWN record as audio.<fmt> — the +// record's metadata untouched, no cookies or channel args sent to archive.org, +// the scratch never left behind, the file tiered when the channel has a media +// tier — and a failure is classified as every fetch's is. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/fetchCopyManaged.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, readlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { COPY_PART_BASENAME, fetchCopyManaged, holdsMedia } from "./fetchCopyManaged"; +import { FetchWindowError } from "./fetchWindowManaged"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetchcopy-")); +const BIN = path.join(ROOT, "fake-ytdlp.mjs"); +const ARGS_LOG = path.join(ROOT, "argv.jsonl"); +process.env.FAKE_ARGS_LOG = ARGS_LOG; + +// FAKE_MODE=ok: the download, then the extraction (the source container left +// behind as a stray, which the caller clears). =gone: the copy's 404. +// =ratelimit: a 429. =noout: exit 0 with nothing written. +await writeFile( + BIN, + `#!/usr/bin/env node +import { appendFileSync, writeFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n"); +const mode = process.env.FAKE_MODE; +const out = args[args.indexOf("-o") + 1]; +const fmt = args[args.indexOf("--audio-format") + 1]; +if (mode === "gone") { process.stderr.write("ERROR: [generic] x: Unable to download webpage: HTTP Error 404: Not Found\\n"); process.exit(1); } +if (mode === "ratelimit") { process.stderr.write("ERROR: [generic] x: HTTP Error 429: Too Many Requests\\n"); process.exit(1); } +if (mode === "noout") process.exit(0); +writeFileSync(out.replace("%(ext)s", "webm"), "video bytes"); +writeFileSync(out.replace("%(ext)s", fmt), "audio bytes"); +`, +); +await chmod(BIN, 0o755); + +const META = JSON.stringify({ id: "gone0000001", title: "The original's title", upload_date: "20240101", webpage_url: "https://www.youtube.com/watch?v=gone0000001" }); + +async function record(name: string, o: { tier?: boolean } = {}) { + const channelDir = path.join(ROOT, name); + const videoDir = path.join(channelDir, "data", "gone0000001"); + await mkdir(videoDir, { recursive: true }); + if (o.tier) await mkdir(path.join(channelDir, "media")); + await writeFile(path.join(videoDir, "metadata.info.json"), META); + return videoDir; +} + +const WAYBACK = { from: "wayback" as const, url: "https://web.archive.org/web/20240102030405/https://www.youtube.com/watch?v=gone0000001" }; + +function opts(videoDir: string, config: Partial<ChannelConfig> = {}) { + return { + paths: { ytdlpBin: BIN } as unknown as Paths, + channelConfig: { cookiesFromBrowser: "firefox", ytdlpExtraArgs: ["--write-info-json"], ...config } as ChannelConfig, + videoDir, + videoId: "gone0000001", + copy: WAYBACK, + onLog: () => {}, + signal: new AbortController().signal, + }; +} + +async function lastArgv(): Promise<string[]> { + const lines = (await readFile(ARGS_LOG, "utf8")).trim().split("\n"); + return JSON.parse(lines.at(-1)!) as string[]; +} + +test("the copy's audio lands as the record's audio.<fmt>; metadata untouched; no cookies or channel args; no scratch left", async () => { + process.env.FAKE_MODE = "ok"; + const dir = await record("ok"); + const r = await fetchCopyManaged(opts(dir, { audioFormat: "m4a" } as Partial<ChannelConfig>)); + assert.equal(r.audioFile, "audio.m4a"); + assert.equal(await readFile(path.join(dir, "audio.m4a"), "utf8"), "audio bytes"); + assert.equal(await readFile(path.join(dir, "metadata.info.json"), "utf8"), META, "the original's metadata stays"); + assert.deepEqual((await readdir(dir)).sort(), ["audio.m4a", "metadata.info.json"], "the scratch and the stray container are gone"); + const argv = await lastArgv(); + assert.ok(!argv.join(" ").includes("--cookies-from-browser"), "no cookies to a copy"); + assert.ok(!argv.includes("--write-info-json"), "the channel's extra args are not sent"); + assert.deepEqual(argv.slice(argv.indexOf("-f"), argv.indexOf("-f") + 5), ["-f", "ba/b", "-x", "--audio-format", "m4a"]); + assert.ok(argv.indexOf("--no-write-info-json") < argv.indexOf("-o")); + assert.equal(argv[argv.indexOf("-o") + 1], path.join(dir, `${COPY_PART_BASENAME}.%(ext)s`)); + assert.equal(argv.at(-1), WAYBACK.url); +}); + +test("a channel with a media tier: the audio is tiered (a relative link in data/<id>/)", async () => { + process.env.FAKE_MODE = "ok"; + const dir = await record("tiered", { tier: true }); + await fetchCopyManaged(opts(dir)); + const st = await lstat(path.join(dir, "audio.mp3")); + assert.ok(st.isSymbolicLink(), "audio.mp3 is the tier's link"); + assert.equal(await readlink(path.join(dir, "audio.mp3")), "../../media/gone0000001/audio.mp3"); +}); + +test("a failure is classified (the copy's 404 per-video, a 429 a rate limit) and leaves nothing; success with no file throws", async () => { + const dir = await record("fail"); + process.env.FAKE_MODE = "gone"; + await assert.rejects(fetchCopyManaged(opts(dir)), (e: unknown) => e instanceof FetchWindowError && /404/.test(e.message)); + process.env.FAKE_MODE = "ratelimit"; + await assert.rejects(fetchCopyManaged(opts(dir)), (e: unknown) => e instanceof FetchWindowError && e.failureClass === "rate_limit"); + process.env.FAKE_MODE = "noout"; + await assert.rejects(fetchCopyManaged(opts(dir)), /wrote no mp3 audio/); + assert.deepEqual(await readdir(dir), ["metadata.info.json"]); +}); + +test("a record already holding audio is never fetched over; holdsMedia names audio, a source container, a saved-video pointer", async () => { + process.env.FAKE_MODE = "ok"; + const dir = await record("held"); + await writeFile(path.join(dir, "audio.opus"), "x"); + await assert.rejects(fetchCopyManaged(opts(dir)), /already holds audio/); + assert.equal(holdsMedia(["metadata.info.json", "audio.mp3"]), true); + assert.equal(holdsMedia(["source-media.mp4"]), true); + assert.equal(holdsMedia(["saved-video.json"]), true); + assert.equal(holdsMedia(["metadata.info.json", "audio.copy-part.mp3", "audio.mp3.part", "transcript.en.vtt"]), false); +}); diff --git a/common/ytdlp/fetchCopyManaged.ts b/common/ytdlp/fetchCopyManaged.ts @@ -0,0 +1,158 @@ +// FETCH A GONE VIDEO'S WHOLE AUDIO FROM A COPY into its OWN record (release 31, +// lane C). +// +// find-copy's scope mode found a copy of a deleted or private YouTube upload — +// the Wayback Machine holding the video, or an archive.org mirror of it +// (publish/findCopy.ts) — and fetch-copies (controller/fetchCopies.ts) brings +// the audio home: `data/<id>/audio.<fmt>` of the ORIGINAL record, where the +// transcription lane finds it like any other downloaded audio +// (channelSnapshot's downloadedNoTranscript; the lane does not ask whether the +// platform still serves the video). +// +// AN EXPLICIT RECORD, like fetchWindowManaged: the caller names the video dir, +// so a Wayback replay URL or an archive.org file URL — whose own ids are not +// the record's — never decides where the bytes land. +// +// WHAT IT DELIBERATELY DOES NOT DO: write metadata.info.json, subtitles, a +// thumbnail or an archive line. The record's metadata is the ORIGINAL's (its +// title, date and page stay; a copy's are often worse — release 24's +// persist-provenance rule), so this is not downloadOneManaged, whose prefetch +// rewrites that file from whatever the URL's extractor says. The argv is +// assembled here, in full, with the writers negated last. +// +// AUDIO ONLY: `-f ba/b` (a Wayback copy or a mirror is usually ONE file of +// unknown height holding both streams; `b` takes it) and yt-dlp's own +// extraction (`-x --audio-format <the channel's audioFormat>`), the source +// container discarded. The file is written under a two-segment scratch name +// (`audio.copy-part.<ext>`, which no reader takes for finished audio: +// lib/mediaFiles.ts isRealAudioFile) and renamed into place, then handed to the +// media tier's hook (lib/mediaTier-server.ts) like every finished media file. +// +// NO COOKIES and none of the channel's platform args or extra args: the copy +// is archive.org's, not the channel's platform's, and the channel's browser +// cookies have no business going to it. Paced like archive.org's clients +// (`--sleep-requests 2`). + +import path from "node:path"; +import { readdir, rename, rm, stat } from "node:fs/promises"; +import { + classifyDownloadFailure, + parseUnavailableFromStderr, +} from "../lib/availability"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; +import type { ClipCopy } from "../lib/clipWindow"; +import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles"; +import { SAVED_VIDEO_POINTER_FILENAME } from "../lib/savedVideo"; +import { tierMediaFile } from "../lib/mediaTier-server"; +import { runOneYtdlp } from "./runOneYtdlp"; +import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged"; +import { FetchWindowError } from "./fetchWindowManaged"; + +// The scratch base the download and the extraction write under. +export const COPY_PART_BASENAME = "audio.copy-part"; + +// archive.org's own pace (lib/archiveOrgClient.ts: 2 s between requests). +export const COPY_SLEEP_REQUESTS_SECONDS = 2; + +export type FetchCopyOpts = { + paths: Paths; + channelConfig: ChannelConfig; + // channels/<slug>/data/<id> — the ORIGINAL record's directory. + videoDir: string; + videoId: string; + copy: ClipCopy; + onLog: (s: string) => void; + signal: AbortSignal; +}; + +export type FetchCopyResult = { + // `audio.<fmt>`, in the video dir (a tier link when the channel has a tier). + audioFile: string; + bytes: number; + args: string[]; +}; + +// Whether a video dir's entries already hold its audio or video: finished +// audio, a persisted source container, or a saved-video pointer. A copy is +// never fetched over any of them. +export function holdsMedia(entries: readonly string[]): boolean { + return entries.some((e) => isRealAudioFile(e) || isSourceMediaFile(e) || e === SAVED_VIDEO_POINTER_FILENAME); +} + +export function copyAudioFormat(config: ChannelConfig): string { + return config.audioFormat ?? "mp3"; +} + +export function fetchCopyArgs(videoDir: string, copy: ClipCopy, audioFormat: string): string[] { + return [ + "--ignore-config", + "--no-playlist", + "--sleep-requests", + String(COPY_SLEEP_REQUESTS_SECONDS), + "-f", + "ba/b", + "-x", + "--audio-format", + audioFormat, + ...FULL_LOG_PROGRESS_ARGS, + "--no-write-info-json", + "--no-write-description", + "--no-write-thumbnail", + "--no-write-subs", + "--no-write-auto-subs", + "--no-download-archive", + "-o", + path.join(videoDir, `${COPY_PART_BASENAME}.%(ext)s`), + "--", + copy.url, + ]; +} + +async function scratchFiles(videoDir: string): Promise<string[]> { + return (await readdir(videoDir).catch(() => [] as string[])).filter((f) => f.startsWith(`${COPY_PART_BASENAME}.`)); +} + +async function clearScratch(videoDir: string): Promise<void> { + for (const f of await scratchFiles(videoDir)) await rm(path.join(videoDir, f), { force: true }).catch(() => {}); +} + +export async function fetchCopyManaged(opts: FetchCopyOpts): Promise<FetchCopyResult> { + const { videoDir } = opts; + const fmt = copyAudioFormat(opts.channelConfig); + const audioFile = `audio.${fmt}`; + const existing = (await readdir(videoDir).catch(() => [] as string[])).filter(isRealAudioFile); + if (existing.length > 0) { + throw new Error(`${opts.videoId} already holds audio (${existing.join(", ")}); nothing is fetched over it`); + } + await clearScratch(videoDir); + const args = fetchCopyArgs(videoDir, opts.copy, fmt); + const outcome = await runOneYtdlp( + { ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal }, + videoDir, + args, + ); + if (outcome.exitCode !== 0) { + await clearScratch(videoDir); + const tail = outcome.stderrTail.trim().split("\n").slice(-4).join(" / "); + const availability = parseUnavailableFromStderr(outcome.stderrTail); + throw new FetchWindowError( + `yt-dlp failed fetching the ${opts.copy.from} copy of ${opts.videoId} (exit ${outcome.exitCode ?? "null"}): ${tail}`, + classifyDownloadFailure(outcome.stderrTail, availability), + availability, + ); + } + // The extraction's output: `audio.copy-part.<fmt>`. Anything else left is + // the source container yt-dlp kept or a stray, and goes. + const produced = `${COPY_PART_BASENAME}.${fmt}`; + const st = await stat(path.join(videoDir, produced)).catch(() => null); + if (!st?.isFile() || st.size === 0) { + await clearScratch(videoDir); + throw new Error(`yt-dlp reported success but wrote no ${fmt} audio for ${opts.videoId}`); + } + await rename(path.join(videoDir, produced), path.join(videoDir, audioFile)); + await clearScratch(videoDir); + await tierMediaFile(videoDir, audioFile, { onLog: opts.onLog }); + opts.onLog(`Fetched the ${opts.copy.from} copy of ${opts.videoId} into ${audioFile} (${st.size} bytes).\n`); + return { audioFile, bytes: st.size, args }; +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **find-copy can bring a deleted or private video's whole audio home, so it gets transcribed.** `pnpm ops find-copy --json '{"siteId":"<site>","gone":"no-transcript","dryRun":true}'` (or `{"slug":"<channel>", …}`) lists every gone video of the site's channels (or of one channel) that has no audio and no transcript, and the copy each would use: the Wayback Machine when it holds the video, else an archive.org mirror of the upload. `"gone":"all"` takes the transcribed ones too, after the others. Without `dryRun` it looks up at most `max` videos (10 by default, at most 200) and starts one **Fetch copies** job on archive.org's download queue, which fetches each copy's audio into the video's own record as `audio.<format>`, one at a time with a pause between them; the transcription lane then picks it up like any downloaded audio. The video's title, date and page stay the original's. Its page says **Audio from a copy:** and links the Wayback capture (with its date) or the archive.org item, where the Wayback or archive.org line used to be. A video neither archive holds is noted in its `copy-attempts.json` and left out of the next 30 days of runs, as is one whose copy failed at its source; `"retryFailed": true` asks again. Needs a restart of the editor. - **A frame scan's timeline reads like the stream.** One tournament stays one tournament until the streamer busts: a hand description, a player's name or a misread of the title no longer starts a new one, and the tournament is named by the title most frames agree on. A stack read mid-hand (chips in the pot) or misread no longer makes a double-up or a big loss; players left come only from the client's own "position N of M" or the log's finishing places, so a table's seats are not the field and no final table appears from them; the big blind is the log's "Blinds are now", so a stack is never 700 big blinds by a misread; "won" banners on other players' hands are gone. A frame and a spoken number that disagree are flagged, and a flagged reading makes no event. **Re-derive** an existing scan with no model call: `pnpm ops frame-scan --json '{"slug":"<channel>","id":"<video>","rederive":true}'`, or `archilyzer frames rederive <channel>/<video> --dry` to see what would change. Needs a restart of the editor. - **Retrying a corrupt full source downloads it again.** A video whose download completed with malformed audio (Odysee's intermittent AAC, on a channel with the audio check) kept its file, and that file made every retry say "Nothing to fetch". A retry of the **corrupt full sources** bucket — the new card on the channel's Download stage, or `pnpm ops retry-bucket --json '{"slug": "<channel>", "bucket": "corruptFullSource"}'` — now sets the kept file aside and downloads again: a clean result replaces it; a malformed one keeps whichever copy decodes longer; a download that fails (a 429, the network) puts the kept file back and the video stays in the bucket, with the attempt recorded. Each retry is recorded in the video's `download-outcome.json`. Needs a restart of the editor. - **A damaged recording is transcribed for what decodes, instead of not at all.** Transcribing a corrupt full source used to fail at the first bad stretch. It is now decoded with error tolerance, with the stretches that will not decode kept as silence of their own length, so every line of the transcript is at its true time in the recording; with parakeet, a window that still fails is skipped and noted. The transcript is marked **salvaged**: the video page says how much decoded and which stretches have no transcript, and the channel's report lists it under **salvaged transcript**. It happens on its own for a corrupt full source; `pnpm ops transcribe-one --json '{"slug": "<channel>", "id": "<video>", "salvage": true}'` asks for it on any video (`false` turns it off). When a later retry downloads the recording clean, the salvaged transcript is removed so the recording is transcribed again in full. On the sites, a salvaged transcript's video page says "Partial transcript: N of M min decoded", and the MCP's `get_transcript` and `get_video_metadata` say it is partial. Needs a restart of the editor; the sites show it after their next build. diff --git a/editor/app/api/ops/_research.test.ts b/editor/app/api/ops/_research.test.ts @@ -101,3 +101,33 @@ test("find-copy: exactly one of article, articles, siteId; an unknown one is ref assert.match(String(noSite.body.error), /No site "no-such-site"/); assert.deepEqual(await corpus.listJobIds(), before, "nothing was queued"); }); + +// Release 31 (lane C): find-copy's scope mode — `{slug | siteId, gone}` — +// refused at the door before any lookup. +test("find-copy scope mode: a known gone scope, one of slug or siteId, max at most 200, an existing channel", async () => { + const find = await route("find-copy"); + const before = await corpus.listJobIds(); + const badGone = await callPost(find, { slug: "test-youtube", gone: "some" }); + assert.equal(badGone.status, 400); + assert.match(String(badGone.body.error), /"gone" must be one of no-transcript, all/); + const both = await callPost(find, { slug: "test-youtube", siteId: "x", gone: "all" }); + assert.equal(both.status, 400); + assert.match(String(both.body.error), /with "gone", send one of "slug"/); + const withArticle = await callPost(find, { article: "a", slug: "test-youtube", gone: "all" }); + assert.equal(withArticle.status, 400); + const big = await callPost(find, { slug: "test-youtube", gone: "all", max: 201 }); + assert.equal(big.status, 400); + assert.match(String(big.body.error), /"max" must be at most 200/); + const zero = await callPost(find, { slug: "test-youtube", gone: "all", max: 0 }); + assert.equal(zero.status, 400); + const noChannel = await callPost(find, { slug: "no-such-channel", gone: "no-transcript", dryRun: true }); + assert.equal(noChannel.status, 400); + assert.match(String(noChannel.body.error), /No channel "no-such-channel"/); + const noSite = await callPost(find, { siteId: "no-such-site", gone: "no-transcript" }); + assert.equal(noSite.status, 400); + assert.match(String(noSite.body.error), /No site "no-such-site"/); + const slugAlone = await callPost(find, { slug: "test-youtube" }); + assert.equal(slugAlone.status, 400); + assert.match(String(slugAlone.body.error), /"slug" and "max" go with "gone"/); + assert.deepEqual(await corpus.listJobIds(), before, "nothing was queued"); +}); diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts @@ -1,5 +1,6 @@ -import { findCopyAction } from "../../../channels/[slug]/videos/findCopyAction"; -import { OpsInputError, jobResponse, ops, optBool, optString } from "../_lib"; +import { findCopyAction, findWholeCopiesAction } from "../../../channels/[slug]/videos/findCopyAction"; +import { FIND_COPY_MAX_LIMIT, GONE_SCOPES, type GoneScope } from "yt-dlp-transcript-common/publish/findCopy"; +import { OpsInputError, jobResponse, ops, optBool, optPositiveInt, optString } from "../_lib"; export const dynamic = "force-dynamic"; @@ -22,11 +23,50 @@ export const dynamic = "force-dynamic"; // `@@find-copy {recordings: [{slug, id, gone, watchUrl, youtubeId, windows, // failedBefore, tried, copy?, outcome}], items, stopped?, fetchJobId?, // refused?}`; `--wait` follows it. +// +// POST { slug } | { siteId }, gone: "no-transcript" | "all", dryRun?, max?, +// retryFailed? -> { ok, jobId } — THE SCOPE MODE (release 31): every gone +// video of the channel (or of the site's channels) with no audio or video +// (and, for "no-transcript", no transcript), at most `max` (default 10, at +// most 200) looked up per run, the copies' WHOLE audio fetched into each +// video's own record by ONE fetch-copies job (archive.org's download queue), +// so the transcription lane transcribes it. A terminal attempt (none found, +// a failed copy) in the last 30 days keeps a video out unless `retryFailed`. +// `dryRun` looks (paced lookups) and records and fetches nothing. The log ends +// with `@@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, +// looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, +// via?, outcome}], left, items, stopped?, fetchJobId?, refused?}`. export async function POST(request: Request) { - return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed"], async (body) => { + return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed", "slug", "gone", "max"], async (body) => { const article = optString(body, "article")?.trim(); const siteId = optString(body, "siteId")?.trim(); const articles = optBool(body, "articles") === true; + const gone = optString(body, "gone"); + if (gone !== undefined) { + if (!(GONE_SCOPES as readonly string[]).includes(gone)) { + throw new OpsInputError(`"gone" must be one of ${GONE_SCOPES.join(", ")}`); + } + const slug = optString(body, "slug")?.trim(); + if ([slug, siteId].filter(Boolean).length !== 1 || article || articles) { + throw new OpsInputError('with "gone", send one of "slug" (a channel) or "siteId" — not "article" or "articles"'); + } + const max = optPositiveInt(body, "max"); + if (max !== undefined && max > FIND_COPY_MAX_LIMIT) { + throw new OpsInputError(`"max" must be at most ${FIND_COPY_MAX_LIMIT}`); + } + return jobResponse( + await findWholeCopiesAction({ + ...(slug ? { slug } : { siteId: siteId! }), + gone: gone as GoneScope, + dryRun: optBool(body, "dryRun") === true, + ...(max !== undefined ? { max } : {}), + retryFailed: optBool(body, "retryFailed") === true, + }), + ); + } + if (optString(body, "slug") !== undefined || body.max !== undefined) { + throw new OpsInputError('"slug" and "max" go with "gone" (the scope mode)'); + } if ([article, siteId, articles || undefined].filter(Boolean).length !== 1) { throw new OpsInputError('send one of "article" (an article id), "articles": true or "siteId"'); } diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -16,6 +16,7 @@ import { loadArchiveOrgProvenance } from "yt-dlp-transcript-common/lib/archiveOr import type { ArchiveOrgProvenance } from "yt-dlp-transcript-common/lib/archiveOrg"; import { loadWaybackProvenance } from "yt-dlp-transcript-common/lib/wayback-server"; import { waybackCaptureDate, type WaybackProvenance } from "yt-dlp-transcript-common/lib/wayback"; +import { latestFetchedCopy, loadCopyAttempts, type CopyAttempt } from "yt-dlp-transcript-common/lib/copyAttempts-server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { readVideoMetadataForDisplay, @@ -150,6 +151,9 @@ export default async function VideoDetailPage({ const archiveOrg = await loadArchiveOrgProvenance(videoDir); // What a Wayback Machine copy is a copy of (lib/wayback-server.ts). const wayback = await loadWaybackProvenance(videoDir); + // A gone video whose audio came from a copy (release 31, find-copy's + // scope mode): the newest `fetched` attempt in copy-attempts.json. + const audioCopy = latestFetchedCopy(await loadCopyAttempts(videoDir)); // The windows another tool asked this editor to fetch. One readdir of // data/<id>/clips/ plus a stat per file — and no per-CHANNEL count anywhere, // because that would be a walk of every video dir to draw one number. @@ -208,6 +212,7 @@ export default async function VideoDetailPage({ savedVideo, archiveOrg, wayback, + audioCopy, clipWindows, vttProvenance, coverage, @@ -239,6 +244,7 @@ export default async function VideoDetailPage({ savedVideo, archiveOrg, wayback, + audioCopy, clipWindows, vttProvenance, coverage, @@ -305,8 +311,16 @@ export default async function VideoDetailPage({ </span> )} </div> - {archiveOrg && <ArchiveOrgProvenanceLine prov={archiveOrg} />} - {wayback && <WaybackProvenanceLine prov={wayback} />} + {/* The audio of a gone video fetched from a copy takes the copy's + provenance line: the record is the original, its audio the copy's. */} + {audioCopy ? ( + <AudioCopyLine copy={audioCopy} /> + ) : ( + <> + {archiveOrg && <ArchiveOrgProvenanceLine prov={archiveOrg} />} + {wayback && <WaybackProvenanceLine prov={wayback} />} + </> + )} {meta.description && ( <details className="text-sm"> <summary className="cursor-pointer text-muted-foreground hover:text-foreground"> @@ -448,6 +462,32 @@ function WaybackProvenanceLine({ prov }: { prov: WaybackProvenance }) { ); } +// "Audio from a copy: Wayback Machine, <capture date>" or "… archive.org +// <identifier>", linking the copy — in the slot (and under the label) of the +// source's own provenance line. +function AudioCopyLine({ copy }: { copy: CopyAttempt }) { + const link = "underline hover:text-foreground"; + const wayback = copy.source === "wayback"; + const text = wayback + ? `Wayback Machine${copy.captureTs ? `, ${waybackCaptureDate(copy.captureTs)}` : ""}` + : `archive.org ${copy.identifier ?? ""}`.trim(); + return ( + <div + aria-label={wayback ? "Wayback provenance" : "archive.org provenance"} + className="text-sm text-muted-foreground" + > + Audio from a copy:{" "} + {copy.url ? ( + <a href={copy.url} target="_blank" rel="noreferrer" className={`${link} break-all`}> + {text} + </a> + ) : ( + text + )} + </div> + ); +} + function formatUploadDate(s: string): string { // yt-dlp emits YYYYMMDD. Render as YYYY-MM-DD; pass through anything else. if (/^\d{8}$/.test(s)) { diff --git a/editor/app/channels/[slug]/videos/findCopyAction.ts b/editor/app/channels/[slug]/videos/findCopyAction.ts @@ -2,12 +2,25 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { diskGate } from "yt-dlp-transcript-common/lib/diskSpace"; +import { formatBytes } from "yt-dlp-transcript-common/lib/format"; 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 { FIND_COPY_RESULT_MARKER, runFindCopy } from "yt-dlp-transcript-common/publish/findCopy"; +import { + FIND_COPY_RESULT_MARKER, + runFindCopy, + runFindWholeCopies, + type GoneScope, + type WholeCopyScope, +} from "yt-dlp-transcript-common/publish/findCopy"; +import { fetchCopies, type FetchCopyItem } from "yt-dlp-transcript-common/controller/fetchCopies"; +import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { requestChannelSnapshot } from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { fetchWindowsJobAction } from "./fetchWindowsAction"; +import { safeRevalidate } from "../../../lib/safeRevalidate"; // 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) — AS A JOB @@ -84,3 +97,126 @@ export async function findCopyAction(req: { }, }); } + +// ─── The scope mode (release 31, lane C): every gone video's WHOLE audio ─── +// +// `{slug | siteId, gone: "no-transcript" | "all", dryRun?, max?, retryFailed?}` +// (publish/findCopy.ts findWholeCopies): a find-copy job looks for a copy of +// each gone video of the channel or the site's channels with no media, at most +// `max` per run; the copies found go to ONE fetch-copies job on the archive.org +// download queue (one stream to archive.org, behind its imports), which brings +// each one's audio into its own record as `audio.<fmt>`. Its log ends with +// `@@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked, +// left, items, stopped?, fetchJobId?, refused?}`. + +// The archive.org download queue: whole files, one at a time. +const FETCH_COPIES_QUEUE = platformQueueKey("archiveorg"); + +export async function findWholeCopiesAction(req: { + slug?: string; + siteId?: string; + gone: GoneScope; + dryRun?: boolean; + max?: number; + retryFailed?: boolean; +}): Promise<StreamActionResult> { + const paths = getPaths(); + let scope: WholeCopyScope; + if (req.slug) { + if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a valid channel slug` }; + if (!(await readChannelConfig(paths, req.slug).catch(() => null))) return { ok: false, error: `No channel "${req.slug}"` }; + scope = { slug: req.slug }; + } else if (req.siteId) { + if (!isValidSiteId(req.siteId)) return { ok: false, error: `"${req.siteId}" is not a valid site id` }; + if (!listSiteIds(paths).includes(req.siteId)) return { ok: false, error: `No site "${req.siteId}"` }; + scope = { siteId: req.siteId }; + } else { + return { ok: false, error: 'send "slug" or "siteId" with "gone"' }; + } + return runManagedFunction({ + kind: "find-copy", + queueKey: FIND_COPY_QUEUE, + paths, + fn: async (onLog, signal) => { + let refused: string | undefined; + const r = await runFindWholeCopies({ + paths, + scope, + gone: req.gone, + dryRun: req.dryRun, + max: req.max, + retryFailed: req.retryFailed, + signal, + onLog, + startFetch: async (items) => { + const res = await fetchCopiesJobAction({ items, requestedBy: "find-copy" }); + if (!res.ok) { + refused = res.error; + return null; + } + void res.stream.cancel().catch(() => {}); + onLog(`find-copy: fetch-copies job ${res.jobId} fetches the audio of ${items.length} gone video(s) from the copies found.`); + return res.jobId; + }, + }); + const { fetch: fetchJobId, ...found } = r; + onLog( + `${FIND_COPY_RESULT_MARKER}${JSON.stringify({ + ...found, + ...(typeof fetchJobId === "string" ? { fetchJobId } : {}), + ...(refused ? { refused } : {}), + })}`, + ); + if (refused) throw new Error(`the fetch was refused: ${refused}`); + if (signal.aborted) throw new Error("cancelled"); + }, + }); +} + +// ONE fetch-copies job (controller/fetchCopies.ts) for a list of gone videos +// and their copies. A list of one channel carries it, so the media guard and +// the report regeneration name it; one spanning channels asks each channel's +// media guard in the controller and asks each changed channel's report here. +export async function fetchCopiesJobAction(req: { + items: FetchCopyItem[]; + requestedBy: string; +}): Promise<StreamActionResult> { + if (req.items.length === 0) return { ok: false, error: "No copies to fetch." }; + const paths = getPaths(); + // A whole file lands on the corpus (or its media) disk: the floor a click asks. + const disk = await diskGate(paths, getSettings(), { mode: "manual", dir: paths.channelsDir }); + if (!disk.ok) { + return { + ok: false, + error: + `Low disk space: ${formatBytes(disk.freeBytes)} free, ` + + `${formatBytes(disk.thresholdBytes)} required. Free up space or lower the floor in Settings.`, + }; + } + const slugs = [...new Set(req.items.map((i) => i.slug))]; + return runManagedFunction({ + kind: "fetch-copies", + queueKey: FETCH_COPIES_QUEUE, + paths, + ...(slugs.length === 1 ? { channelSlug: slugs[0] } : {}), + fn: async (onLog, signal, setProgress, ctx) => { + onLog(`Requested by ${req.requestedBy}.`); + const result = await fetchCopies({ + paths, + items: req.items, + onLog, + signal, + drainSignal: ctx.drainSignal, + setProgress, + }); + // The transcription lane draws from the snapshot: each channel that + // gained audio has its report regenerated (downloadedNoTranscript). + for (const slug of new Set(result.fetched.map((f) => f.slug))) requestChannelSnapshot(paths, slug); + safeRevalidate([...new Set(result.fetched.map((f) => `/channels/${f.slug}/videos/${f.id}`))]); + if (result.stopped && result.stopped !== "drain" && result.stopped !== "cancel") { + throw new Error(`Stopped (${result.stopped}) with ${result.notAttempted.length} copy(ies) not attempted — run it again later.`); + } + if (result.failed.length > 0) throw new Error(`${result.failed.length} copy(ies) failed to fetch.`); + }, + }); +} diff --git a/editor/e2e/find-copy-whole.spec.ts b/editor/e2e/find-copy-whole.spec.ts @@ -0,0 +1,88 @@ +import { test, expect } from "@playwright/test"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { resetData, testPaths } from "./helpers"; + +// Release 31, lane C: a gone video whose audio find-copy's scope mode fetched +// from a copy says so on its page — "Audio from a copy:" and the copy, in the +// slot (and under the label) of that source's own provenance line, which a +// record that IS a copy keeps. Synthetic records only: the sidecars as +// fetch-copies writes them (controller/fetchCopies.ts). + +const SLUG = "test-youtube"; +const WB_ID = "goneWayback"; +const IA_ID = "goneMirror1"; +const COPY_ID = "isACopy0001"; +const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`; +const WB_URL = `https://web.archive.org/web/20240102030405/${watch(WB_ID)}`; +const IA_URL = `https://archive.org/download/youtube-${IA_ID}/An%20upload-${IA_ID}.mp4`; + +async function goneVideo(id: string, files: Record<string, unknown>) { + const dir = join(testPaths().transcriptsDir, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile( + join(dir, "metadata.info.json"), + JSON.stringify({ id, title: `The original ${id}`, webpage_url: watch(id), extractor_key: "Youtube", duration: 300, upload_date: "20240101" }), + ); + await writeFile( + join(dir, "availability.json"), + JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted", webpageUrl: watch(id), history: [] }), + ); + await writeFile(join(dir, "audio.mp3"), "synthetic audio"); + for (const [name, body] of Object.entries(files)) await writeFile(join(dir, name), JSON.stringify(body)); +} + +const waybackJson = (id: string, ts: string) => ({ + originalUrl: watch(id), + captureTs: ts, + waybackUrl: `https://web.archive.org/web/${ts}/${watch(id)}`, + rawUrl: `https://web.archive.org/web/${ts}id_/${watch(id)}`, +}); + +test("a gone video's audio from a copy: the copy's line; a record that is a copy keeps its own", async ({ page }) => { + await resetData("one-youtube-channel-with-data"); + await goneVideo(WB_ID, { + "wayback.json": waybackJson(WB_ID, "20240102030405"), + "copy-attempts.json": { + failed: [], + attempts: [ + { at: "2026-10-10T00:00:00.000Z", outcome: "none-found", detail: "wayback none; archive.org none" }, + { at: "2026-10-16T00:00:00.000Z", outcome: "fetched", source: "wayback", url: WB_URL, captureTs: "20240102030405", audioFile: "audio.mp3" }, + ], + }, + }); + await goneVideo(IA_ID, { + "archiveorg.json": { + version: 1, + identifier: `youtube-${IA_ID}`, + file: `An upload-${IA_ID}.mp4`, + itemUrl: `https://archive.org/details/youtube-${IA_ID}`, + item: { title: `An upload ${IA_ID}`, collections: [] }, + fetchedAt: "2026-10-16T00:00:00.000Z", + }, + "copy-attempts.json": { + failed: [], + attempts: [ + { at: "2026-10-16T00:00:00.000Z", outcome: "fetched", source: "archive.org", url: IA_URL, identifier: `youtube-${IA_ID}`, file: `An upload-${IA_ID}.mp4`, audioFile: "audio.mp3" }, + ], + }, + }); + // A record imported FROM a Wayback capture, no copy attempt: its own line. + await goneVideo(COPY_ID, { "wayback.json": waybackJson(COPY_ID, "20230506070809") }); + + await page.goto(`/channels/${SLUG}/videos/${WB_ID}`); + const wb = page.getByLabel("Wayback provenance"); + await expect(wb).toHaveText("Audio from a copy: Wayback Machine, 2024-01-02"); + await expect(wb.getByRole("link", { name: "Wayback Machine, 2024-01-02" })).toHaveAttribute("href", WB_URL); + await expect(page.getByText("Archived copy (")).toHaveCount(0); + + await page.goto(`/channels/${SLUG}/videos/${IA_ID}`); + const ia = page.getByLabel("archive.org provenance"); + await expect(ia).toHaveText(`Audio from a copy: archive.org youtube-${IA_ID}`); + await expect(ia.getByRole("link", { name: `archive.org youtube-${IA_ID}` })).toHaveAttribute("href", IA_URL); + await expect(page.getByText("Archived on archive.org:")).toHaveCount(0); + + await page.goto(`/channels/${SLUG}/videos/${COPY_ID}`); + await expect(page.getByLabel("Wayback provenance")).toContainText("Archived copy (Wayback Machine, 2023-05-06) of"); + await expect(page.getByText("Audio from a copy:")).toHaveCount(0); +}); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9716,3 +9716,38 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri edit makes it the operator's), `frameEvents`, and a top-level `frameScan {profile, file, channel, video, tournaments, overlay: [{clip, points: [{at, …frameTotals}]}]}` no render reads yet. + +## Release 31 lane C: a gone video's whole audio from a copy (verified 2026-10-16, branch `r31/find-copy-all`) + +- **find-copy's scope mode** (`publish/findCopy.ts` `enumerateGoneVideos` / `findWholeCopies` / + `runFindWholeCopies`; `pnpm ops find-copy {slug | siteId, gone: "no-transcript" | "all", dryRun?, max?, + retryFailed?}`): a candidate is a video DIR of the channel (or of `site.json` `channels`, in its order) that holds no + media (`ytdlp/fetchCopyManaged.ts` `holdsMedia`: `audio.<ext>`, `source-media.<ext>`, `saved-video.json`), has no + transcript (`isVideoTranscribed`) for "no-transcript", and is gone by `sourceGoneState`; untranscribed first. The + lookups are the article mode's (`lookForCopy`, shared), at most `max` YouTube ones per run (default 10, ≤ 200; a + non-YouTube record costs none and is listed `not-youtube`). The `{siteId}` body WITHOUT `gone` is still the article + mode (the site's reports). +- **`copy-attempts.json` has two lists** (`lib/copyAttempts-server.ts`): `failed` (release 29, a copy fetch-windows or + fetch-copies failed from at its source — never picked again) and `attempts` (release 31): `{at, outcome: fetched | + none-found | failed, source?: "wayback" | "archive.org", url?, identifier?, file?, captureTs?, audioFile?, detail?, + error?}`, newest 20. Both writers update under the file's lock and keep the other list. The scope mode skips a video + whose NEWEST attempt is terminal (none-found, failed) and younger than `COPY_ATTEMPT_RETRY_DAYS` (30) unless + `retryFailed`; a dry run and a lookup error record nothing. +- **fetch-copies** (job kind, drainable, needsMedia, an ingest kind; queue `platform:archiveorg`; + `controller/fetchCopies.ts`, `ytdlp/fetchCopyManaged.ts`): yt-dlp `-f ba/b -x --audio-format <channel audioFormat, + default mp3>` on the copy's URL, no cookies, none of the channel's platform or extra args, `--sleep-requests 2`, + `-o data/<id>/audio.copy-part.%(ext)s`, renamed to `audio.<fmt>` and tiered (`tierMediaFile`). It never writes + `metadata.info.json`: the record stays the original's. Then `wayback.json` (`ensureWaybackProvenance`, from the URL; + none when the URL has no capture timestamp) or `archiveorg.json` (`ensureArchiveOrgProvenanceSidecar`, the item's + metadata — the standard `ArchiveOrgProvenance`, `mirror` included), and a `fetched` attempt. Paced as platform + `archiveorg` (hold and cooldown before each fetch, a 429 → backoff + stop), 30 s between fetches. +- **A YouTube record can now carry `archiveorg.json` without being archive.org's.** `refreshArchiveOrgRecords` skips + a record whose metadata is not archive.org's (`isArchiveOrgRecordInfo`: extractor `ArchiveOrg` or an archive.org + page). A `wayback.json` on the original makes compose cite it as "Original (may be gone)" + the Wayback copy + (`waybackCitationLinks`), and hides the video page's Refresh metadata (as for any copy). +- **The transcription lane takes the audio as is**: a gone video with `audio.<ext>` is in `downloadedNoTranscript` + (no availability filter there) and so in `backfill.transcription.ids`; it stays in `excludedFromDownload.deleted`. + fetch-copies asks each changed channel's report (`requestChannelSnapshot`). +- **The video page** reads `latestFetchedCopy(copy-attempts.json)`: "Audio from a copy: Wayback Machine, <date>" / + "… archive.org <identifier>", linking the copy, in place of (and under the label of) the source's own provenance + line ("Wayback provenance" / "archive.org provenance"). diff --git a/plans/release-31/find-copy-all.md b/plans/release-31/find-copy-all.md @@ -0,0 +1,96 @@ +# Release 31, lane C — find a copy of every gone video (as shipped) + +Branch `r31/find-copy-all` from `main` `3ef1b558`. Brief: `r31c-brief.md` (the plan of record for this lane). +FACTS: "Release 31 lane C: a gone video's whole audio from a copy". + +## What and why + +find-copy (release 29 E2 and the r29/fix-copy follow-up) fetched only the cited WINDOWS of gone recordings an +article cites. The hole on Jeralyzer is gone videos with no transcript at all. This lane brings a gone video's WHOLE +audio home from its copy — the Wayback Machine holding the video, or an archive.org mirror of the upload — into the +video's own record, where the transcription lane transcribes it like any downloaded audio. + +- **The scope mode** (`publish/findCopy.ts` `enumerateGoneVideos`, `findWholeCopies`, `runFindWholeCopies`): + `pnpm ops find-copy {slug | siteId, gone: "no-transcript" | "all", dryRun?, max?, retryFailed?}`. Candidates are the + video dirs of the channel (or of every channel in `site.json` `channels`, in its order) that hold no media + (`holdsMedia`: finished audio, a `source-media.*` container, a `saved-video.json` pointer), have no transcript for + `no-transcript` (`isVideoTranscribed`), and are gone by THE reading (`sourceGoneState`: deleted or private); + untranscribed first, then (for `all`) the transcribed ones. A video whose newest copy attempt is terminal + (none-found, failed) and younger than `COPY_ATTEMPT_RETRY_DAYS` (30) is left out unless `retryFailed`. A channel + whose text cannot be read is named and skipped. The lookups are the article mode's, factored into `lookForCopy` + (Wayback when it holds the video, then an archive.org mirror of the upload of its length, never a copy that failed + before) — at most `max` YouTube lookups per run (default 10, ceiling 200); a non-YouTube record costs none and is + listed `not-youtube`; archive.org refusing stops the run. Not a dry run: a video neither source holds is recorded + `none-found`, and every copy found goes to ONE fetch-copies job. A dry run asks the same paced questions and + records and fetches nothing. The `{siteId}` body without `gone` is still the article mode (the site's reports). +- **fetch-copies** (new job kind: drainable, needsMedia, an ingest kind, not replayable; queue `platform:archiveorg`; + `controller/fetchCopies.ts`, per item `ytdlp/fetchCopyManaged.ts`): yt-dlp `-f ba/b -x --audio-format <the + channel's audioFormat, default mp3>` on the copy URL, no cookies and none of the channel's platform or extra args, + `--sleep-requests 2`, the writers negated, `-o data/<id>/audio.copy-part.%(ext)s` → renamed `audio.<fmt>` and + tiered (`tierMediaFile`). `metadata.info.json` is never written. Then the copy's provenance through the existing + writers — `wayback.json` (`ensureWaybackProvenance`, from the URL) or `archiveorg.json` + (`ensureArchiveOrgProvenanceSidecar`, the standard `ArchiveOrgProvenance`) — and a `fetched` attempt. A + source-side failure is recorded in `failed` and as a `failed` attempt; ours (the extraction, a disk) is not. Paced + as platform `archiveorg`: hold and cooldown asked before every fetch, a 429 records the backoff and stops the run, + 30 s between fetches. A video holding media by its turn is skipped; each channel's media guard is asked once. The + editor action asks each channel that gained audio for its report (`requestChannelSnapshot`). +- **`copy-attempts.json`** (`lib/copyAttempts-server.ts`): `{failed: [...], attempts?: [{at, outcome: fetched | + none-found | failed, source?, url?, identifier?, file?, captureTs?, audioFile?, detail?, error?}]}`, newest 20 each; + both writers update under the file's lock and keep the other list (release 29's `recordFailedCopy` rewrote the file + with `failed` alone). +- **The transcription lane picks it up**: a gone video with `audio.<ext>` lands in `downloadedNoTranscript` (the + snapshot applies no availability filter there) and so in `backfill.transcription.ids`; `whisperBatch` asks only + "transcribed?" and "downloaded?". It stays in `excludedFromDownload.deleted`. Pinned by a unit test over + `generateChannelSnapshot` (noTranscript → downloadedNoTranscript). +- **The video page**: `latestFetchedCopy(copy-attempts.json)` → "Audio from a copy: Wayback Machine, <capture date>" + or "… archive.org <identifier>", linking the copy, IN PLACE of the source's own provenance line and under its label + (`Wayback provenance` / `archive.org provenance`) — the brief's "extend it rather than add a second". A record that + IS a copy (no fetched attempt) keeps its line. +- **archive.org refresh** (`refreshArchiveOrgRecords`) now skips a record whose metadata is not archive.org's + (`isArchiveOrgRecordInfo`), so a YouTube original carrying a copy's `archiveorg.json` is never re-titled from it. + +| Commit | What | +| --- | --- | +| `243b25c0` | common: the scope mode, `lookForCopy`, fetch-copies (controller + managed fetch), copy-attempts' `attempts`, the job kind, the archive.org refresh guard; tests | +| `f57d1ccf` | editor, scripts: the route's scope mode, `findWholeCopiesAction` / `fetchCopiesJobAction`, the video page's copy line; ops help, COMMANDS.md, CHANGELOG; the route test and `e2e/find-copy-whole.spec.ts` | +| (this commit) | this record, FACTS | + +## Gates (from the worktree root, every heavy step through the shared lock) + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean before each commit. +- common 4362 → 4379/4379 (+17: `lib/copyAttempts.test.ts` +2, `ytdlp/fetchCopyManaged.test.ts` 4, + `controller/fetchCopies.test.ts` 6, `publish/findCopyScope.test.ts` 4, `controller/archiveOrgRefresh.test.ts` +1; + `jobs/jobKinds.test.ts` pins the new kind). `publish/findCopy.test.ts` (the article mode, over the refactored + lookup) unchanged and green. +- editor unit 319 → 320/320 (`_research.test.ts`: the scope mode's refusals at the door, nothing queued). +- `docs cli --check`, `docs files --check`, `docs env --check`: clean (COMMANDS.md regenerated). +- e2e (editor, one spec, through the lock): `find-copy-whole.spec.ts` 1/1 passed (17.2 s; its start-mode build 332 s in the heavy slot, 5 GB cap; 395 s in all). The spec writes the sidecars as fetch-copies does and checks the Wayback and archive.org copy lines, their links, and that a record that IS a Wayback copy keeps "Archived copy (…) of". +- MCP not touched (lane D owns its tool definitions); no settings, env or file-schema doc changed. + +## Rulings and calls + +- **One whole-copy path for both sources, not downloadOneManaged for Wayback.** The brief suggested Wayback "through + downloadOneManaged as today", and also "do not overwrite metadata.info.json from the copy": the managed download's + prefetch rewrites that file from the Wayback extractor's answer (keepProvenanceFields keeps only fields a provenance + writer set — a YouTube original's title and date are not), and it would also fetch subtitles and write an archive + line. So both sources go through `fetchCopyManaged` (audio only, `-x`), which never writes metadata; Wayback's id + unwrapping is not needed because the record is explicit. +- **`archiveorg.json` keeps its one declared shape** (`ArchiveOrgProvenance`, identifier, file, downloadUrl, + fetchedAt and the item's fields) rather than a second, ClipCopy-like shape under the same name, which the existing + coerce would reject (the page line and the refresh read it). The attempt in `copy-attempts.json` carries the + ClipCopy-like fields (source, url, identifier, file, captureTs). +- **`source` uses the file's existing vocabulary** (`"wayback" | "archive.org"`, as `failed` and the windows' + `copy.from`), not the brief's `archiveorg`. +- **No cookies and no channel args to a copy**; pace `--sleep-requests 2` (archive.org's client gap); 30 s between + whole fetches; queue `platform:archiveorg` (one stream to archive.org, behind its imports). +- **Terminal = the NEWEST attempt** (none-found or failed) within 30 days; a lookup error and a dry run record + nothing; a failure on our side is never terminal. +- **A YouTube original with `wayback.json`** is now cited by compose as "Original (may be gone)" plus the Wayback copy + (the existing `waybackCitationLinks`) — the copy plays where the original does not. Nothing is published by this + lane; it takes effect at a site's next compose after a live run. +- `max` counts YouTube lookups; a non-YouTube gone record costs no request and is listed, never fetched. + +## Not done + +- No editor button for the scope mode (ops only, as the article mode). No replay handler for fetch-copies (a re-run of + find-copy is the retry). Nothing ran against the real archives (the orchestrator's live run). diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -108,6 +108,8 @@ // pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}' // pnpm ops find-copy --json '{"article":"demo-article"}' --wait // pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait +// pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait +// pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait // pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait // pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait // pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}' @@ -427,7 +429,8 @@ const ACTIONS = [ // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), // its windows fetched from it as one fetch-windows job ({article} | - // {articles: true} | {siteId}, dryRun?). + // {articles: true} | {siteId}, dryRun?); release 31: {slug | siteId, gone} + // brings every gone video's WHOLE audio home (a fetch-copies job). "wayback-lookup", "find-copy", // GENERATION (release 27 S6): a sweep, a report or video revision, or a @@ -1321,6 +1324,23 @@ export function usage() { " {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.", + ' The scope mode (release 31): {"slug"} | {"siteId"}, "gone":', + ' "no-transcript" | "all", "dryRun"?, "max"? (10, at most 200),', + ' "retryFailed"? -> {jobId}. Every gone (deleted or private) video of the', + " channel, or of the site's channels, that holds no audio or video", + ' ("no-transcript": and no transcript; "all": the transcribed ones too,', + " after) is looked for the same way, at most max per run; a video whose", + " last copy attempt found none or failed in the last 30 days is left out", + ' unless "retryFailed". Each copy\'s WHOLE audio is fetched into the', + " video's own record (audio.<fmt>; its metadata stays the original's, the", + " copy is in wayback.json or archiveorg.json and copy-attempts.json) by", + " ONE fetch-copies job on archive.org's download queue, one at a time;", + " the transcription lane then transcribes it like any downloaded audio.", + " A video neither source holds is recorded none-found. dryRun asks the", + " same (paced) questions and records and fetches nothing. The log ends", + " with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped,", + " looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried,", + " copy?, via?, outcome}], left, items, stopped?, fetchJobId?, refused?}.", "", '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',