Archilyzer · Source

archilyzer

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

commit 6131fcc28046bba80a1e49b17da8db75f34fa824
parent bfe6522daeae596d08f42489bca7833827b32dbc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 01:48:38 -0400

editor, scripts: find-copy's scope mode at the door ({slug | siteId, gone, dryRun?, max?, retryFailed?}) and its fetch-copies job on archive.org's download queue (each changed channel's report asked); the video page's "Audio from a copy" line in the copy's provenance slot; ops help, COMMANDS.md, CHANGELOG; the route's refusals and the e2e spec find-copy-whole

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

Diffstat:
MCOMMANDS.md | 2+-
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+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 22+++++++++++++++++++++-
8 files changed, 363 insertions(+), 8 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/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/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."}' @@ -425,7 +427,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 @@ -1309,6 +1312,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',